xref: /linux/io_uring/io-wq.c (revision 0659e44ce739ecd856164c75a5325b7959a2921d)
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/sched/debug.h>
13 #include <linux/percpu.h>
14 #include <linux/slab.h>
15 #include <linux/rculist_nulls.h>
16 #include <linux/cpu.h>
17 #include <linux/cpuset.h>
18 #include <linux/task_work.h>
19 #include <linux/audit.h>
20 #include <linux/mmu_context.h>
21 #include <linux/sched/sysctl.h>
22 #include <uapi/linux/io_uring.h>
23 #include <linux/kcov.h>
24 
25 #include "io-wq.h"
26 #include "slist.h"
27 #include "io_uring.h"
28 
29 #define WORKER_IDLE_TIMEOUT	(5 * HZ)
30 #define WORKER_INIT_LIMIT	3
31 
32 enum {
33 	IO_WORKER_F_UP		= 0,	/* up and active */
34 	IO_WORKER_F_RUNNING	= 1,	/* account as running */
35 	IO_WORKER_F_FREE	= 2,	/* worker on free list */
36 };
37 
38 enum {
39 	IO_WQ_BIT_EXIT		= 0,	/* wq exiting */
40 	IO_WQ_BIT_EXIT_ON_IDLE	= 1,	/* allow all workers to exit on idle */
41 };
42 
43 enum {
44 	IO_ACCT_STALLED_BIT	= 0,	/* stalled on hash */
45 };
46 
47 /*
48  * One for each thread in a wq pool
49  */
50 struct io_worker {
51 	refcount_t ref;
52 	unsigned long flags;
53 	struct hlist_nulls_node nulls_node;
54 	struct list_head all_list;
55 	struct task_struct *task;
56 	struct io_wq *wq;
57 	struct io_wq_acct *acct;
58 
59 	struct io_wq_work *cur_work;
60 	/* rest of the hashed chain ->cur_work was taken off the list with */
61 	struct io_wq_work *next_work;
62 	raw_spinlock_t lock;
63 
64 	struct completion ref_done;
65 
66 	unsigned long create_state;
67 	struct callback_head create_work;
68 	int init_retries;
69 
70 	union {
71 		struct rcu_head rcu;
72 		struct delayed_work work;
73 	};
74 };
75 
76 #if BITS_PER_LONG == 64
77 #define IO_WQ_HASH_ORDER	6
78 #else
79 #define IO_WQ_HASH_ORDER	5
80 #endif
81 
82 #define IO_WQ_NR_HASH_BUCKETS	(1u << IO_WQ_HASH_ORDER)
83 
84 struct io_wq_acct {
85 	/**
86 	 * Protects access to the worker lists.
87 	 */
88 	raw_spinlock_t workers_lock;
89 
90 	unsigned nr_workers;
91 	unsigned max_workers;
92 	atomic_t nr_running;
93 
94 	/**
95 	 * The list of free workers.  Protected by #workers_lock
96 	 * (write) and RCU (read).
97 	 */
98 	struct hlist_nulls_head free_list;
99 
100 	/**
101 	 * The list of all workers.  Protected by #workers_lock
102 	 * (write) and RCU (read).
103 	 */
104 	struct list_head all_list;
105 
106 	raw_spinlock_t lock;
107 	struct io_wq_work_list work_list;
108 	unsigned long flags;
109 };
110 
111 enum {
112 	IO_WQ_ACCT_BOUND,
113 	IO_WQ_ACCT_UNBOUND,
114 	IO_WQ_ACCT_NR,
115 };
116 
117 /*
118  * Per io_wq state
119   */
120 struct io_wq {
121 	unsigned long state;
122 
123 	struct io_wq_hash *hash;
124 
125 	atomic_t worker_refs;
126 	struct completion worker_done;
127 
128 	struct hlist_node cpuhp_node;
129 
130 	struct task_struct *task;
131 
132 	struct io_wq_acct acct[IO_WQ_ACCT_NR];
133 
134 	struct wait_queue_entry wait;
135 
136 	struct io_wq_work *hash_tail[IO_WQ_NR_HASH_BUCKETS];
137 
138 	cpumask_var_t cpu_mask;
139 };
140 
141 static enum cpuhp_state io_wq_online;
142 
143 struct io_cb_cancel_data {
144 	work_cancel_fn *fn;
145 	void *data;
146 	int nr_running;
147 	int nr_pending;
148 	bool cancel_all;
149 };
150 
151 static bool create_io_worker(struct io_wq *wq, struct io_wq_acct *acct);
152 static void io_wq_dec_running(struct io_worker *worker);
153 static bool io_acct_cancel_pending_work(struct io_wq *wq,
154 					struct io_wq_acct *acct,
155 					struct io_cb_cancel_data *match);
156 static void create_worker_cb(struct callback_head *cb);
157 static void io_wq_cancel_tw_create(struct io_wq *wq);
158 
159 static inline unsigned int __io_get_work_hash(unsigned int work_flags)
160 {
161 	return work_flags >> IO_WQ_HASH_SHIFT;
162 }
163 
164 static inline unsigned int io_get_work_hash(struct io_wq_work *work)
165 {
166 	return __io_get_work_hash(atomic_read(&work->flags));
167 }
168 
169 static bool io_worker_get(struct io_worker *worker)
170 {
171 	return refcount_inc_not_zero(&worker->ref);
172 }
173 
174 static void io_worker_release(struct io_worker *worker)
175 {
176 	if (refcount_dec_and_test(&worker->ref))
177 		complete(&worker->ref_done);
178 }
179 
180 static inline struct io_wq_acct *io_get_acct(struct io_wq *wq, bool bound)
181 {
182 	return &wq->acct[bound ? IO_WQ_ACCT_BOUND : IO_WQ_ACCT_UNBOUND];
183 }
184 
185 static inline struct io_wq_acct *io_work_get_acct(struct io_wq *wq,
186 						  unsigned int work_flags)
187 {
188 	return io_get_acct(wq, !(work_flags & IO_WQ_WORK_UNBOUND));
189 }
190 
191 static inline struct io_wq_acct *io_wq_get_acct(struct io_worker *worker)
192 {
193 	return worker->acct;
194 }
195 
196 static void io_worker_ref_put(struct io_wq *wq)
197 {
198 	if (atomic_dec_and_test(&wq->worker_refs))
199 		complete(&wq->worker_done);
200 }
201 
202 bool io_wq_worker_stopped(void)
203 {
204 	struct io_worker *worker = current->worker_private;
205 
206 	if (WARN_ON_ONCE(!io_wq_current_is_worker()))
207 		return true;
208 
209 	return test_bit(IO_WQ_BIT_EXIT, &worker->wq->state);
210 }
211 
212 static void io_worker_cancel_cb(struct io_worker *worker)
213 {
214 	struct io_wq_acct *acct = io_wq_get_acct(worker);
215 	struct io_wq *wq = worker->wq;
216 
217 	atomic_dec(&acct->nr_running);
218 	/* create_worker_cb() has not reserved a worker slot yet. */
219 	if (worker->create_work.func != create_worker_cb) {
220 		raw_spin_lock(&acct->workers_lock);
221 		acct->nr_workers--;
222 		raw_spin_unlock(&acct->workers_lock);
223 	}
224 	io_worker_ref_put(wq);
225 	clear_bit_unlock(0, &worker->create_state);
226 	io_worker_release(worker);
227 }
228 
229 static bool io_task_worker_match(struct callback_head *cb, void *data)
230 {
231 	struct io_worker *worker;
232 
233 	if (cb->func != create_worker_cb)
234 		return false;
235 	worker = container_of(cb, struct io_worker, create_work);
236 	return worker == data;
237 }
238 
239 static void io_worker_exit(struct io_worker *worker)
240 {
241 	struct io_wq *wq = worker->wq;
242 	struct io_wq_acct *acct = io_wq_get_acct(worker);
243 
244 	while (1) {
245 		struct callback_head *cb = task_work_cancel_match(wq->task,
246 						io_task_worker_match, worker);
247 
248 		if (!cb)
249 			break;
250 		io_worker_cancel_cb(worker);
251 	}
252 
253 	io_worker_release(worker);
254 	wait_for_completion(&worker->ref_done);
255 
256 	raw_spin_lock(&acct->workers_lock);
257 	if (test_bit(IO_WORKER_F_FREE, &worker->flags))
258 		hlist_nulls_del_rcu(&worker->nulls_node);
259 	list_del_rcu(&worker->all_list);
260 	raw_spin_unlock(&acct->workers_lock);
261 	io_wq_dec_running(worker);
262 	/*
263 	 * this worker is a goner, clear ->worker_private to avoid any
264 	 * inc/dec running calls that could happen as part of exit from
265 	 * touching 'worker'.
266 	 */
267 	current->worker_private = NULL;
268 
269 	kfree_rcu(worker, rcu);
270 	io_worker_ref_put(wq);
271 	do_exit(0);
272 }
273 
274 static inline bool __io_acct_run_queue(struct io_wq_acct *acct)
275 {
276 	return !test_bit(IO_ACCT_STALLED_BIT, &acct->flags) &&
277 		!wq_list_empty(&acct->work_list);
278 }
279 
280 /*
281  * If there's work to do, returns true with acct->lock acquired. If not,
282  * returns false with no lock held.
283  */
284 static inline bool io_acct_run_queue(struct io_wq_acct *acct)
285 	__acquires(&acct->lock)
286 {
287 	raw_spin_lock(&acct->lock);
288 	if (__io_acct_run_queue(acct))
289 		return true;
290 
291 	raw_spin_unlock(&acct->lock);
292 	return false;
293 }
294 
295 /*
296  * Check head of free list for an available worker. If one isn't available,
297  * caller must create one.
298  */
299 static bool io_acct_activate_free_worker(struct io_wq_acct *acct)
300 	__must_hold(RCU)
301 {
302 	struct hlist_nulls_node *n;
303 	struct io_worker *worker;
304 
305 	/*
306 	 * Iterate free_list and see if we can find an idle worker to
307 	 * activate. If a given worker is on the free_list but in the process
308 	 * of exiting, keep trying.
309 	 */
310 	hlist_nulls_for_each_entry_rcu(worker, n, &acct->free_list, nulls_node) {
311 		if (!io_worker_get(worker))
312 			continue;
313 		/*
314 		 * If the worker is already running, it's either already
315 		 * starting work or finishing work. In either case, if it does
316 		 * to go sleep, we'll kick off a new task for this work anyway.
317 		 */
318 		wake_up_process(worker->task);
319 		io_worker_release(worker);
320 		return true;
321 	}
322 
323 	return false;
324 }
325 
326 /*
327  * We need a worker. If we find a free one, we're good. If not, and we're
328  * below the max number of workers, create one.
329  */
330 static bool io_wq_create_worker(struct io_wq *wq, struct io_wq_acct *acct)
331 {
332 	/*
333 	 * Most likely an attempt to queue unbounded work on an io_wq that
334 	 * wasn't setup with any unbounded workers.
335 	 */
336 	if (unlikely(!acct->max_workers))
337 		pr_warn_once("io-wq is not configured for unbound workers");
338 
339 	raw_spin_lock(&acct->workers_lock);
340 	if (acct->nr_workers >= acct->max_workers) {
341 		raw_spin_unlock(&acct->workers_lock);
342 		return true;
343 	}
344 	acct->nr_workers++;
345 	raw_spin_unlock(&acct->workers_lock);
346 	atomic_inc(&acct->nr_running);
347 	atomic_inc(&wq->worker_refs);
348 	return create_io_worker(wq, acct);
349 }
350 
351 static void io_wq_inc_running(struct io_worker *worker)
352 {
353 	struct io_wq_acct *acct = io_wq_get_acct(worker);
354 
355 	atomic_inc(&acct->nr_running);
356 }
357 
358 static void create_worker_cb(struct callback_head *cb)
359 {
360 	struct io_worker *worker;
361 	struct io_wq *wq;
362 
363 	struct io_wq_acct *acct;
364 	bool activated_free_worker, do_create = false;
365 
366 	worker = container_of(cb, struct io_worker, create_work);
367 	wq = worker->wq;
368 	acct = worker->acct;
369 
370 	rcu_read_lock();
371 	activated_free_worker = io_acct_activate_free_worker(acct);
372 	rcu_read_unlock();
373 	if (activated_free_worker)
374 		goto no_need_create;
375 
376 	raw_spin_lock(&acct->workers_lock);
377 
378 	if (acct->nr_workers < acct->max_workers) {
379 		acct->nr_workers++;
380 		do_create = true;
381 	}
382 	raw_spin_unlock(&acct->workers_lock);
383 	if (do_create) {
384 		create_io_worker(wq, acct);
385 	} else {
386 no_need_create:
387 		atomic_dec(&acct->nr_running);
388 		io_worker_ref_put(wq);
389 	}
390 	clear_bit_unlock(0, &worker->create_state);
391 	io_worker_release(worker);
392 }
393 
394 static bool io_queue_worker_create(struct io_worker *worker,
395 				   struct io_wq_acct *acct,
396 				   task_work_func_t func)
397 {
398 	struct io_wq *wq = worker->wq;
399 
400 	/* raced with exit, just ignore create call */
401 	if (test_bit(IO_WQ_BIT_EXIT, &wq->state))
402 		goto fail;
403 	if (!io_worker_get(worker))
404 		goto fail;
405 	/*
406 	 * create_state manages ownership of create_work/index. We should
407 	 * only need one entry per worker, as the worker going to sleep
408 	 * will trigger the condition, and waking will clear it once it
409 	 * runs the task_work.
410 	 */
411 	if (test_bit(0, &worker->create_state) ||
412 	    test_and_set_bit_lock(0, &worker->create_state))
413 		goto fail_release;
414 
415 	atomic_inc(&wq->worker_refs);
416 	init_task_work(&worker->create_work, func);
417 	if (!task_work_add(wq->task, &worker->create_work, TWA_SIGNAL)) {
418 		/*
419 		 * EXIT may have been set after checking it above, check after
420 		 * adding the task_work and remove any creation item if it is
421 		 * now set. wq exit does that too, but we can have added this
422 		 * work item after we canceled in io_wq_exit_workers().
423 		 */
424 		if (test_bit(IO_WQ_BIT_EXIT, &wq->state))
425 			io_wq_cancel_tw_create(wq);
426 		io_worker_ref_put(wq);
427 		return true;
428 	}
429 	io_worker_ref_put(wq);
430 	clear_bit_unlock(0, &worker->create_state);
431 fail_release:
432 	io_worker_release(worker);
433 fail:
434 	atomic_dec(&acct->nr_running);
435 	io_worker_ref_put(wq);
436 	return false;
437 }
438 
439 /* Defer if current and next work are both hashed to the same chain */
440 static bool io_wq_hash_defer(struct io_wq_work *work, struct io_wq_acct *acct)
441 {
442 	unsigned int hash, work_flags;
443 	struct io_wq_work *next;
444 
445 	lockdep_assert_held(&acct->lock);
446 
447 	work_flags = atomic_read(&work->flags);
448 	if (!__io_wq_is_hashed(work_flags))
449 		return false;
450 
451 	/* should not happen, io_acct_run_queue() said we had work */
452 	if (wq_list_empty(&acct->work_list))
453 		return true;
454 
455 	hash = __io_get_work_hash(work_flags);
456 	next = container_of(acct->work_list.first, struct io_wq_work, list);
457 	work_flags = atomic_read(&next->flags);
458 	if (!__io_wq_is_hashed(work_flags))
459 		return false;
460 	return hash == __io_get_work_hash(work_flags);
461 }
462 
463 static void io_wq_dec_running(struct io_worker *worker)
464 {
465 	struct io_wq_acct *acct = io_wq_get_acct(worker);
466 	struct io_wq *wq = worker->wq;
467 
468 	if (!test_bit(IO_WORKER_F_UP, &worker->flags))
469 		return;
470 
471 	if (!atomic_dec_and_test(&acct->nr_running))
472 		return;
473 	if (!io_acct_run_queue(acct))
474 		return;
475 	if (worker->cur_work && io_wq_hash_defer(worker->cur_work, acct)) {
476 		raw_spin_unlock(&acct->lock);
477 		return;
478 	}
479 
480 	raw_spin_unlock(&acct->lock);
481 	atomic_inc(&acct->nr_running);
482 	atomic_inc(&wq->worker_refs);
483 	io_queue_worker_create(worker, acct, create_worker_cb);
484 }
485 
486 /*
487  * Worker will start processing some work. Move it to the busy list, if
488  * it's currently on the freelist
489  */
490 static void __io_worker_busy(struct io_wq_acct *acct, struct io_worker *worker)
491 {
492 	if (test_bit(IO_WORKER_F_FREE, &worker->flags)) {
493 		clear_bit(IO_WORKER_F_FREE, &worker->flags);
494 		raw_spin_lock(&acct->workers_lock);
495 		hlist_nulls_del_init_rcu(&worker->nulls_node);
496 		raw_spin_unlock(&acct->workers_lock);
497 	}
498 }
499 
500 /*
501  * No work, worker going to sleep. Move to freelist.
502  */
503 static void __io_worker_idle(struct io_wq_acct *acct, struct io_worker *worker)
504 	__must_hold(acct->workers_lock)
505 {
506 	if (!test_bit(IO_WORKER_F_FREE, &worker->flags)) {
507 		set_bit(IO_WORKER_F_FREE, &worker->flags);
508 		hlist_nulls_add_head_rcu(&worker->nulls_node, &acct->free_list);
509 	}
510 }
511 
512 static bool io_wait_on_hash(struct io_wq *wq, unsigned int hash)
513 {
514 	bool ret = false;
515 
516 	spin_lock_irq(&wq->hash->wait.lock);
517 	if (list_empty(&wq->wait.entry)) {
518 		__add_wait_queue(&wq->hash->wait, &wq->wait);
519 		if (!test_bit(hash, &wq->hash->map)) {
520 			__set_current_state(TASK_RUNNING);
521 			list_del_init(&wq->wait.entry);
522 			ret = true;
523 		}
524 	}
525 	spin_unlock_irq(&wq->hash->wait.lock);
526 	return ret;
527 }
528 
529 static struct io_wq_work *io_get_next_work(struct io_wq_acct *acct,
530 					   struct io_wq *wq,
531 					   bool *need_wake)
532 	__must_hold(acct->lock)
533 {
534 	struct io_wq_work_node *node, *prev;
535 	struct io_wq_work *work, *tail;
536 	unsigned int stall_hash = -1U;
537 
538 	wq_list_for_each(node, prev, &acct->work_list) {
539 		unsigned int work_flags;
540 		unsigned int hash;
541 
542 		work = container_of(node, struct io_wq_work, list);
543 
544 		/* not hashed, can run anytime */
545 		work_flags = atomic_read(&work->flags);
546 		if (!__io_wq_is_hashed(work_flags)) {
547 			wq_list_del(&acct->work_list, node, prev);
548 			return work;
549 		}
550 
551 		hash = __io_get_work_hash(work_flags);
552 		/* all items with this hash lie in [work, tail] */
553 		tail = wq->hash_tail[hash];
554 
555 		/* hashed, can run if not already running */
556 		if (!test_and_set_bit(hash, &wq->hash->map)) {
557 			wq->hash_tail[hash] = NULL;
558 			wq_list_cut(&acct->work_list, &tail->list, prev);
559 			return work;
560 		}
561 		if (stall_hash == -1U)
562 			stall_hash = hash;
563 		/* fast forward to a next hash, for-each will fix up @prev */
564 		node = &tail->list;
565 	}
566 
567 	if (stall_hash != -1U) {
568 		bool unstalled;
569 
570 		/*
571 		 * Set this before dropping the lock to avoid racing with new
572 		 * work being added and clearing the stalled bit.
573 		 */
574 		set_bit(IO_ACCT_STALLED_BIT, &acct->flags);
575 		raw_spin_unlock(&acct->lock);
576 		unstalled = io_wait_on_hash(wq, stall_hash);
577 		raw_spin_lock(&acct->lock);
578 		if (unstalled) {
579 			clear_bit(IO_ACCT_STALLED_BIT, &acct->flags);
580 			*need_wake = wq_has_sleeper(&wq->hash->wait);
581 		}
582 	}
583 
584 	return NULL;
585 }
586 
587 static void __io_assign_current_work(struct io_worker *worker,
588 				     struct io_wq_work *work)
589 {
590 	raw_spin_lock(&worker->lock);
591 	worker->cur_work = work;
592 	/* stays valid while in between two items of a chain */
593 	if (work)
594 		worker->next_work = wq_next_work(work);
595 	raw_spin_unlock(&worker->lock);
596 }
597 
598 static void io_assign_current_work(struct io_worker *worker,
599 				   struct io_wq_work *work)
600 {
601 	if (work) {
602 		io_run_task_work();
603 		cond_resched();
604 	}
605 
606 	__io_assign_current_work(worker, work);
607 }
608 
609 /*
610  * Called with acct->lock held, drops it before returning
611  */
612 static void io_worker_handle_work(struct io_wq_acct *acct,
613 				  struct io_worker *worker)
614 	__releases(&acct->lock)
615 {
616 	struct io_wq *wq = worker->wq;
617 
618 	do {
619 		struct io_wq_work *work;
620 		bool need_wake = false;
621 
622 		/*
623 		 * If we got some work, mark us as busy. If we didn't, but
624 		 * the list isn't empty, it means we stalled on hashed work.
625 		 * Mark us stalled so we don't keep looking for work when we
626 		 * can't make progress, any work completion or insertion will
627 		 * clear the stalled flag.
628 		 */
629 		work = io_get_next_work(acct, wq, &need_wake);
630 		if (work) {
631 			/*
632 			 * Make sure cancelation can find this, even before
633 			 * it becomes the active work. That avoids a window
634 			 * where the work has been removed from our general
635 			 * work list, but isn't yet discoverable as the
636 			 * current work item for this worker.
637 			 */
638 			__io_assign_current_work(worker, work);
639 		}
640 
641 		raw_spin_unlock(&acct->lock);
642 
643 		if (need_wake)
644 			wake_up(&wq->hash->wait);
645 
646 		if (!work)
647 			break;
648 
649 		__io_worker_busy(acct, worker);
650 
651 		io_assign_current_work(worker, work);
652 		__set_current_state(TASK_RUNNING);
653 
654 		/* handle a whole dependent link */
655 		do {
656 			bool do_kill = test_bit(IO_WQ_BIT_EXIT, &wq->state);
657 			struct io_wq_work *next_hashed, *linked, *done = work;
658 			unsigned int work_flags = atomic_read(&work->flags);
659 			unsigned int hash = __io_wq_is_hashed(work_flags)
660 				? __io_get_work_hash(work_flags)
661 				: -1U;
662 			struct io_kiocb *req;
663 			bool last;
664 
665 			next_hashed = wq_next_work(work);
666 
667 			/*
668 			 * io_wq_exit_workers() signals us once, so that we
669 			 * don't sleep for ever. If that was before this work
670 			 * became the current one, the signal is gone.
671 			 */
672 			if (do_kill && (work_flags & IO_WQ_WORK_UNBOUND))
673 				atomic_or(IO_WQ_WORK_CANCEL, &work->flags);
674 			else if (do_kill)
675 				set_notify_signal(current);
676 			req = container_of(work, struct io_kiocb, work);
677 			kcov_remote_start_common(req->ctx->kcov_handle);
678 			io_wq_submit_work(work);
679 			kcov_remote_stop();
680 			io_assign_current_work(worker, NULL);
681 
682 			last = io_wq_put_work(work, &linked);
683 			work = next_hashed;
684 			if (!work && linked && !io_wq_is_hashed(linked)) {
685 				work = linked;
686 				linked = NULL;
687 			}
688 			io_assign_current_work(worker, work);
689 			if (linked)
690 				io_wq_enqueue(wq, linked);
691 			/*
692 			 * Not before the link is current or pending work again.
693 			 * This may be the last time that a task is woken up
694 			 * which exits and looks for requests to cancel.
695 			 */
696 			if (last)
697 				io_wq_free_work(done);
698 
699 			if (hash != -1U && !next_hashed) {
700 				/* serialize hash clear with wake_up() */
701 				spin_lock_irq(&wq->hash->wait.lock);
702 				clear_bit(hash, &wq->hash->map);
703 				clear_bit(IO_ACCT_STALLED_BIT, &acct->flags);
704 				spin_unlock_irq(&wq->hash->wait.lock);
705 				if (wq_has_sleeper(&wq->hash->wait))
706 					wake_up(&wq->hash->wait);
707 			}
708 		} while (work);
709 
710 		if (!__io_acct_run_queue(acct))
711 			break;
712 		raw_spin_lock(&acct->lock);
713 	} while (1);
714 }
715 
716 /*
717  * The worker has decided to exit, and has given up its ->nr_workers slot and
718  * its place on the free list. io_wq_enqueue() may have picked it from that
719  * list, or seen it running, after it last looked at the work list. Leave
720  * ->nr_running as well and check again. Returns false if the worker has to
721  * stay.
722  */
723 static bool io_worker_retire(struct io_wq_acct *acct, struct io_worker *worker)
724 {
725 	/* turns io_wq_dec_running() and the scheduler hooks into no-ops */
726 	clear_bit(IO_WORKER_F_UP, &worker->flags);
727 	atomic_dec(&acct->nr_running);
728 	if (!io_acct_run_queue(acct))
729 		return true;
730 	raw_spin_unlock(&acct->lock);
731 
732 	raw_spin_lock(&acct->workers_lock);
733 	if (acct->nr_workers >= acct->max_workers) {
734 		/* a worker was created in our place, the work is its business */
735 		raw_spin_unlock(&acct->workers_lock);
736 		return true;
737 	}
738 	acct->nr_workers++;
739 	raw_spin_unlock(&acct->workers_lock);
740 	atomic_inc(&acct->nr_running);
741 	set_bit(IO_WORKER_F_UP, &worker->flags);
742 	return false;
743 }
744 
745 /*
746  * The CPUs a worker of @wq runs on: those of the io-wq affinity that the
747  * worker's cpuset allows, or the cpuset if they have none in common, as the
748  * scheduler does with a task's requested affinity when its cpuset changes.
749  * Read the cpuset each time: it can change while the io-wq exists.
750  */
751 static void io_wq_worker_cpus(struct io_wq *wq, struct task_struct *tsk,
752 			      struct cpumask *cpus)
753 {
754 	cpuset_cpus_allowed(tsk, cpus);
755 	if (cpumask_intersects(cpus, wq->cpu_mask))
756 		cpumask_and(cpus, cpus, wq->cpu_mask);
757 }
758 
759 /* Is the current worker on a CPU that a new worker would not get? */
760 static bool io_wq_worker_off_cpus(struct io_wq *wq)
761 {
762 	cpumask_var_t cpus;
763 	bool off;
764 
765 	if (!alloc_cpumask_var(&cpus, GFP_KERNEL))
766 		return false;
767 	io_wq_worker_cpus(wq, current, cpus);
768 	off = !cpumask_test_cpu(raw_smp_processor_id(), cpus);
769 	free_cpumask_var(cpus);
770 	return off;
771 }
772 
773 static int io_wq_worker(void *data)
774 {
775 	struct io_worker *worker = data;
776 	struct io_wq_acct *acct = io_wq_get_acct(worker);
777 	struct io_wq *wq = worker->wq;
778 	bool exit_mask = false, last_timeout = false;
779 	char buf[TASK_COMM_LEN] = {};
780 
781 	set_mask_bits(&worker->flags, 0,
782 		      BIT(IO_WORKER_F_UP) | BIT(IO_WORKER_F_RUNNING));
783 
784 	snprintf(buf, sizeof(buf), "iou-wrk-%d", wq->task->pid);
785 	set_task_comm(current, buf);
786 
787 	while (!test_bit(IO_WQ_BIT_EXIT, &wq->state)) {
788 		long ret;
789 
790 		set_current_state(TASK_INTERRUPTIBLE);
791 
792 		/*
793 		 * If we have work to do, io_acct_run_queue() returns with
794 		 * the acct->lock held. If not, it will drop it.
795 		 */
796 		while (io_acct_run_queue(acct))
797 			io_worker_handle_work(acct, worker);
798 
799 		raw_spin_lock(&acct->workers_lock);
800 		/*
801 		 * Last sleep timed out. Exit if we're not the last worker,
802 		 * or if someone modified our affinity. If wq is marked
803 		 * idle-exit, drop the worker as well. This is used to avoid
804 		 * keeping io-wq workers around for tasks that no longer have
805 		 * any active io_uring instances.
806 		 * Not as long as a request of ours for another worker is
807 		 * pending, though. It is accounted as a running worker, which
808 		 * others rely on, and io_worker_exit() would cancel it.
809 		 */
810 		if (((last_timeout && (exit_mask || acct->nr_workers > 1)) ||
811 		     test_bit(IO_WQ_BIT_EXIT_ON_IDLE, &wq->state)) &&
812 		    !test_bit(0, &worker->create_state)) {
813 			acct->nr_workers--;
814 			if (test_and_clear_bit(IO_WORKER_F_FREE, &worker->flags))
815 				hlist_nulls_del_init_rcu(&worker->nulls_node);
816 			raw_spin_unlock(&acct->workers_lock);
817 			__set_current_state(TASK_RUNNING);
818 			if (io_worker_retire(acct, worker))
819 				break;
820 			last_timeout = false;
821 			continue;
822 		}
823 		last_timeout = false;
824 		__io_worker_idle(acct, worker);
825 		raw_spin_unlock(&acct->workers_lock);
826 		if (io_run_task_work())
827 			continue;
828 		/*
829 		 * io_wq_enqueue() leaves new work to us for as long as we are
830 		 * accounted as running. Get out of ->nr_running before taking
831 		 * the last look at the work list, rather than when scheduling
832 		 * out. No need to ask for another worker then, we can do it.
833 		 */
834 		clear_bit(IO_WORKER_F_RUNNING, &worker->flags);
835 		atomic_dec(&acct->nr_running);
836 		if (io_acct_run_queue(acct)) {
837 			io_wq_worker_running(current);
838 			io_worker_handle_work(acct, worker);
839 			continue;
840 		}
841 		ret = schedule_timeout(WORKER_IDLE_TIMEOUT);
842 		if (signal_pending(current)) {
843 			struct ksignal ksig;
844 
845 			if (!get_signal(&ksig))
846 				continue;
847 			break;
848 		}
849 		if (!ret) {
850 			last_timeout = true;
851 			exit_mask = io_wq_worker_off_cpus(wq);
852 		}
853 	}
854 
855 	if (test_bit(IO_WQ_BIT_EXIT, &wq->state) && io_acct_run_queue(acct))
856 		io_worker_handle_work(acct, worker);
857 
858 	io_worker_exit(worker);
859 	return 0;
860 }
861 
862 /*
863  * Called when a worker is scheduled in. Mark us as currently running.
864  */
865 void io_wq_worker_running(struct task_struct *tsk)
866 {
867 	struct io_worker *worker = tsk->worker_private;
868 
869 	if (!worker)
870 		return;
871 	if (!test_bit(IO_WORKER_F_UP, &worker->flags))
872 		return;
873 	if (test_bit(IO_WORKER_F_RUNNING, &worker->flags))
874 		return;
875 	set_bit(IO_WORKER_F_RUNNING, &worker->flags);
876 	io_wq_inc_running(worker);
877 }
878 
879 /*
880  * Called when worker is going to sleep. If there are no workers currently
881  * running and we have work pending, wake up a free one or create a new one.
882  */
883 void io_wq_worker_sleeping(struct task_struct *tsk)
884 {
885 	struct io_worker *worker = tsk->worker_private;
886 
887 	if (!worker)
888 		return;
889 	if (!test_bit(IO_WORKER_F_UP, &worker->flags))
890 		return;
891 	if (!test_bit(IO_WORKER_F_RUNNING, &worker->flags))
892 		return;
893 
894 	clear_bit(IO_WORKER_F_RUNNING, &worker->flags);
895 	io_wq_dec_running(worker);
896 }
897 
898 static void io_init_new_worker(struct io_wq *wq, struct io_wq_acct *acct, struct io_worker *worker,
899 			       struct task_struct *tsk)
900 {
901 	cpumask_var_t cpus;
902 
903 	tsk->worker_private = worker;
904 	worker->task = tsk;
905 	/* Without a mask, the worker keeps its creator's CPUs. */
906 	if (alloc_cpumask_var(&cpus, GFP_KERNEL)) {
907 		io_wq_worker_cpus(wq, tsk, cpus);
908 		set_cpus_allowed_ptr(tsk, cpus);
909 		free_cpumask_var(cpus);
910 	}
911 
912 	raw_spin_lock(&acct->workers_lock);
913 	hlist_nulls_add_head_rcu(&worker->nulls_node, &acct->free_list);
914 	list_add_tail_rcu(&worker->all_list, &acct->all_list);
915 	set_bit(IO_WORKER_F_FREE, &worker->flags);
916 	raw_spin_unlock(&acct->workers_lock);
917 	wake_up_new_task(tsk);
918 }
919 
920 static bool io_wq_work_match_all(struct io_wq_work *work, void *data)
921 {
922 	return true;
923 }
924 
925 static inline bool io_should_retry_thread(struct io_worker *worker, long err)
926 {
927 	/*
928 	 * Prevent perpetual task_work retry, if the task (or its group) is
929 	 * exiting.
930 	 */
931 	if (fatal_signal_pending(current))
932 		return false;
933 
934 	worker->init_retries++;
935 	switch (err) {
936 	case -EAGAIN:
937 		return worker->init_retries <= WORKER_INIT_LIMIT;
938 	/* Analogous to a fork() syscall, always retry on a restartable error */
939 	case -ERESTARTSYS:
940 	case -ERESTARTNOINTR:
941 	case -ERESTARTNOHAND:
942 		return true;
943 	default:
944 		return false;
945 	}
946 }
947 
948 static void queue_create_worker_retry(struct io_worker *worker)
949 {
950 	/*
951 	 * We only bother retrying because there's a chance that the
952 	 * failure to create a worker is due to some temporary condition
953 	 * in the forking task (e.g. outstanding signal); give the task
954 	 * some time to clear that condition.
955 	 */
956 	schedule_delayed_work(&worker->work,
957 			      msecs_to_jiffies(worker->init_retries * 5));
958 }
959 
960 static void create_worker_cont(struct callback_head *cb)
961 {
962 	struct io_worker *worker;
963 	struct task_struct *tsk;
964 	struct io_wq *wq;
965 	struct io_wq_acct *acct;
966 
967 	worker = container_of(cb, struct io_worker, create_work);
968 	clear_bit_unlock(0, &worker->create_state);
969 	wq = worker->wq;
970 	acct = io_wq_get_acct(worker);
971 	tsk = create_io_thread(io_wq_worker, worker, NUMA_NO_NODE);
972 	if (!IS_ERR(tsk)) {
973 		io_init_new_worker(wq, acct, worker, tsk);
974 		io_worker_release(worker);
975 		return;
976 	} else if (!io_should_retry_thread(worker, PTR_ERR(tsk))) {
977 		atomic_dec(&acct->nr_running);
978 		raw_spin_lock(&acct->workers_lock);
979 		acct->nr_workers--;
980 		if (!acct->nr_workers) {
981 			struct io_cb_cancel_data match = {
982 				.fn		= io_wq_work_match_all,
983 				.cancel_all	= true,
984 			};
985 
986 			raw_spin_unlock(&acct->workers_lock);
987 			while (io_acct_cancel_pending_work(wq, acct, &match))
988 				;
989 		} else {
990 			raw_spin_unlock(&acct->workers_lock);
991 		}
992 		io_worker_ref_put(wq);
993 		kfree(worker);
994 		return;
995 	}
996 
997 	/* re-create attempts grab a new worker ref, drop the existing one */
998 	io_worker_release(worker);
999 	queue_create_worker_retry(worker);
1000 }
1001 
1002 static void io_workqueue_create(struct work_struct *work)
1003 {
1004 	struct io_worker *worker = container_of(work, struct io_worker,
1005 						work.work);
1006 	struct io_wq_acct *acct = io_wq_get_acct(worker);
1007 
1008 	if (!io_queue_worker_create(worker, acct, create_worker_cont))
1009 		kfree(worker);
1010 }
1011 
1012 static bool create_io_worker(struct io_wq *wq, struct io_wq_acct *acct)
1013 {
1014 	struct io_worker *worker;
1015 	struct task_struct *tsk;
1016 
1017 	__set_current_state(TASK_RUNNING);
1018 
1019 	worker = kzalloc_obj(*worker);
1020 	if (!worker) {
1021 fail:
1022 		atomic_dec(&acct->nr_running);
1023 		raw_spin_lock(&acct->workers_lock);
1024 		acct->nr_workers--;
1025 		raw_spin_unlock(&acct->workers_lock);
1026 		io_worker_ref_put(wq);
1027 		return false;
1028 	}
1029 
1030 	refcount_set(&worker->ref, 1);
1031 	worker->wq = wq;
1032 	worker->acct = acct;
1033 	raw_spin_lock_init(&worker->lock);
1034 	init_completion(&worker->ref_done);
1035 
1036 	tsk = create_io_thread(io_wq_worker, worker, NUMA_NO_NODE);
1037 	if (!IS_ERR(tsk)) {
1038 		io_init_new_worker(wq, acct, worker, tsk);
1039 	} else if (!io_should_retry_thread(worker, PTR_ERR(tsk))) {
1040 		kfree(worker);
1041 		goto fail;
1042 	} else {
1043 		INIT_DELAYED_WORK(&worker->work, io_workqueue_create);
1044 		queue_create_worker_retry(worker);
1045 	}
1046 
1047 	return true;
1048 }
1049 
1050 /*
1051  * Iterate the passed in list and call the specific function for each
1052  * worker that isn't exiting
1053  */
1054 static bool io_acct_for_each_worker(struct io_wq_acct *acct,
1055 				    bool (*func)(struct io_worker *, void *),
1056 				    void *data)
1057 {
1058 	struct io_worker *worker;
1059 	bool ret = false;
1060 
1061 	list_for_each_entry_rcu(worker, &acct->all_list, all_list) {
1062 		if (io_worker_get(worker)) {
1063 			/* no task if node is/was offline */
1064 			if (worker->task)
1065 				ret = func(worker, data);
1066 			io_worker_release(worker);
1067 			if (ret)
1068 				break;
1069 		}
1070 	}
1071 
1072 	return ret;
1073 }
1074 
1075 static void io_wq_for_each_worker(struct io_wq *wq,
1076 				  bool (*func)(struct io_worker *, void *),
1077 				  void *data)
1078 {
1079 	for (int i = 0; i < IO_WQ_ACCT_NR; i++)
1080 		if (io_acct_for_each_worker(&wq->acct[i], func, data))
1081 			break;
1082 }
1083 
1084 static bool io_wq_worker_wake(struct io_worker *worker, void *data)
1085 {
1086 	set_tsk_thread_flag(worker->task, TIF_NOTIFY_SIGNAL);
1087 	wake_up_process(worker->task);
1088 	return false;
1089 }
1090 
1091 void io_wq_set_exit_on_idle(struct io_wq *wq, bool enable)
1092 {
1093 	if (!wq->task)
1094 		return;
1095 
1096 	if (!enable) {
1097 		clear_bit(IO_WQ_BIT_EXIT_ON_IDLE, &wq->state);
1098 		return;
1099 	}
1100 
1101 	if (test_and_set_bit(IO_WQ_BIT_EXIT_ON_IDLE, &wq->state))
1102 		return;
1103 
1104 	rcu_read_lock();
1105 	io_wq_for_each_worker(wq, io_wq_worker_wake, NULL);
1106 	rcu_read_unlock();
1107 }
1108 
1109 static void io_run_cancel(struct io_wq_work *work, struct io_wq *wq)
1110 {
1111 	do {
1112 		struct io_wq_work *linked;
1113 
1114 		atomic_or(IO_WQ_WORK_CANCEL, &work->flags);
1115 		io_wq_submit_work(work);
1116 		if (io_wq_put_work(work, &linked))
1117 			io_wq_free_work(work);
1118 		work = linked;
1119 	} while (work);
1120 }
1121 
1122 static void io_wq_insert_work(struct io_wq *wq, struct io_wq_acct *acct,
1123 			      struct io_wq_work *work, unsigned int work_flags)
1124 {
1125 	unsigned int hash;
1126 	struct io_wq_work *tail;
1127 
1128 	if (!__io_wq_is_hashed(work_flags)) {
1129 append:
1130 		wq_list_add_tail(&work->list, &acct->work_list);
1131 		return;
1132 	}
1133 
1134 	hash = __io_get_work_hash(work_flags);
1135 	tail = wq->hash_tail[hash];
1136 	wq->hash_tail[hash] = work;
1137 	if (!tail)
1138 		goto append;
1139 
1140 	wq_list_add_after(&work->list, &tail->list, &acct->work_list);
1141 }
1142 
1143 static bool io_wq_work_match_item(struct io_wq_work *work, void *data)
1144 {
1145 	return work == data;
1146 }
1147 
1148 void io_wq_enqueue(struct io_wq *wq, struct io_wq_work *work)
1149 {
1150 	unsigned int work_flags = atomic_read(&work->flags);
1151 	struct io_wq_acct *acct = io_work_get_acct(wq, work_flags);
1152 	struct io_cb_cancel_data match = {
1153 		.fn		= io_wq_work_match_item,
1154 		.data		= work,
1155 		.cancel_all	= false,
1156 	};
1157 	bool do_create;
1158 
1159 	/*
1160 	 * If io-wq is exiting for this task, or if the request has explicitly
1161 	 * been marked as one that should not get executed, cancel it here.
1162 	 */
1163 	if (test_bit(IO_WQ_BIT_EXIT, &wq->state) ||
1164 	    (work_flags & IO_WQ_WORK_CANCEL)) {
1165 		io_run_cancel(work, wq);
1166 		return;
1167 	}
1168 
1169 	raw_spin_lock(&acct->lock);
1170 	io_wq_insert_work(wq, acct, work, work_flags);
1171 	clear_bit(IO_ACCT_STALLED_BIT, &acct->flags);
1172 	raw_spin_unlock(&acct->lock);
1173 
1174 	rcu_read_lock();
1175 	do_create = !io_acct_activate_free_worker(acct);
1176 	rcu_read_unlock();
1177 
1178 	if (do_create && ((work_flags & IO_WQ_WORK_CONCURRENT) ||
1179 	    !atomic_read(&acct->nr_running))) {
1180 		bool did_create;
1181 
1182 		did_create = io_wq_create_worker(wq, acct);
1183 		if (likely(did_create))
1184 			return;
1185 
1186 		raw_spin_lock(&acct->workers_lock);
1187 		if (acct->nr_workers) {
1188 			raw_spin_unlock(&acct->workers_lock);
1189 			return;
1190 		}
1191 		raw_spin_unlock(&acct->workers_lock);
1192 
1193 		/* fatal condition, failed to create the first worker */
1194 		io_acct_cancel_pending_work(wq, acct, &match);
1195 	}
1196 }
1197 
1198 /*
1199  * Work items that hash to the same value will not be done in parallel.
1200  * Used to limit concurrent writes, generally hashed by inode.
1201  */
1202 void io_wq_hash_work(struct io_wq_work *work, void *val)
1203 {
1204 	unsigned int bit;
1205 
1206 	bit = hash_ptr(val, IO_WQ_HASH_ORDER);
1207 	atomic_or(IO_WQ_WORK_HASHED | (bit << IO_WQ_HASH_SHIFT), &work->flags);
1208 }
1209 
1210 static bool __io_wq_worker_cancel(struct io_worker *worker,
1211 				  struct io_cb_cancel_data *match,
1212 				  struct io_wq_work *work)
1213 {
1214 	if (work && match->fn(work, match->data)) {
1215 		atomic_or(IO_WQ_WORK_CANCEL, &work->flags);
1216 		__set_notify_signal(worker->task);
1217 		return true;
1218 	}
1219 
1220 	return false;
1221 }
1222 
1223 static bool io_wq_worker_cancel(struct io_worker *worker, void *data)
1224 {
1225 	struct io_cb_cancel_data *match = data;
1226 	struct io_wq_work *work;
1227 
1228 	/*
1229 	 * Hold the lock to avoid ->cur_work going out of scope, caller
1230 	 * may dereference the passed in work.
1231 	 */
1232 	raw_spin_lock(&worker->lock);
1233 	if (__io_wq_worker_cancel(worker, match, worker->cur_work))
1234 		match->nr_running++;
1235 	/*
1236 	 * Hashed work is taken off the work list a chain at a time, what the
1237 	 * worker hasn't started yet can only be found here. It doesn't move on
1238 	 * without the lock. Just mark the work, it fails once it is its turn.
1239 	 */
1240 	for (work = worker->next_work; work; work = wq_next_work(work)) {
1241 		if (match->nr_running && !match->cancel_all)
1242 			break;
1243 		if (match->fn(work, match->data)) {
1244 			atomic_or(IO_WQ_WORK_CANCEL, &work->flags);
1245 			match->nr_running++;
1246 		}
1247 	}
1248 	raw_spin_unlock(&worker->lock);
1249 
1250 	return match->nr_running && !match->cancel_all;
1251 }
1252 
1253 static inline void io_wq_remove_pending(struct io_wq *wq,
1254 					struct io_wq_acct *acct,
1255 					 struct io_wq_work *work,
1256 					 struct io_wq_work_node *prev)
1257 {
1258 	unsigned int hash = io_get_work_hash(work);
1259 	struct io_wq_work *prev_work = NULL;
1260 
1261 	if (io_wq_is_hashed(work) && work == wq->hash_tail[hash]) {
1262 		if (prev)
1263 			prev_work = container_of(prev, struct io_wq_work, list);
1264 		if (prev_work && io_wq_is_hashed(prev_work) &&
1265 		    io_get_work_hash(prev_work) == hash)
1266 			wq->hash_tail[hash] = prev_work;
1267 		else
1268 			wq->hash_tail[hash] = NULL;
1269 	}
1270 	wq_list_del(&acct->work_list, &work->list, prev);
1271 }
1272 
1273 static bool io_acct_cancel_pending_work(struct io_wq *wq,
1274 					struct io_wq_acct *acct,
1275 					struct io_cb_cancel_data *match)
1276 {
1277 	struct io_wq_work_node *node, *prev;
1278 	struct io_wq_work *work;
1279 
1280 	raw_spin_lock(&acct->lock);
1281 	wq_list_for_each(node, prev, &acct->work_list) {
1282 		work = container_of(node, struct io_wq_work, list);
1283 		if (!match->fn(work, match->data))
1284 			continue;
1285 		io_wq_remove_pending(wq, acct, work, prev);
1286 		raw_spin_unlock(&acct->lock);
1287 		io_run_cancel(work, wq);
1288 		match->nr_pending++;
1289 		/* not safe to continue after unlock */
1290 		return true;
1291 	}
1292 	raw_spin_unlock(&acct->lock);
1293 
1294 	return false;
1295 }
1296 
1297 static void io_wq_cancel_pending_work(struct io_wq *wq,
1298 				      struct io_cb_cancel_data *match)
1299 {
1300 	int i;
1301 retry:
1302 	for (i = 0; i < IO_WQ_ACCT_NR; i++) {
1303 		struct io_wq_acct *acct = io_get_acct(wq, i == 0);
1304 
1305 		if (io_acct_cancel_pending_work(wq, acct, match)) {
1306 			if (match->cancel_all)
1307 				goto retry;
1308 			break;
1309 		}
1310 	}
1311 }
1312 
1313 static void io_acct_cancel_running_work(struct io_wq_acct *acct,
1314 					struct io_cb_cancel_data *match)
1315 {
1316 	raw_spin_lock(&acct->workers_lock);
1317 	io_acct_for_each_worker(acct, io_wq_worker_cancel, match);
1318 	raw_spin_unlock(&acct->workers_lock);
1319 }
1320 
1321 static void io_wq_cancel_running_work(struct io_wq *wq,
1322 				       struct io_cb_cancel_data *match)
1323 {
1324 	rcu_read_lock();
1325 
1326 	for (int i = 0; i < IO_WQ_ACCT_NR; i++)
1327 		io_acct_cancel_running_work(&wq->acct[i], match);
1328 
1329 	rcu_read_unlock();
1330 }
1331 
1332 enum io_wq_cancel io_wq_cancel_cb(struct io_wq *wq, work_cancel_fn *cancel,
1333 				  void *data, bool cancel_all)
1334 {
1335 	struct io_cb_cancel_data match = {
1336 		.fn		= cancel,
1337 		.data		= data,
1338 		.cancel_all	= cancel_all,
1339 	};
1340 
1341 	/*
1342 	 * First check pending list, if we're lucky we can just remove it
1343 	 * from there. CANCEL_OK means that the work is returned as-new,
1344 	 * no completion will be posted for it.
1345 	 *
1346 	 * Then check if a free (going busy) or busy worker has the work
1347 	 * currently running. If we find it there, we'll return CANCEL_RUNNING
1348 	 * as an indication that we attempt to signal cancellation. The
1349 	 * completion will run normally in this case.
1350 	 *
1351 	 * Do both of these while holding the acct->workers_lock, to ensure that
1352 	 * we'll find a work item regardless of state.
1353 	 */
1354 	io_wq_cancel_pending_work(wq, &match);
1355 	if (match.nr_pending && !match.cancel_all)
1356 		return IO_WQ_CANCEL_OK;
1357 
1358 	io_wq_cancel_running_work(wq, &match);
1359 	if (match.nr_running && !match.cancel_all)
1360 		return IO_WQ_CANCEL_RUNNING;
1361 
1362 	if (match.nr_running)
1363 		return IO_WQ_CANCEL_RUNNING;
1364 	if (match.nr_pending)
1365 		return IO_WQ_CANCEL_OK;
1366 	return IO_WQ_CANCEL_NOTFOUND;
1367 }
1368 
1369 static int io_wq_hash_wake(struct wait_queue_entry *wait, unsigned mode,
1370 			    int sync, void *key)
1371 {
1372 	struct io_wq *wq = container_of(wait, struct io_wq, wait);
1373 	int i;
1374 
1375 	list_del_init(&wait->entry);
1376 
1377 	rcu_read_lock();
1378 	for (i = 0; i < IO_WQ_ACCT_NR; i++) {
1379 		struct io_wq_acct *acct = &wq->acct[i];
1380 
1381 		if (test_and_clear_bit(IO_ACCT_STALLED_BIT, &acct->flags))
1382 			io_acct_activate_free_worker(acct);
1383 	}
1384 	rcu_read_unlock();
1385 	return 1;
1386 }
1387 
1388 struct io_wq *io_wq_create(unsigned bounded, struct io_wq_data *data)
1389 {
1390 	int ret, i;
1391 	struct io_wq *wq;
1392 
1393 	if (WARN_ON_ONCE(!bounded))
1394 		return ERR_PTR(-EINVAL);
1395 
1396 	wq = kzalloc_obj(struct io_wq);
1397 	if (!wq)
1398 		return ERR_PTR(-ENOMEM);
1399 
1400 	refcount_inc(&data->hash->refs);
1401 	wq->hash = data->hash;
1402 
1403 	ret = -ENOMEM;
1404 
1405 	if (!alloc_cpumask_var(&wq->cpu_mask, GFP_KERNEL))
1406 		goto err;
1407 	cpumask_copy(wq->cpu_mask, cpu_possible_mask);
1408 	wq->acct[IO_WQ_ACCT_BOUND].max_workers = bounded;
1409 	wq->acct[IO_WQ_ACCT_UNBOUND].max_workers =
1410 				task_rlimit(current, RLIMIT_NPROC);
1411 	INIT_LIST_HEAD(&wq->wait.entry);
1412 	wq->wait.func = io_wq_hash_wake;
1413 	for (i = 0; i < IO_WQ_ACCT_NR; i++) {
1414 		struct io_wq_acct *acct = &wq->acct[i];
1415 
1416 		atomic_set(&acct->nr_running, 0);
1417 
1418 		raw_spin_lock_init(&acct->workers_lock);
1419 		INIT_HLIST_NULLS_HEAD(&acct->free_list, 0);
1420 		INIT_LIST_HEAD(&acct->all_list);
1421 
1422 		INIT_WQ_LIST(&acct->work_list);
1423 		raw_spin_lock_init(&acct->lock);
1424 	}
1425 
1426 	wq->task = get_task_struct(data->task);
1427 	atomic_set(&wq->worker_refs, 1);
1428 	init_completion(&wq->worker_done);
1429 	ret = cpuhp_state_add_instance_nocalls(io_wq_online, &wq->cpuhp_node);
1430 	if (ret) {
1431 		put_task_struct(wq->task);
1432 		goto err;
1433 	}
1434 
1435 	return wq;
1436 err:
1437 	io_wq_put_hash(data->hash);
1438 	free_cpumask_var(wq->cpu_mask);
1439 	kfree(wq);
1440 	return ERR_PTR(ret);
1441 }
1442 
1443 static bool io_task_work_match(struct callback_head *cb, void *data)
1444 {
1445 	struct io_worker *worker;
1446 
1447 	if (cb->func != create_worker_cb && cb->func != create_worker_cont)
1448 		return false;
1449 	worker = container_of(cb, struct io_worker, create_work);
1450 	return worker->wq == data;
1451 }
1452 
1453 void io_wq_exit_start(struct io_wq *wq)
1454 {
1455 	set_bit(IO_WQ_BIT_EXIT, &wq->state);
1456 	/* Pairs with task_work_add() in io_queue_worker_create(). */
1457 	smp_mb__after_atomic();
1458 	/*
1459 	 * No more workers from here on. The caller is going to run its task
1460 	 * work, and on exec a thread that is created now would still be
1461 	 * around, exiting, by the time that the caller must be on its own.
1462 	 */
1463 	io_wq_cancel_tw_create(wq);
1464 }
1465 
1466 static void io_wq_cancel_tw_create(struct io_wq *wq)
1467 {
1468 	struct callback_head *cb;
1469 
1470 	while ((cb = task_work_cancel_match(wq->task, io_task_work_match, wq)) != NULL) {
1471 		struct io_worker *worker;
1472 		bool free_worker;
1473 
1474 		worker = container_of(cb, struct io_worker, create_work);
1475 		/*
1476 		 * Only the worker continuation helper has worker allocated and
1477 		 * hence needs freeing. Save this before dropping its reference.
1478 		 */
1479 		free_worker = cb->func == create_worker_cont;
1480 		io_worker_cancel_cb(worker);
1481 		if (free_worker)
1482 			kfree(worker);
1483 	}
1484 }
1485 
1486 static bool io_wq_worker_show(struct io_worker *worker, void *data)
1487 {
1488 	sched_show_task(worker->task);
1489 	return false;
1490 }
1491 
1492 /* The exit path is always the same, show what the workers are stuck on */
1493 static void io_wq_show_stuck_workers(struct io_wq *wq)
1494 {
1495 	pr_warn("io-wq: %s/%d stuck waiting for workers to exit\n",
1496 		current->comm, task_pid_nr(current));
1497 	rcu_read_lock();
1498 	io_wq_for_each_worker(wq, io_wq_worker_show, NULL);
1499 	rcu_read_unlock();
1500 }
1501 
1502 static void io_wq_exit_workers(struct io_wq *wq)
1503 {
1504 	unsigned long timeout, warn_timeout;
1505 
1506 	if (!wq->task)
1507 		return;
1508 
1509 	io_wq_cancel_tw_create(wq);
1510 
1511 	rcu_read_lock();
1512 	io_wq_for_each_worker(wq, io_wq_worker_wake, NULL);
1513 	rcu_read_unlock();
1514 	io_worker_ref_put(wq);
1515 
1516 	/*
1517 	 * Shut up hung task complaint, see for example
1518 	 *
1519 	 * https://lore.kernel.org/all/696fc9e7.a70a0220.111c58.0006.GAE@google.com/
1520 	 *
1521 	 * where completely overloading the system with tons of long running
1522 	 * io-wq items can easily trigger the hung task timeout. Only sleep
1523 	 * uninterruptibly for half that time, and show the stuck workers if
1524 	 * we end up waiting more than IO_URING_EXIT_WAIT_MAX.
1525 	 */
1526 	timeout = sysctl_hung_task_timeout_secs * HZ / 2;
1527 	if (!timeout)
1528 		timeout = MAX_SCHEDULE_TIMEOUT;
1529 	warn_timeout = jiffies + IO_URING_EXIT_WAIT_MAX;
1530 	do {
1531 		if (wait_for_completion_timeout(&wq->worker_done, timeout))
1532 			break;
1533 		if (time_after(jiffies, warn_timeout))
1534 			DO_ONCE_LITE(io_wq_show_stuck_workers, wq);
1535 	} while (1);
1536 
1537 	spin_lock_irq(&wq->hash->wait.lock);
1538 	list_del_init(&wq->wait.entry);
1539 	spin_unlock_irq(&wq->hash->wait.lock);
1540 
1541 	put_task_struct(wq->task);
1542 	wq->task = NULL;
1543 }
1544 
1545 static void io_wq_destroy(struct io_wq *wq)
1546 {
1547 	struct io_cb_cancel_data match = {
1548 		.fn		= io_wq_work_match_all,
1549 		.cancel_all	= true,
1550 	};
1551 
1552 	cpuhp_state_remove_instance_nocalls(io_wq_online, &wq->cpuhp_node);
1553 	io_wq_cancel_pending_work(wq, &match);
1554 	free_cpumask_var(wq->cpu_mask);
1555 	io_wq_put_hash(wq->hash);
1556 	kfree(wq);
1557 }
1558 
1559 void io_wq_put_and_exit(struct io_wq *wq)
1560 {
1561 	WARN_ON_ONCE(!test_bit(IO_WQ_BIT_EXIT, &wq->state));
1562 
1563 	io_wq_exit_workers(wq);
1564 	io_wq_destroy(wq);
1565 }
1566 
1567 struct online_data {
1568 	unsigned int cpu;
1569 	bool online;
1570 };
1571 
1572 static bool io_wq_worker_affinity(struct io_worker *worker, void *data)
1573 {
1574 	struct online_data *od = data;
1575 
1576 	if (od->online)
1577 		cpumask_set_cpu(od->cpu, worker->wq->cpu_mask);
1578 	else
1579 		cpumask_clear_cpu(od->cpu, worker->wq->cpu_mask);
1580 	return false;
1581 }
1582 
1583 static int __io_wq_cpu_online(struct io_wq *wq, unsigned int cpu, bool online)
1584 {
1585 	struct online_data od = {
1586 		.cpu = cpu,
1587 		.online = online
1588 	};
1589 
1590 	rcu_read_lock();
1591 	io_wq_for_each_worker(wq, io_wq_worker_affinity, &od);
1592 	rcu_read_unlock();
1593 	return 0;
1594 }
1595 
1596 static int io_wq_cpu_online(unsigned int cpu, struct hlist_node *node)
1597 {
1598 	struct io_wq *wq = hlist_entry_safe(node, struct io_wq, cpuhp_node);
1599 
1600 	return __io_wq_cpu_online(wq, cpu, true);
1601 }
1602 
1603 static int io_wq_cpu_offline(unsigned int cpu, struct hlist_node *node)
1604 {
1605 	struct io_wq *wq = hlist_entry_safe(node, struct io_wq, cpuhp_node);
1606 
1607 	return __io_wq_cpu_online(wq, cpu, false);
1608 }
1609 
1610 int io_wq_cpu_affinity(struct io_uring_task *tctx, cpumask_var_t mask)
1611 {
1612 	cpumask_var_t allowed_mask;
1613 	int ret = 0;
1614 
1615 	if (!tctx || !tctx->io_wq)
1616 		return -EINVAL;
1617 
1618 	if (!alloc_cpumask_var(&allowed_mask, GFP_KERNEL))
1619 		return -ENOMEM;
1620 
1621 	rcu_read_lock();
1622 	cpuset_cpus_allowed(tctx->io_wq->task, allowed_mask);
1623 	if (mask) {
1624 		if (cpumask_subset(mask, allowed_mask))
1625 			cpumask_copy(tctx->io_wq->cpu_mask, mask);
1626 		else
1627 			ret = -EINVAL;
1628 	} else {
1629 		cpumask_copy(tctx->io_wq->cpu_mask, cpu_possible_mask);
1630 	}
1631 	rcu_read_unlock();
1632 
1633 	free_cpumask_var(allowed_mask);
1634 	return ret;
1635 }
1636 
1637 /*
1638  * Set max number of unbounded workers, returns old value. If new_count is 0,
1639  * then just return the old value.
1640  */
1641 int io_wq_max_workers(struct io_wq *wq, int *new_count)
1642 {
1643 	struct io_wq_acct *acct;
1644 	int prev[IO_WQ_ACCT_NR];
1645 	int i;
1646 
1647 	BUILD_BUG_ON((int) IO_WQ_ACCT_BOUND   != (int) IO_WQ_BOUND);
1648 	BUILD_BUG_ON((int) IO_WQ_ACCT_UNBOUND != (int) IO_WQ_UNBOUND);
1649 	BUILD_BUG_ON((int) IO_WQ_ACCT_NR      != 2);
1650 
1651 	for (i = 0; i < IO_WQ_ACCT_NR; i++) {
1652 		if (new_count[i] > task_rlimit(current, RLIMIT_NPROC))
1653 			new_count[i] = task_rlimit(current, RLIMIT_NPROC);
1654 	}
1655 
1656 	for (i = 0; i < IO_WQ_ACCT_NR; i++)
1657 		prev[i] = 0;
1658 
1659 	rcu_read_lock();
1660 
1661 	for (i = 0; i < IO_WQ_ACCT_NR; i++) {
1662 		acct = &wq->acct[i];
1663 		raw_spin_lock(&acct->workers_lock);
1664 		prev[i] = max_t(int, acct->max_workers, prev[i]);
1665 		if (new_count[i])
1666 			acct->max_workers = new_count[i];
1667 		raw_spin_unlock(&acct->workers_lock);
1668 	}
1669 	rcu_read_unlock();
1670 
1671 	for (i = 0; i < IO_WQ_ACCT_NR; i++)
1672 		new_count[i] = prev[i];
1673 
1674 	return 0;
1675 }
1676 
1677 static __init int io_wq_init(void)
1678 {
1679 	int ret;
1680 
1681 	ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "io-wq/online",
1682 					io_wq_cpu_online, io_wq_cpu_offline);
1683 	if (ret < 0)
1684 		return ret;
1685 	io_wq_online = ret;
1686 	return 0;
1687 }
1688 subsys_initcall(io_wq_init);
1689