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