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