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