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