io_uring: fix race condition in task_work add and clear
[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 = get_task_struct(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         complete(&wq->exited);
775         do_exit(0);
776 }
777
778 static void io_run_cancel(struct io_wq_work *work, struct io_wqe *wqe)
779 {
780         struct io_wq *wq = wqe->wq;
781
782         do {
783                 work->flags |= IO_WQ_WORK_CANCEL;
784                 wq->do_work(work);
785                 work = wq->free_work(work);
786         } while (work);
787 }
788
789 static void io_wqe_insert_work(struct io_wqe *wqe, struct io_wq_work *work)
790 {
791         unsigned int hash;
792         struct io_wq_work *tail;
793
794         if (!io_wq_is_hashed(work)) {
795 append:
796                 wq_list_add_tail(&work->list, &wqe->work_list);
797                 return;
798         }
799
800         hash = io_get_work_hash(work);
801         tail = wqe->hash_tail[hash];
802         wqe->hash_tail[hash] = work;
803         if (!tail)
804                 goto append;
805
806         wq_list_add_after(&work->list, &tail->list, &wqe->work_list);
807 }
808
809 static int io_wq_fork_manager(struct io_wq *wq)
810 {
811         int ret;
812
813         if (wq->manager)
814                 return 0;
815
816         reinit_completion(&wq->worker_done);
817         current->flags |= PF_IO_WORKER;
818         ret = io_wq_fork_thread(io_wq_manager, wq);
819         current->flags &= ~PF_IO_WORKER;
820         if (ret >= 0) {
821                 wait_for_completion(&wq->started);
822                 return 0;
823         }
824
825         return ret;
826 }
827
828 static void io_wqe_enqueue(struct io_wqe *wqe, struct io_wq_work *work)
829 {
830         struct io_wqe_acct *acct = io_work_get_acct(wqe, work);
831         int work_flags;
832         unsigned long flags;
833
834         /* Can only happen if manager creation fails after exec */
835         if (unlikely(io_wq_fork_manager(wqe->wq))) {
836                 work->flags |= IO_WQ_WORK_CANCEL;
837                 wqe->wq->do_work(work);
838                 return;
839         }
840
841         work_flags = work->flags;
842         raw_spin_lock_irqsave(&wqe->lock, flags);
843         io_wqe_insert_work(wqe, work);
844         wqe->flags &= ~IO_WQE_FLAG_STALLED;
845         raw_spin_unlock_irqrestore(&wqe->lock, flags);
846
847         if ((work_flags & IO_WQ_WORK_CONCURRENT) ||
848             !atomic_read(&acct->nr_running))
849                 io_wqe_wake_worker(wqe, acct);
850 }
851
852 void io_wq_enqueue(struct io_wq *wq, struct io_wq_work *work)
853 {
854         struct io_wqe *wqe = wq->wqes[numa_node_id()];
855
856         io_wqe_enqueue(wqe, work);
857 }
858
859 /*
860  * Work items that hash to the same value will not be done in parallel.
861  * Used to limit concurrent writes, generally hashed by inode.
862  */
863 void io_wq_hash_work(struct io_wq_work *work, void *val)
864 {
865         unsigned int bit;
866
867         bit = hash_ptr(val, IO_WQ_HASH_ORDER);
868         work->flags |= (IO_WQ_WORK_HASHED | (bit << IO_WQ_HASH_SHIFT));
869 }
870
871 struct io_cb_cancel_data {
872         work_cancel_fn *fn;
873         void *data;
874         int nr_running;
875         int nr_pending;
876         bool cancel_all;
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         io_wq_put_hash(data->hash);
1077 err:
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                 kfree(wqe);
1113         }
1114         spin_unlock_irq(&wq->hash->wait.lock);
1115         io_wq_put_hash(wq->hash);
1116         kfree(wq->wqes);
1117         kfree(wq);
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 void io_wq_put_and_exit(struct io_wq *wq)
1127 {
1128         set_bit(IO_WQ_BIT_EXIT, &wq->state);
1129         io_wq_destroy_manager(wq);
1130         io_wq_put(wq);
1131 }
1132
1133 static bool io_wq_worker_affinity(struct io_worker *worker, void *data)
1134 {
1135         struct task_struct *task = worker->task;
1136         struct rq_flags rf;
1137         struct rq *rq;
1138
1139         rq = task_rq_lock(task, &rf);
1140         do_set_cpus_allowed(task, cpumask_of_node(worker->wqe->node));
1141         task->flags |= PF_NO_SETAFFINITY;
1142         task_rq_unlock(rq, task, &rf);
1143         return false;
1144 }
1145
1146 static int io_wq_cpu_online(unsigned int cpu, struct hlist_node *node)
1147 {
1148         struct io_wq *wq = hlist_entry_safe(node, struct io_wq, cpuhp_node);
1149         int i;
1150
1151         rcu_read_lock();
1152         for_each_node(i)
1153                 io_wq_for_each_worker(wq->wqes[i], io_wq_worker_affinity, NULL);
1154         rcu_read_unlock();
1155         return 0;
1156 }
1157
1158 static __init int io_wq_init(void)
1159 {
1160         int ret;
1161
1162         ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "io-wq/online",
1163                                         io_wq_cpu_online, NULL);
1164         if (ret < 0)
1165                 return ret;
1166         io_wq_online = ret;
1167         return 0;
1168 }
1169 subsys_initcall(io_wq_init);