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