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