io-wq: make buffered file write hashed work map per-ctx
[linux-2.6-microblaze.git] / fs / io-wq.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Basic worker thread pool for io_uring
4  *
5  * Copyright (C) 2019 Jens Axboe
6  *
7  */
8 #include <linux/kernel.h>
9 #include <linux/init.h>
10 #include <linux/errno.h>
11 #include <linux/sched/signal.h>
12 #include <linux/mm.h>
13 #include <linux/sched/mm.h>
14 #include <linux/percpu.h>
15 #include <linux/slab.h>
16 #include <linux/rculist_nulls.h>
17 #include <linux/cpu.h>
18 #include <linux/tracehook.h>
19
20 #include "../kernel/sched/sched.h"
21 #include "io-wq.h"
22
23 #define WORKER_IDLE_TIMEOUT     (5 * HZ)
24
25 enum {
26         IO_WORKER_F_UP          = 1,    /* up and active */
27         IO_WORKER_F_RUNNING     = 2,    /* account as running */
28         IO_WORKER_F_FREE        = 4,    /* worker on free list */
29         IO_WORKER_F_FIXED       = 8,    /* static idle worker */
30         IO_WORKER_F_BOUND       = 16,   /* is doing bounded work */
31 };
32
33 enum {
34         IO_WQ_BIT_EXIT          = 0,    /* wq exiting */
35         IO_WQ_BIT_ERROR         = 1,    /* error on setup */
36 };
37
38 enum {
39         IO_WQE_FLAG_STALLED     = 1,    /* stalled on hash */
40 };
41
42 /*
43  * One for each thread in a wqe pool
44  */
45 struct io_worker {
46         refcount_t ref;
47         unsigned flags;
48         struct hlist_nulls_node nulls_node;
49         struct list_head all_list;
50         struct task_struct *task;
51         struct io_wqe *wqe;
52
53         struct io_wq_work *cur_work;
54         spinlock_t lock;
55
56         const struct cred *cur_creds;
57         const struct cred *saved_creds;
58
59         struct completion ref_done;
60
61         struct rcu_head rcu;
62 };
63
64 #if BITS_PER_LONG == 64
65 #define IO_WQ_HASH_ORDER        6
66 #else
67 #define IO_WQ_HASH_ORDER        5
68 #endif
69
70 #define IO_WQ_NR_HASH_BUCKETS   (1u << IO_WQ_HASH_ORDER)
71
72 struct io_wqe_acct {
73         unsigned nr_workers;
74         unsigned max_workers;
75         atomic_t nr_running;
76 };
77
78 enum {
79         IO_WQ_ACCT_BOUND,
80         IO_WQ_ACCT_UNBOUND,
81 };
82
83 /*
84  * Per-node worker thread pool
85  */
86 struct io_wqe {
87         struct {
88                 raw_spinlock_t lock;
89                 struct io_wq_work_list work_list;
90                 unsigned flags;
91         } ____cacheline_aligned_in_smp;
92
93         int node;
94         struct io_wqe_acct acct[2];
95
96         struct hlist_nulls_head free_list;
97         struct list_head all_list;
98
99         struct wait_queue_entry wait;
100
101         struct io_wq *wq;
102         struct io_wq_work *hash_tail[IO_WQ_NR_HASH_BUCKETS];
103 };
104
105 /*
106  * Per io_wq state
107   */
108 struct io_wq {
109         struct io_wqe **wqes;
110         unsigned long state;
111
112         free_work_fn *free_work;
113         io_wq_work_fn *do_work;
114
115         struct task_struct *manager;
116         struct user_struct *user;
117
118         struct io_wq_hash *hash;
119
120         refcount_t refs;
121         struct completion done;
122
123         struct hlist_node cpuhp_node;
124
125         pid_t task_pid;
126 };
127
128 static enum cpuhp_state io_wq_online;
129
130 static bool io_worker_get(struct io_worker *worker)
131 {
132         return refcount_inc_not_zero(&worker->ref);
133 }
134
135 static void io_worker_release(struct io_worker *worker)
136 {
137         if (refcount_dec_and_test(&worker->ref))
138                 complete(&worker->ref_done);
139 }
140
141 static inline struct io_wqe_acct *io_work_get_acct(struct io_wqe *wqe,
142                                                    struct io_wq_work *work)
143 {
144         if (work->flags & IO_WQ_WORK_UNBOUND)
145                 return &wqe->acct[IO_WQ_ACCT_UNBOUND];
146
147         return &wqe->acct[IO_WQ_ACCT_BOUND];
148 }
149
150 static inline struct io_wqe_acct *io_wqe_get_acct(struct io_worker *worker)
151 {
152         struct io_wqe *wqe = worker->wqe;
153
154         if (worker->flags & IO_WORKER_F_BOUND)
155                 return &wqe->acct[IO_WQ_ACCT_BOUND];
156
157         return &wqe->acct[IO_WQ_ACCT_UNBOUND];
158 }
159
160 static void io_worker_exit(struct io_worker *worker)
161 {
162         struct io_wqe *wqe = worker->wqe;
163         struct io_wqe_acct *acct = io_wqe_get_acct(worker);
164         unsigned flags;
165
166         if (refcount_dec_and_test(&worker->ref))
167                 complete(&worker->ref_done);
168         wait_for_completion(&worker->ref_done);
169
170         preempt_disable();
171         current->flags &= ~PF_IO_WORKER;
172         flags = worker->flags;
173         worker->flags = 0;
174         if (flags & IO_WORKER_F_RUNNING)
175                 atomic_dec(&acct->nr_running);
176         worker->flags = 0;
177         preempt_enable();
178
179         if (worker->saved_creds) {
180                 revert_creds(worker->saved_creds);
181                 worker->cur_creds = worker->saved_creds = NULL;
182         }
183
184         raw_spin_lock_irq(&wqe->lock);
185         if (flags & IO_WORKER_F_FREE)
186                 hlist_nulls_del_rcu(&worker->nulls_node);
187         list_del_rcu(&worker->all_list);
188         acct->nr_workers--;
189         raw_spin_unlock_irq(&wqe->lock);
190
191         kfree_rcu(worker, rcu);
192         if (refcount_dec_and_test(&wqe->wq->refs))
193                 complete(&wqe->wq->done);
194 }
195
196 static inline bool io_wqe_run_queue(struct io_wqe *wqe)
197         __must_hold(wqe->lock)
198 {
199         if (!wq_list_empty(&wqe->work_list) &&
200             !(wqe->flags & IO_WQE_FLAG_STALLED))
201                 return true;
202         return false;
203 }
204
205 /*
206  * Check head of free list for an available worker. If one isn't available,
207  * caller must wake up the wq manager to create one.
208  */
209 static bool io_wqe_activate_free_worker(struct io_wqe *wqe)
210         __must_hold(RCU)
211 {
212         struct hlist_nulls_node *n;
213         struct io_worker *worker;
214
215         n = rcu_dereference(hlist_nulls_first_rcu(&wqe->free_list));
216         if (is_a_nulls(n))
217                 return false;
218
219         worker = hlist_nulls_entry(n, struct io_worker, nulls_node);
220         if (io_worker_get(worker)) {
221                 wake_up_process(worker->task);
222                 io_worker_release(worker);
223                 return true;
224         }
225
226         return false;
227 }
228
229 /*
230  * We need a worker. If we find a free one, we're good. If not, and we're
231  * below the max number of workers, wake up the manager to create one.
232  */
233 static void io_wqe_wake_worker(struct io_wqe *wqe, struct io_wqe_acct *acct)
234 {
235         bool ret;
236
237         /*
238          * Most likely an attempt to queue unbounded work on an io_wq that
239          * wasn't setup with any unbounded workers.
240          */
241         WARN_ON_ONCE(!acct->max_workers);
242
243         rcu_read_lock();
244         ret = io_wqe_activate_free_worker(wqe);
245         rcu_read_unlock();
246
247         if (!ret && acct->nr_workers < acct->max_workers)
248                 wake_up_process(wqe->wq->manager);
249 }
250
251 static void io_wqe_inc_running(struct io_worker *worker)
252 {
253         struct io_wqe_acct *acct = io_wqe_get_acct(worker);
254
255         atomic_inc(&acct->nr_running);
256 }
257
258 static void io_wqe_dec_running(struct io_worker *worker)
259         __must_hold(wqe->lock)
260 {
261         struct io_wqe_acct *acct = io_wqe_get_acct(worker);
262         struct io_wqe *wqe = worker->wqe;
263
264         if (atomic_dec_and_test(&acct->nr_running) && io_wqe_run_queue(wqe))
265                 io_wqe_wake_worker(wqe, acct);
266 }
267
268 static void io_worker_start(struct io_worker *worker)
269 {
270         worker->flags |= (IO_WORKER_F_UP | IO_WORKER_F_RUNNING);
271         io_wqe_inc_running(worker);
272 }
273
274 /*
275  * Worker will start processing some work. Move it to the busy list, if
276  * it's currently on the freelist
277  */
278 static void __io_worker_busy(struct io_wqe *wqe, struct io_worker *worker,
279                              struct io_wq_work *work)
280         __must_hold(wqe->lock)
281 {
282         bool worker_bound, work_bound;
283
284         if (worker->flags & IO_WORKER_F_FREE) {
285                 worker->flags &= ~IO_WORKER_F_FREE;
286                 hlist_nulls_del_init_rcu(&worker->nulls_node);
287         }
288
289         /*
290          * If worker is moving from bound to unbound (or vice versa), then
291          * ensure we update the running accounting.
292          */
293         worker_bound = (worker->flags & IO_WORKER_F_BOUND) != 0;
294         work_bound = (work->flags & IO_WQ_WORK_UNBOUND) == 0;
295         if (worker_bound != work_bound) {
296                 io_wqe_dec_running(worker);
297                 if (work_bound) {
298                         worker->flags |= IO_WORKER_F_BOUND;
299                         wqe->acct[IO_WQ_ACCT_UNBOUND].nr_workers--;
300                         wqe->acct[IO_WQ_ACCT_BOUND].nr_workers++;
301                 } else {
302                         worker->flags &= ~IO_WORKER_F_BOUND;
303                         wqe->acct[IO_WQ_ACCT_UNBOUND].nr_workers++;
304                         wqe->acct[IO_WQ_ACCT_BOUND].nr_workers--;
305                 }
306                 io_wqe_inc_running(worker);
307          }
308 }
309
310 /*
311  * No work, worker going to sleep. Move to freelist, and unuse mm if we
312  * have one attached. Dropping the mm may potentially sleep, so we drop
313  * the lock in that case and return success. Since the caller has to
314  * retry the loop in that case (we changed task state), we don't regrab
315  * the lock if we return success.
316  */
317 static void __io_worker_idle(struct io_wqe *wqe, struct io_worker *worker)
318         __must_hold(wqe->lock)
319 {
320         if (!(worker->flags & IO_WORKER_F_FREE)) {
321                 worker->flags |= IO_WORKER_F_FREE;
322                 hlist_nulls_add_head_rcu(&worker->nulls_node, &wqe->free_list);
323         }
324         if (worker->saved_creds) {
325                 revert_creds(worker->saved_creds);
326                 worker->cur_creds = worker->saved_creds = NULL;
327         }
328 }
329
330 static inline unsigned int io_get_work_hash(struct io_wq_work *work)
331 {
332         return work->flags >> IO_WQ_HASH_SHIFT;
333 }
334
335 static void io_wait_on_hash(struct io_wqe *wqe, unsigned int hash)
336 {
337         struct io_wq *wq = wqe->wq;
338
339         spin_lock(&wq->hash->wait.lock);
340         if (list_empty(&wqe->wait.entry)) {
341                 __add_wait_queue(&wq->hash->wait, &wqe->wait);
342                 if (!test_bit(hash, &wq->hash->map)) {
343                         __set_current_state(TASK_RUNNING);
344                         list_del_init(&wqe->wait.entry);
345                 }
346         }
347         spin_unlock(&wq->hash->wait.lock);
348 }
349
350 static struct io_wq_work *io_get_next_work(struct io_wqe *wqe)
351         __must_hold(wqe->lock)
352 {
353         struct io_wq_work_node *node, *prev;
354         struct io_wq_work *work, *tail;
355         unsigned int stall_hash = -1U;
356
357         wq_list_for_each(node, prev, &wqe->work_list) {
358                 unsigned int hash;
359
360                 work = container_of(node, struct io_wq_work, list);
361
362                 /* not hashed, can run anytime */
363                 if (!io_wq_is_hashed(work)) {
364                         wq_list_del(&wqe->work_list, node, prev);
365                         return work;
366                 }
367
368                 hash = io_get_work_hash(work);
369                 /* all items with this hash lie in [work, tail] */
370                 tail = wqe->hash_tail[hash];
371
372                 /* hashed, can run if not already running */
373                 if (!test_and_set_bit(hash, &wqe->wq->hash->map)) {
374                         wqe->hash_tail[hash] = NULL;
375                         wq_list_cut(&wqe->work_list, &tail->list, prev);
376                         return work;
377                 }
378                 if (stall_hash == -1U)
379                         stall_hash = hash;
380                 /* fast forward to a next hash, for-each will fix up @prev */
381                 node = &tail->list;
382         }
383
384         if (stall_hash != -1U) {
385                 raw_spin_unlock(&wqe->lock);
386                 io_wait_on_hash(wqe, stall_hash);
387                 raw_spin_lock(&wqe->lock);
388         }
389
390         return NULL;
391 }
392
393 static void io_flush_signals(void)
394 {
395         if (unlikely(test_tsk_thread_flag(current, TIF_NOTIFY_SIGNAL))) {
396                 if (current->task_works)
397                         task_work_run();
398                 clear_tsk_thread_flag(current, TIF_NOTIFY_SIGNAL);
399         }
400 }
401
402 static void io_wq_switch_creds(struct io_worker *worker,
403                                struct io_wq_work *work)
404 {
405         const struct cred *old_creds = override_creds(work->creds);
406
407         worker->cur_creds = work->creds;
408         if (worker->saved_creds)
409                 put_cred(old_creds); /* creds set by previous switch */
410         else
411                 worker->saved_creds = old_creds;
412 }
413
414 static void io_assign_current_work(struct io_worker *worker,
415                                    struct io_wq_work *work)
416 {
417         if (work) {
418                 io_flush_signals();
419                 cond_resched();
420         }
421
422         spin_lock_irq(&worker->lock);
423         worker->cur_work = work;
424         spin_unlock_irq(&worker->lock);
425 }
426
427 static void io_wqe_enqueue(struct io_wqe *wqe, struct io_wq_work *work);
428
429 static void io_worker_handle_work(struct io_worker *worker)
430         __releases(wqe->lock)
431 {
432         struct io_wqe *wqe = worker->wqe;
433         struct io_wq *wq = wqe->wq;
434
435         do {
436                 struct io_wq_work *work;
437 get_next:
438                 /*
439                  * If we got some work, mark us as busy. If we didn't, but
440                  * the list isn't empty, it means we stalled on hashed work.
441                  * Mark us stalled so we don't keep looking for work when we
442                  * can't make progress, any work completion or insertion will
443                  * clear the stalled flag.
444                  */
445                 work = io_get_next_work(wqe);
446                 if (work)
447                         __io_worker_busy(wqe, worker, work);
448                 else if (!wq_list_empty(&wqe->work_list))
449                         wqe->flags |= IO_WQE_FLAG_STALLED;
450
451                 raw_spin_unlock_irq(&wqe->lock);
452                 if (!work)
453                         break;
454                 io_assign_current_work(worker, work);
455                 __set_current_state(TASK_RUNNING);
456
457                 /* handle a whole dependent link */
458                 do {
459                         struct io_wq_work *next_hashed, *linked;
460                         unsigned int hash = io_get_work_hash(work);
461
462                         next_hashed = wq_next_work(work);
463                         if (work->creds && worker->cur_creds != work->creds)
464                                 io_wq_switch_creds(worker, work);
465                         wq->do_work(work);
466                         io_assign_current_work(worker, NULL);
467
468                         linked = wq->free_work(work);
469                         work = next_hashed;
470                         if (!work && linked && !io_wq_is_hashed(linked)) {
471                                 work = linked;
472                                 linked = NULL;
473                         }
474                         io_assign_current_work(worker, work);
475                         if (linked)
476                                 io_wqe_enqueue(wqe, linked);
477
478                         if (hash != -1U && !next_hashed) {
479                                 clear_bit(hash, &wq->hash->map);
480                                 if (wq_has_sleeper(&wq->hash->wait))
481                                         wake_up(&wq->hash->wait);
482                                 raw_spin_lock_irq(&wqe->lock);
483                                 wqe->flags &= ~IO_WQE_FLAG_STALLED;
484                                 /* skip unnecessary unlock-lock wqe->lock */
485                                 if (!work)
486                                         goto get_next;
487                                 raw_spin_unlock_irq(&wqe->lock);
488                         }
489                 } while (work);
490
491                 raw_spin_lock_irq(&wqe->lock);
492         } while (1);
493 }
494
495 static int io_wqe_worker(void *data)
496 {
497         struct io_worker *worker = data;
498         struct io_wqe *wqe = worker->wqe;
499         struct io_wq *wq = wqe->wq;
500
501         io_worker_start(worker);
502
503         while (!test_bit(IO_WQ_BIT_EXIT, &wq->state)) {
504                 set_current_state(TASK_INTERRUPTIBLE);
505 loop:
506                 raw_spin_lock_irq(&wqe->lock);
507                 if (io_wqe_run_queue(wqe)) {
508                         io_worker_handle_work(worker);
509                         goto loop;
510                 }
511                 __io_worker_idle(wqe, worker);
512                 raw_spin_unlock_irq(&wqe->lock);
513                 io_flush_signals();
514                 if (schedule_timeout(WORKER_IDLE_TIMEOUT))
515                         continue;
516                 if (fatal_signal_pending(current))
517                         break;
518                 /* timed out, exit unless we're the fixed worker */
519                 if (test_bit(IO_WQ_BIT_EXIT, &wq->state) ||
520                     !(worker->flags & IO_WORKER_F_FIXED))
521                         break;
522         }
523
524         if (test_bit(IO_WQ_BIT_EXIT, &wq->state)) {
525                 raw_spin_lock_irq(&wqe->lock);
526                 if (!wq_list_empty(&wqe->work_list))
527                         io_worker_handle_work(worker);
528                 else
529                         raw_spin_unlock_irq(&wqe->lock);
530         }
531
532         io_worker_exit(worker);
533         return 0;
534 }
535
536 /*
537  * Called when a worker is scheduled in. Mark us as currently running.
538  */
539 void io_wq_worker_running(struct task_struct *tsk)
540 {
541         struct io_worker *worker = tsk->pf_io_worker;
542
543         if (!worker)
544                 return;
545         if (!(worker->flags & IO_WORKER_F_UP))
546                 return;
547         if (worker->flags & IO_WORKER_F_RUNNING)
548                 return;
549         worker->flags |= IO_WORKER_F_RUNNING;
550         io_wqe_inc_running(worker);
551 }
552
553 /*
554  * Called when worker is going to sleep. If there are no workers currently
555  * running and we have work pending, wake up a free one or have the manager
556  * set one up.
557  */
558 void io_wq_worker_sleeping(struct task_struct *tsk)
559 {
560         struct io_worker *worker = tsk->pf_io_worker;
561
562         if (!worker)
563                 return;
564         if (!(worker->flags & IO_WORKER_F_UP))
565                 return;
566         if (!(worker->flags & IO_WORKER_F_RUNNING))
567                 return;
568
569         worker->flags &= ~IO_WORKER_F_RUNNING;
570
571         raw_spin_lock_irq(&worker->wqe->lock);
572         io_wqe_dec_running(worker);
573         raw_spin_unlock_irq(&worker->wqe->lock);
574 }
575
576 static int task_thread(void *data, int index)
577 {
578         struct io_worker *worker = data;
579         struct io_wqe *wqe = worker->wqe;
580         struct io_wqe_acct *acct = &wqe->acct[index];
581         struct io_wq *wq = wqe->wq;
582         char buf[TASK_COMM_LEN];
583
584         sprintf(buf, "iou-wrk-%d", wq->task_pid);
585         set_task_comm(current, buf);
586
587         current->pf_io_worker = worker;
588         worker->task = current;
589
590         set_cpus_allowed_ptr(current, cpumask_of_node(wqe->node));
591         current->flags |= PF_NO_SETAFFINITY;
592
593         raw_spin_lock_irq(&wqe->lock);
594         hlist_nulls_add_head_rcu(&worker->nulls_node, &wqe->free_list);
595         list_add_tail_rcu(&worker->all_list, &wqe->all_list);
596         worker->flags |= IO_WORKER_F_FREE;
597         if (index == IO_WQ_ACCT_BOUND)
598                 worker->flags |= IO_WORKER_F_BOUND;
599         if (!acct->nr_workers && (worker->flags & IO_WORKER_F_BOUND))
600                 worker->flags |= IO_WORKER_F_FIXED;
601         acct->nr_workers++;
602         raw_spin_unlock_irq(&wqe->lock);
603
604         io_wqe_worker(data);
605         do_exit(0);
606 }
607
608 static int task_thread_bound(void *data)
609 {
610         return task_thread(data, IO_WQ_ACCT_BOUND);
611 }
612
613 static int task_thread_unbound(void *data)
614 {
615         return task_thread(data, IO_WQ_ACCT_UNBOUND);
616 }
617
618 pid_t io_wq_fork_thread(int (*fn)(void *), void *arg)
619 {
620         unsigned long flags = CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|
621                                 CLONE_IO|SIGCHLD;
622         struct kernel_clone_args args = {
623                 .flags          = ((lower_32_bits(flags) | CLONE_VM |
624                                     CLONE_UNTRACED) & ~CSIGNAL),
625                 .exit_signal    = (lower_32_bits(flags) & CSIGNAL),
626                 .stack          = (unsigned long)fn,
627                 .stack_size     = (unsigned long)arg,
628         };
629
630         return kernel_clone(&args);
631 }
632
633 static bool create_io_worker(struct io_wq *wq, struct io_wqe *wqe, int index)
634 {
635         struct io_worker *worker;
636         pid_t pid;
637
638         __set_current_state(TASK_RUNNING);
639
640         worker = kzalloc_node(sizeof(*worker), GFP_KERNEL, wqe->node);
641         if (!worker)
642                 return false;
643
644         refcount_set(&worker->ref, 1);
645         worker->nulls_node.pprev = NULL;
646         worker->wqe = wqe;
647         spin_lock_init(&worker->lock);
648         init_completion(&worker->ref_done);
649
650         refcount_inc(&wq->refs);
651
652         if (index == IO_WQ_ACCT_BOUND)
653                 pid = io_wq_fork_thread(task_thread_bound, worker);
654         else
655                 pid = io_wq_fork_thread(task_thread_unbound, worker);
656         if (pid < 0) {
657                 if (refcount_dec_and_test(&wq->refs))
658                         complete(&wq->done);
659                 kfree(worker);
660                 return false;
661         }
662         return true;
663 }
664
665 static inline bool io_wqe_need_worker(struct io_wqe *wqe, int index)
666         __must_hold(wqe->lock)
667 {
668         struct io_wqe_acct *acct = &wqe->acct[index];
669
670         /* if we have available workers or no work, no need */
671         if (!hlist_nulls_empty(&wqe->free_list) || !io_wqe_run_queue(wqe))
672                 return false;
673         return acct->nr_workers < acct->max_workers;
674 }
675
676 /*
677  * Iterate the passed in list and call the specific function for each
678  * worker that isn't exiting
679  */
680 static bool io_wq_for_each_worker(struct io_wqe *wqe,
681                                   bool (*func)(struct io_worker *, void *),
682                                   void *data)
683 {
684         struct io_worker *worker;
685         bool ret = false;
686
687         list_for_each_entry_rcu(worker, &wqe->all_list, all_list) {
688                 if (io_worker_get(worker)) {
689                         /* no task if node is/was offline */
690                         if (worker->task)
691                                 ret = func(worker, data);
692                         io_worker_release(worker);
693                         if (ret)
694                                 break;
695                 }
696         }
697
698         return ret;
699 }
700
701 static bool io_wq_worker_wake(struct io_worker *worker, void *data)
702 {
703         wake_up_process(worker->task);
704         return false;
705 }
706
707 static void io_wq_check_workers(struct io_wq *wq)
708 {
709         int node;
710
711         for_each_node(node) {
712                 struct io_wqe *wqe = wq->wqes[node];
713                 bool fork_worker[2] = { false, false };
714
715                 if (!node_online(node))
716                         continue;
717
718                 raw_spin_lock_irq(&wqe->lock);
719                 if (io_wqe_need_worker(wqe, IO_WQ_ACCT_BOUND))
720                         fork_worker[IO_WQ_ACCT_BOUND] = true;
721                 if (io_wqe_need_worker(wqe, IO_WQ_ACCT_UNBOUND))
722                         fork_worker[IO_WQ_ACCT_UNBOUND] = true;
723                 raw_spin_unlock_irq(&wqe->lock);
724                 if (fork_worker[IO_WQ_ACCT_BOUND])
725                         create_io_worker(wq, wqe, IO_WQ_ACCT_BOUND);
726                 if (fork_worker[IO_WQ_ACCT_UNBOUND])
727                         create_io_worker(wq, wqe, IO_WQ_ACCT_UNBOUND);
728         }
729 }
730
731 /*
732  * Manager thread. Tasked with creating new workers, if we need them.
733  */
734 static int io_wq_manager(void *data)
735 {
736         struct io_wq *wq = data;
737         char buf[TASK_COMM_LEN];
738         int node;
739
740         sprintf(buf, "iou-mgr-%d", wq->task_pid);
741         set_task_comm(current, buf);
742         current->flags |= PF_IO_WORKER;
743         wq->manager = current;
744
745         complete(&wq->done);
746
747         do {
748                 set_current_state(TASK_INTERRUPTIBLE);
749                 io_wq_check_workers(wq);
750                 schedule_timeout(HZ);
751                 if (fatal_signal_pending(current))
752                         set_bit(IO_WQ_BIT_EXIT, &wq->state);
753         } while (!test_bit(IO_WQ_BIT_EXIT, &wq->state));
754
755         io_wq_check_workers(wq);
756
757         if (refcount_dec_and_test(&wq->refs)) {
758                 wq->manager = NULL;
759                 complete(&wq->done);
760                 do_exit(0);
761         }
762         /* if ERROR is set and we get here, we have workers to wake */
763         if (test_bit(IO_WQ_BIT_ERROR, &wq->state)) {
764                 rcu_read_lock();
765                 for_each_node(node)
766                         io_wq_for_each_worker(wq->wqes[node], io_wq_worker_wake, NULL);
767                 rcu_read_unlock();
768         }
769         wq->manager = NULL;
770         do_exit(0);
771 }
772
773 static void io_run_cancel(struct io_wq_work *work, struct io_wqe *wqe)
774 {
775         struct io_wq *wq = wqe->wq;
776
777         do {
778                 work->flags |= IO_WQ_WORK_CANCEL;
779                 wq->do_work(work);
780                 work = wq->free_work(work);
781         } while (work);
782 }
783
784 static void io_wqe_insert_work(struct io_wqe *wqe, struct io_wq_work *work)
785 {
786         unsigned int hash;
787         struct io_wq_work *tail;
788
789         if (!io_wq_is_hashed(work)) {
790 append:
791                 wq_list_add_tail(&work->list, &wqe->work_list);
792                 return;
793         }
794
795         hash = io_get_work_hash(work);
796         tail = wqe->hash_tail[hash];
797         wqe->hash_tail[hash] = work;
798         if (!tail)
799                 goto append;
800
801         wq_list_add_after(&work->list, &tail->list, &wqe->work_list);
802 }
803
804 static void io_wqe_enqueue(struct io_wqe *wqe, struct io_wq_work *work)
805 {
806         struct io_wqe_acct *acct = io_work_get_acct(wqe, work);
807         int work_flags;
808         unsigned long flags;
809
810         work_flags = work->flags;
811         raw_spin_lock_irqsave(&wqe->lock, flags);
812         io_wqe_insert_work(wqe, work);
813         wqe->flags &= ~IO_WQE_FLAG_STALLED;
814         raw_spin_unlock_irqrestore(&wqe->lock, flags);
815
816         if ((work_flags & IO_WQ_WORK_CONCURRENT) ||
817             !atomic_read(&acct->nr_running))
818                 io_wqe_wake_worker(wqe, acct);
819 }
820
821 void io_wq_enqueue(struct io_wq *wq, struct io_wq_work *work)
822 {
823         struct io_wqe *wqe = wq->wqes[numa_node_id()];
824
825         io_wqe_enqueue(wqe, work);
826 }
827
828 /*
829  * Work items that hash to the same value will not be done in parallel.
830  * Used to limit concurrent writes, generally hashed by inode.
831  */
832 void io_wq_hash_work(struct io_wq_work *work, void *val)
833 {
834         unsigned int bit;
835
836         bit = hash_ptr(val, IO_WQ_HASH_ORDER);
837         work->flags |= (IO_WQ_WORK_HASHED | (bit << IO_WQ_HASH_SHIFT));
838 }
839
840 struct io_cb_cancel_data {
841         work_cancel_fn *fn;
842         void *data;
843         int nr_running;
844         int nr_pending;
845         bool cancel_all;
846 };
847
848 static bool io_wq_worker_cancel(struct io_worker *worker, void *data)
849 {
850         struct io_cb_cancel_data *match = data;
851         unsigned long flags;
852
853         /*
854          * Hold the lock to avoid ->cur_work going out of scope, caller
855          * may dereference the passed in work.
856          */
857         spin_lock_irqsave(&worker->lock, flags);
858         if (worker->cur_work &&
859             match->fn(worker->cur_work, match->data)) {
860                 set_notify_signal(worker->task);
861                 match->nr_running++;
862         }
863         spin_unlock_irqrestore(&worker->lock, flags);
864
865         return match->nr_running && !match->cancel_all;
866 }
867
868 static inline void io_wqe_remove_pending(struct io_wqe *wqe,
869                                          struct io_wq_work *work,
870                                          struct io_wq_work_node *prev)
871 {
872         unsigned int hash = io_get_work_hash(work);
873         struct io_wq_work *prev_work = NULL;
874
875         if (io_wq_is_hashed(work) && work == wqe->hash_tail[hash]) {
876                 if (prev)
877                         prev_work = container_of(prev, struct io_wq_work, list);
878                 if (prev_work && io_get_work_hash(prev_work) == hash)
879                         wqe->hash_tail[hash] = prev_work;
880                 else
881                         wqe->hash_tail[hash] = NULL;
882         }
883         wq_list_del(&wqe->work_list, &work->list, prev);
884 }
885
886 static void io_wqe_cancel_pending_work(struct io_wqe *wqe,
887                                        struct io_cb_cancel_data *match)
888 {
889         struct io_wq_work_node *node, *prev;
890         struct io_wq_work *work;
891         unsigned long flags;
892
893 retry:
894         raw_spin_lock_irqsave(&wqe->lock, flags);
895         wq_list_for_each(node, prev, &wqe->work_list) {
896                 work = container_of(node, struct io_wq_work, list);
897                 if (!match->fn(work, match->data))
898                         continue;
899                 io_wqe_remove_pending(wqe, work, prev);
900                 raw_spin_unlock_irqrestore(&wqe->lock, flags);
901                 io_run_cancel(work, wqe);
902                 match->nr_pending++;
903                 if (!match->cancel_all)
904                         return;
905
906                 /* not safe to continue after unlock */
907                 goto retry;
908         }
909         raw_spin_unlock_irqrestore(&wqe->lock, flags);
910 }
911
912 static void io_wqe_cancel_running_work(struct io_wqe *wqe,
913                                        struct io_cb_cancel_data *match)
914 {
915         rcu_read_lock();
916         io_wq_for_each_worker(wqe, io_wq_worker_cancel, match);
917         rcu_read_unlock();
918 }
919
920 enum io_wq_cancel io_wq_cancel_cb(struct io_wq *wq, work_cancel_fn *cancel,
921                                   void *data, bool cancel_all)
922 {
923         struct io_cb_cancel_data match = {
924                 .fn             = cancel,
925                 .data           = data,
926                 .cancel_all     = cancel_all,
927         };
928         int node;
929
930         /*
931          * First check pending list, if we're lucky we can just remove it
932          * from there. CANCEL_OK means that the work is returned as-new,
933          * no completion will be posted for it.
934          */
935         for_each_node(node) {
936                 struct io_wqe *wqe = wq->wqes[node];
937
938                 io_wqe_cancel_pending_work(wqe, &match);
939                 if (match.nr_pending && !match.cancel_all)
940                         return IO_WQ_CANCEL_OK;
941         }
942
943         /*
944          * Now check if a free (going busy) or busy worker has the work
945          * currently running. If we find it there, we'll return CANCEL_RUNNING
946          * as an indication that we attempt to signal cancellation. The
947          * completion will run normally in this case.
948          */
949         for_each_node(node) {
950                 struct io_wqe *wqe = wq->wqes[node];
951
952                 io_wqe_cancel_running_work(wqe, &match);
953                 if (match.nr_running && !match.cancel_all)
954                         return IO_WQ_CANCEL_RUNNING;
955         }
956
957         if (match.nr_running)
958                 return IO_WQ_CANCEL_RUNNING;
959         if (match.nr_pending)
960                 return IO_WQ_CANCEL_OK;
961         return IO_WQ_CANCEL_NOTFOUND;
962 }
963
964 static int io_wqe_hash_wake(struct wait_queue_entry *wait, unsigned mode,
965                             int sync, void *key)
966 {
967         struct io_wqe *wqe = container_of(wait, struct io_wqe, wait);
968         int ret;
969
970         list_del_init(&wait->entry);
971
972         rcu_read_lock();
973         ret = io_wqe_activate_free_worker(wqe);
974         rcu_read_unlock();
975
976         if (!ret)
977                 wake_up_process(wqe->wq->manager);
978
979         return 1;
980 }
981
982 struct io_wq *io_wq_create(unsigned bounded, struct io_wq_data *data)
983 {
984         int ret = -ENOMEM, node;
985         struct io_wq *wq;
986
987         if (WARN_ON_ONCE(!data->free_work || !data->do_work))
988                 return ERR_PTR(-EINVAL);
989
990         wq = kzalloc(sizeof(*wq), GFP_KERNEL);
991         if (!wq)
992                 return ERR_PTR(-ENOMEM);
993
994         wq->wqes = kcalloc(nr_node_ids, sizeof(struct io_wqe *), GFP_KERNEL);
995         if (!wq->wqes)
996                 goto err_wq;
997
998         ret = cpuhp_state_add_instance_nocalls(io_wq_online, &wq->cpuhp_node);
999         if (ret)
1000                 goto err_wqes;
1001
1002         refcount_inc(&data->hash->refs);
1003         wq->hash = data->hash;
1004         wq->free_work = data->free_work;
1005         wq->do_work = data->do_work;
1006
1007         ret = -ENOMEM;
1008         for_each_node(node) {
1009                 struct io_wqe *wqe;
1010                 int alloc_node = node;
1011
1012                 if (!node_online(alloc_node))
1013                         alloc_node = NUMA_NO_NODE;
1014                 wqe = kzalloc_node(sizeof(struct io_wqe), GFP_KERNEL, alloc_node);
1015                 if (!wqe)
1016                         goto err;
1017                 wq->wqes[node] = wqe;
1018                 wqe->node = alloc_node;
1019                 wqe->acct[IO_WQ_ACCT_BOUND].max_workers = bounded;
1020                 atomic_set(&wqe->acct[IO_WQ_ACCT_BOUND].nr_running, 0);
1021                 wqe->acct[IO_WQ_ACCT_UNBOUND].max_workers =
1022                                         task_rlimit(current, RLIMIT_NPROC);
1023                 atomic_set(&wqe->acct[IO_WQ_ACCT_UNBOUND].nr_running, 0);
1024                 wqe->wait.func = io_wqe_hash_wake;
1025                 INIT_LIST_HEAD(&wqe->wait.entry);
1026                 wqe->wq = wq;
1027                 raw_spin_lock_init(&wqe->lock);
1028                 INIT_WQ_LIST(&wqe->work_list);
1029                 INIT_HLIST_NULLS_HEAD(&wqe->free_list, 0);
1030                 INIT_LIST_HEAD(&wqe->all_list);
1031         }
1032
1033         wq->task_pid = current->pid;
1034         init_completion(&wq->done);
1035         refcount_set(&wq->refs, 1);
1036
1037         current->flags |= PF_IO_WORKER;
1038         ret = io_wq_fork_thread(io_wq_manager, wq);
1039         current->flags &= ~PF_IO_WORKER;
1040         if (ret >= 0) {
1041                 wait_for_completion(&wq->done);
1042                 return wq;
1043         }
1044
1045         if (refcount_dec_and_test(&wq->refs))
1046                 complete(&wq->done);
1047         io_wq_put_hash(data->hash);
1048 err:
1049         cpuhp_state_remove_instance_nocalls(io_wq_online, &wq->cpuhp_node);
1050         for_each_node(node)
1051                 kfree(wq->wqes[node]);
1052 err_wqes:
1053         kfree(wq->wqes);
1054 err_wq:
1055         kfree(wq);
1056         return ERR_PTR(ret);
1057 }
1058
1059 void io_wq_destroy(struct io_wq *wq)
1060 {
1061         int node;
1062
1063         cpuhp_state_remove_instance_nocalls(io_wq_online, &wq->cpuhp_node);
1064
1065         set_bit(IO_WQ_BIT_EXIT, &wq->state);
1066         if (wq->manager)
1067                 wake_up_process(wq->manager);
1068
1069         rcu_read_lock();
1070         for_each_node(node)
1071                 io_wq_for_each_worker(wq->wqes[node], io_wq_worker_wake, NULL);
1072         rcu_read_unlock();
1073
1074         wait_for_completion(&wq->done);
1075
1076         spin_lock_irq(&wq->hash->wait.lock);
1077         for_each_node(node) {
1078                 struct io_wqe *wqe = wq->wqes[node];
1079
1080                 list_del_init(&wqe->wait.entry);
1081                 kfree(wqe);
1082         }
1083         spin_unlock_irq(&wq->hash->wait.lock);
1084         io_wq_put_hash(wq->hash);
1085         kfree(wq->wqes);
1086         kfree(wq);
1087 }
1088
1089 static bool io_wq_worker_affinity(struct io_worker *worker, void *data)
1090 {
1091         struct task_struct *task = worker->task;
1092         struct rq_flags rf;
1093         struct rq *rq;
1094
1095         rq = task_rq_lock(task, &rf);
1096         do_set_cpus_allowed(task, cpumask_of_node(worker->wqe->node));
1097         task->flags |= PF_NO_SETAFFINITY;
1098         task_rq_unlock(rq, task, &rf);
1099         return false;
1100 }
1101
1102 static int io_wq_cpu_online(unsigned int cpu, struct hlist_node *node)
1103 {
1104         struct io_wq *wq = hlist_entry_safe(node, struct io_wq, cpuhp_node);
1105         int i;
1106
1107         rcu_read_lock();
1108         for_each_node(i)
1109                 io_wq_for_each_worker(wq->wqes[i], io_wq_worker_affinity, NULL);
1110         rcu_read_unlock();
1111         return 0;
1112 }
1113
1114 static __init int io_wq_init(void)
1115 {
1116         int ret;
1117
1118         ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "io-wq/online",
1119                                         io_wq_cpu_online, NULL);
1120         if (ret < 0)
1121                 return ret;
1122         io_wq_online = ret;
1123         return 0;
1124 }
1125 subsys_initcall(io_wq_init);