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