io-wq: fix double put of 'wq' in error path
[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         return ret;
830 }
831
832 static void io_wqe_enqueue(struct io_wqe *wqe, struct io_wq_work *work)
833 {
834         struct io_wqe_acct *acct = io_work_get_acct(wqe, work);
835         int work_flags;
836         unsigned long flags;
837
838         /* Can only happen if manager creation fails after exec */
839         if (unlikely(io_wq_fork_manager(wqe->wq))) {
840                 work->flags |= IO_WQ_WORK_CANCEL;
841                 wqe->wq->do_work(work);
842                 return;
843         }
844
845         work_flags = work->flags;
846         raw_spin_lock_irqsave(&wqe->lock, flags);
847         io_wqe_insert_work(wqe, work);
848         wqe->flags &= ~IO_WQE_FLAG_STALLED;
849         raw_spin_unlock_irqrestore(&wqe->lock, flags);
850
851         if ((work_flags & IO_WQ_WORK_CONCURRENT) ||
852             !atomic_read(&acct->nr_running))
853                 io_wqe_wake_worker(wqe, acct);
854 }
855
856 void io_wq_enqueue(struct io_wq *wq, struct io_wq_work *work)
857 {
858         struct io_wqe *wqe = wq->wqes[numa_node_id()];
859
860         io_wqe_enqueue(wqe, work);
861 }
862
863 /*
864  * Work items that hash to the same value will not be done in parallel.
865  * Used to limit concurrent writes, generally hashed by inode.
866  */
867 void io_wq_hash_work(struct io_wq_work *work, void *val)
868 {
869         unsigned int bit;
870
871         bit = hash_ptr(val, IO_WQ_HASH_ORDER);
872         work->flags |= (IO_WQ_WORK_HASHED | (bit << IO_WQ_HASH_SHIFT));
873 }
874
875 struct io_cb_cancel_data {
876         work_cancel_fn *fn;
877         void *data;
878         int nr_running;
879         int nr_pending;
880         bool cancel_all;
881 };
882
883 static bool io_wq_worker_cancel(struct io_worker *worker, void *data)
884 {
885         struct io_cb_cancel_data *match = data;
886         unsigned long flags;
887
888         /*
889          * Hold the lock to avoid ->cur_work going out of scope, caller
890          * may dereference the passed in work.
891          */
892         spin_lock_irqsave(&worker->lock, flags);
893         if (worker->cur_work &&
894             match->fn(worker->cur_work, match->data)) {
895                 set_notify_signal(worker->task);
896                 match->nr_running++;
897         }
898         spin_unlock_irqrestore(&worker->lock, flags);
899
900         return match->nr_running && !match->cancel_all;
901 }
902
903 static inline void io_wqe_remove_pending(struct io_wqe *wqe,
904                                          struct io_wq_work *work,
905                                          struct io_wq_work_node *prev)
906 {
907         unsigned int hash = io_get_work_hash(work);
908         struct io_wq_work *prev_work = NULL;
909
910         if (io_wq_is_hashed(work) && work == wqe->hash_tail[hash]) {
911                 if (prev)
912                         prev_work = container_of(prev, struct io_wq_work, list);
913                 if (prev_work && io_get_work_hash(prev_work) == hash)
914                         wqe->hash_tail[hash] = prev_work;
915                 else
916                         wqe->hash_tail[hash] = NULL;
917         }
918         wq_list_del(&wqe->work_list, &work->list, prev);
919 }
920
921 static void io_wqe_cancel_pending_work(struct io_wqe *wqe,
922                                        struct io_cb_cancel_data *match)
923 {
924         struct io_wq_work_node *node, *prev;
925         struct io_wq_work *work;
926         unsigned long flags;
927
928 retry:
929         raw_spin_lock_irqsave(&wqe->lock, flags);
930         wq_list_for_each(node, prev, &wqe->work_list) {
931                 work = container_of(node, struct io_wq_work, list);
932                 if (!match->fn(work, match->data))
933                         continue;
934                 io_wqe_remove_pending(wqe, work, prev);
935                 raw_spin_unlock_irqrestore(&wqe->lock, flags);
936                 io_run_cancel(work, wqe);
937                 match->nr_pending++;
938                 if (!match->cancel_all)
939                         return;
940
941                 /* not safe to continue after unlock */
942                 goto retry;
943         }
944         raw_spin_unlock_irqrestore(&wqe->lock, flags);
945 }
946
947 static void io_wqe_cancel_running_work(struct io_wqe *wqe,
948                                        struct io_cb_cancel_data *match)
949 {
950         rcu_read_lock();
951         io_wq_for_each_worker(wqe, io_wq_worker_cancel, match);
952         rcu_read_unlock();
953 }
954
955 enum io_wq_cancel io_wq_cancel_cb(struct io_wq *wq, work_cancel_fn *cancel,
956                                   void *data, bool cancel_all)
957 {
958         struct io_cb_cancel_data match = {
959                 .fn             = cancel,
960                 .data           = data,
961                 .cancel_all     = cancel_all,
962         };
963         int node;
964
965         /*
966          * First check pending list, if we're lucky we can just remove it
967          * from there. CANCEL_OK means that the work is returned as-new,
968          * no completion will be posted for it.
969          */
970         for_each_node(node) {
971                 struct io_wqe *wqe = wq->wqes[node];
972
973                 io_wqe_cancel_pending_work(wqe, &match);
974                 if (match.nr_pending && !match.cancel_all)
975                         return IO_WQ_CANCEL_OK;
976         }
977
978         /*
979          * Now check if a free (going busy) or busy worker has the work
980          * currently running. If we find it there, we'll return CANCEL_RUNNING
981          * as an indication that we attempt to signal cancellation. The
982          * completion will run normally in this case.
983          */
984         for_each_node(node) {
985                 struct io_wqe *wqe = wq->wqes[node];
986
987                 io_wqe_cancel_running_work(wqe, &match);
988                 if (match.nr_running && !match.cancel_all)
989                         return IO_WQ_CANCEL_RUNNING;
990         }
991
992         if (match.nr_running)
993                 return IO_WQ_CANCEL_RUNNING;
994         if (match.nr_pending)
995                 return IO_WQ_CANCEL_OK;
996         return IO_WQ_CANCEL_NOTFOUND;
997 }
998
999 static int io_wqe_hash_wake(struct wait_queue_entry *wait, unsigned mode,
1000                             int sync, void *key)
1001 {
1002         struct io_wqe *wqe = container_of(wait, struct io_wqe, wait);
1003         int ret;
1004
1005         list_del_init(&wait->entry);
1006
1007         rcu_read_lock();
1008         ret = io_wqe_activate_free_worker(wqe);
1009         rcu_read_unlock();
1010
1011         if (!ret)
1012                 wake_up_process(wqe->wq->manager);
1013
1014         return 1;
1015 }
1016
1017 struct io_wq *io_wq_create(unsigned bounded, struct io_wq_data *data)
1018 {
1019         int ret = -ENOMEM, node;
1020         struct io_wq *wq;
1021
1022         if (WARN_ON_ONCE(!data->free_work || !data->do_work))
1023                 return ERR_PTR(-EINVAL);
1024
1025         wq = kzalloc(sizeof(*wq), GFP_KERNEL);
1026         if (!wq)
1027                 return ERR_PTR(-ENOMEM);
1028
1029         wq->wqes = kcalloc(nr_node_ids, sizeof(struct io_wqe *), GFP_KERNEL);
1030         if (!wq->wqes)
1031                 goto err_wq;
1032
1033         ret = cpuhp_state_add_instance_nocalls(io_wq_online, &wq->cpuhp_node);
1034         if (ret)
1035                 goto err_wqes;
1036
1037         refcount_inc(&data->hash->refs);
1038         wq->hash = data->hash;
1039         wq->free_work = data->free_work;
1040         wq->do_work = data->do_work;
1041
1042         ret = -ENOMEM;
1043         for_each_node(node) {
1044                 struct io_wqe *wqe;
1045                 int alloc_node = node;
1046
1047                 if (!node_online(alloc_node))
1048                         alloc_node = NUMA_NO_NODE;
1049                 wqe = kzalloc_node(sizeof(struct io_wqe), GFP_KERNEL, alloc_node);
1050                 if (!wqe)
1051                         goto err;
1052                 wq->wqes[node] = wqe;
1053                 wqe->node = alloc_node;
1054                 wqe->acct[IO_WQ_ACCT_BOUND].max_workers = bounded;
1055                 atomic_set(&wqe->acct[IO_WQ_ACCT_BOUND].nr_running, 0);
1056                 wqe->acct[IO_WQ_ACCT_UNBOUND].max_workers =
1057                                         task_rlimit(current, RLIMIT_NPROC);
1058                 atomic_set(&wqe->acct[IO_WQ_ACCT_UNBOUND].nr_running, 0);
1059                 wqe->wait.func = io_wqe_hash_wake;
1060                 INIT_LIST_HEAD(&wqe->wait.entry);
1061                 wqe->wq = wq;
1062                 raw_spin_lock_init(&wqe->lock);
1063                 INIT_WQ_LIST(&wqe->work_list);
1064                 INIT_HLIST_NULLS_HEAD(&wqe->free_list, 0);
1065                 INIT_LIST_HEAD(&wqe->all_list);
1066         }
1067
1068         wq->task_pid = current->pid;
1069         init_completion(&wq->started);
1070         init_completion(&wq->exited);
1071         refcount_set(&wq->refs, 1);
1072
1073         init_completion(&wq->worker_done);
1074         atomic_set(&wq->worker_refs, 0);
1075
1076         ret = io_wq_fork_manager(wq);
1077         if (!ret)
1078                 return wq;
1079
1080         io_wq_put_hash(data->hash);
1081 err:
1082         cpuhp_state_remove_instance_nocalls(io_wq_online, &wq->cpuhp_node);
1083         for_each_node(node)
1084                 kfree(wq->wqes[node]);
1085 err_wqes:
1086         kfree(wq->wqes);
1087 err_wq:
1088         kfree(wq);
1089         return ERR_PTR(ret);
1090 }
1091
1092 static void io_wq_destroy(struct io_wq *wq)
1093 {
1094         int node;
1095
1096         cpuhp_state_remove_instance_nocalls(io_wq_online, &wq->cpuhp_node);
1097
1098         set_bit(IO_WQ_BIT_EXIT, &wq->state);
1099         if (wq->manager) {
1100                 wake_up_process(wq->manager);
1101                 wait_for_completion(&wq->exited);
1102         }
1103
1104         spin_lock_irq(&wq->hash->wait.lock);
1105         for_each_node(node) {
1106                 struct io_wqe *wqe = wq->wqes[node];
1107
1108                 list_del_init(&wqe->wait.entry);
1109                 kfree(wqe);
1110         }
1111         spin_unlock_irq(&wq->hash->wait.lock);
1112         io_wq_put_hash(wq->hash);
1113         kfree(wq->wqes);
1114         kfree(wq);
1115
1116 }
1117
1118 void io_wq_put(struct io_wq *wq)
1119 {
1120         if (refcount_dec_and_test(&wq->refs))
1121                 io_wq_destroy(wq);
1122 }
1123
1124 static bool io_wq_worker_affinity(struct io_worker *worker, void *data)
1125 {
1126         struct task_struct *task = worker->task;
1127         struct rq_flags rf;
1128         struct rq *rq;
1129
1130         rq = task_rq_lock(task, &rf);
1131         do_set_cpus_allowed(task, cpumask_of_node(worker->wqe->node));
1132         task->flags |= PF_NO_SETAFFINITY;
1133         task_rq_unlock(rq, task, &rf);
1134         return false;
1135 }
1136
1137 static int io_wq_cpu_online(unsigned int cpu, struct hlist_node *node)
1138 {
1139         struct io_wq *wq = hlist_entry_safe(node, struct io_wq, cpuhp_node);
1140         int i;
1141
1142         rcu_read_lock();
1143         for_each_node(i)
1144                 io_wq_for_each_worker(wq->wqes[i], io_wq_worker_affinity, NULL);
1145         rcu_read_unlock();
1146         return 0;
1147 }
1148
1149 static __init int io_wq_init(void)
1150 {
1151         int ret;
1152
1153         ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "io-wq/online",
1154                                         io_wq_cpu_online, NULL);
1155         if (ret < 0)
1156                 return ret;
1157         io_wq_online = ret;
1158         return 0;
1159 }
1160 subsys_initcall(io_wq_init);