xref: /linux/block/blk-cgroup.c (revision ba9c792c824fff732df85119011d399d9b6d9155)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Common Block IO controller cgroup interface
4  *
5  * Based on ideas and code from CFQ, CFS and BFQ:
6  * Copyright (C) 2003 Jens Axboe <axboe@kernel.dk>
7  *
8  * Copyright (C) 2008 Fabio Checconi <fabio@gandalf.sssup.it>
9  *		      Paolo Valente <paolo.valente@unimore.it>
10  *
11  * Copyright (C) 2009 Vivek Goyal <vgoyal@redhat.com>
12  * 	              Nauman Rafique <nauman@google.com>
13  *
14  * For policy-specific per-blkcg data:
15  * Copyright (C) 2015 Paolo Valente <paolo.valente@unimore.it>
16  *                    Arianna Avanzini <avanzini.arianna@gmail.com>
17  */
18 #include <linux/ioprio.h>
19 #include <linux/kdev_t.h>
20 #include <linux/module.h>
21 #include <linux/sched/signal.h>
22 #include <linux/err.h>
23 #include <linux/blkdev.h>
24 #include <linux/backing-dev.h>
25 #include <linux/slab.h>
26 #include <linux/delay.h>
27 #include <linux/wait_bit.h>
28 #include <linux/atomic.h>
29 #include <linux/ctype.h>
30 #include <linux/resume_user_mode.h>
31 #include <linux/psi.h>
32 #include <linux/part_stat.h>
33 #include "blk.h"
34 #include "blk-cgroup.h"
35 #include "blk-ioprio.h"
36 #include "blk-throttle.h"
37 
38 static void __blkcg_rstat_flush(struct blkcg *blkcg, int cpu);
39 
40 /*
41  * blkcg_pol_mutex protects blkcg_policy[] and policy [de]activation.
42  * blkcg_pol_register_mutex nests outside of it and synchronizes entire
43  * policy [un]register operations including cgroup file additions /
44  * removals.  Putting cgroup file registration outside blkcg_pol_mutex
45  * allows grabbing it from cgroup callbacks.
46  */
47 static DEFINE_MUTEX(blkcg_pol_register_mutex);
48 static DEFINE_MUTEX(blkcg_pol_mutex);
49 
50 struct blkcg blkcg_root;
51 EXPORT_SYMBOL_GPL(blkcg_root);
52 
53 struct cgroup_subsys_state * const blkcg_root_css = &blkcg_root.css;
54 EXPORT_SYMBOL_GPL(blkcg_root_css);
55 
56 static struct blkcg_policy *blkcg_policy[BLKCG_MAX_POLS];
57 
58 static LIST_HEAD(all_blkcgs);		/* protected by blkcg_pol_mutex */
59 
60 bool blkcg_debug_stats = false;
61 
62 static DEFINE_RAW_SPINLOCK(blkg_stat_lock);
63 
64 #define BLKG_DESTROY_BATCH_SIZE  64
65 
66 /*
67  * Lockless lists for tracking IO stats update
68  *
69  * New IO stats are stored in the percpu iostat_cpu within blkcg_gq (blkg).
70  * There are multiple blkg's (one for each block device) attached to each
71  * blkcg. The rstat code keeps track of which cpu has IO stats updated,
72  * but it doesn't know which blkg has the updated stats. If there are many
73  * block devices in a system, the cost of iterating all the blkg's to flush
74  * out the IO stats can be high. To reduce such overhead, a set of percpu
75  * lockless lists (lhead) per blkcg are used to track the set of recently
76  * updated iostat_cpu's since the last flush. An iostat_cpu will be put
77  * onto the lockless list on the update side [blk_cgroup_bio_start()] if
78  * not there yet and then removed when being flushed [blkcg_rstat_flush()].
79  * References to blkg are gotten and then put back in the process to
80  * protect against blkg removal.
81  *
82  * Return: 0 if successful or -ENOMEM if allocation fails.
83  */
84 static int init_blkcg_llists(struct blkcg *blkcg)
85 {
86 	int cpu;
87 
88 	blkcg->lhead = alloc_percpu_gfp(struct llist_head, GFP_KERNEL);
89 	if (!blkcg->lhead)
90 		return -ENOMEM;
91 
92 	for_each_possible_cpu(cpu)
93 		init_llist_head(per_cpu_ptr(blkcg->lhead, cpu));
94 	return 0;
95 }
96 
97 /**
98  * blkcg_css - find the current css
99  *
100  * Find the css associated with either the kthread or the current task.
101  * This may return a dying css, so it is up to the caller to use tryget logic
102  * to confirm it is alive and well.
103  */
104 static struct cgroup_subsys_state *blkcg_css(void)
105 {
106 	struct cgroup_subsys_state *css;
107 
108 	css = kthread_blkcg();
109 	if (css)
110 		return css;
111 	return task_css(current, io_cgrp_id);
112 }
113 
114 static void blkg_free_workfn(struct work_struct *work)
115 {
116 	struct blkcg_gq *blkg = container_of(work, struct blkcg_gq,
117 					     free_work);
118 	struct request_queue *q = blkg->q;
119 	int i;
120 
121 	/*
122 	 * pd_free_fn() can also be called from blkcg_deactivate_policy(),
123 	 * in order to make sure pd_free_fn() is called in order, the deletion
124 	 * of the list blkg->q_node is delayed to here from blkg_destroy(), and
125 	 * blkcg_mutex is used to synchronize blkg_free_workfn() and
126 	 * blkcg_deactivate_policy().
127 	 */
128 	mutex_lock(&q->blkcg_mutex);
129 	for (i = 0; i < BLKCG_MAX_POLS; i++)
130 		if (blkg->pd[i])
131 			blkcg_policy[i]->pd_free_fn(blkg->pd[i]);
132 	if (blkg->parent)
133 		blkg_put(blkg->parent);
134 	spin_lock_irq(&q->queue_lock);
135 	list_del_init(&blkg->q_node);
136 	spin_unlock_irq(&q->queue_lock);
137 	mutex_unlock(&q->blkcg_mutex);
138 
139 	blk_put_queue(q);
140 	free_percpu(blkg->iostat_cpu);
141 	percpu_ref_exit(&blkg->refcnt);
142 	kfree(blkg);
143 }
144 
145 /**
146  * blkg_free - free a blkg
147  * @blkg: blkg to free
148  *
149  * Free @blkg which may be partially allocated.
150  */
151 static void blkg_free(struct blkcg_gq *blkg)
152 {
153 	if (!blkg)
154 		return;
155 
156 	/*
157 	 * Both ->pd_free_fn() and request queue's release handler may
158 	 * sleep, so free us by scheduling one work func
159 	 */
160 	INIT_WORK(&blkg->free_work, blkg_free_workfn);
161 	schedule_work(&blkg->free_work);
162 }
163 
164 static void __blkg_release(struct rcu_head *rcu)
165 {
166 	struct blkcg_gq *blkg = container_of(rcu, struct blkcg_gq, rcu_head);
167 	struct blkcg *blkcg = blkg->blkcg;
168 	int cpu;
169 
170 #ifdef CONFIG_BLK_CGROUP_PUNT_BIO
171 	WARN_ON(!bio_list_empty(&blkg->async_bios));
172 #endif
173 	/*
174 	 * Flush all the non-empty percpu lockless lists before releasing
175 	 * us, given these stat belongs to us.
176 	 *
177 	 * blkg_stat_lock is for serializing blkg stat update
178 	 */
179 	for_each_possible_cpu(cpu)
180 		__blkcg_rstat_flush(blkcg, cpu);
181 
182 	/* release the blkcg and parent blkg refs this blkg has been holding */
183 	css_put(&blkg->blkcg->css);
184 	blkg_free(blkg);
185 }
186 
187 /*
188  * A group is RCU protected, but having an rcu lock does not mean that one
189  * can access all the fields of blkg and assume these are valid.  For
190  * example, don't try to follow throtl_data and request queue links.
191  *
192  * Having a reference to blkg under an rcu allows accesses to only values
193  * local to groups like group stats and group rate limits.
194  */
195 static void blkg_release(struct percpu_ref *ref)
196 {
197 	struct blkcg_gq *blkg = container_of(ref, struct blkcg_gq, refcnt);
198 
199 	call_rcu(&blkg->rcu_head, __blkg_release);
200 }
201 
202 #ifdef CONFIG_BLK_CGROUP_PUNT_BIO
203 static struct workqueue_struct *blkcg_punt_bio_wq;
204 
205 static void blkg_async_bio_workfn(struct work_struct *work)
206 {
207 	struct blkcg_gq *blkg = container_of(work, struct blkcg_gq,
208 					     async_bio_work);
209 	struct bio_list bios = BIO_EMPTY_LIST;
210 	struct bio *bio;
211 	struct blk_plug plug;
212 	bool need_plug = false;
213 
214 	/* as long as there are pending bios, @blkg can't go away */
215 	spin_lock(&blkg->async_bio_lock);
216 	bio_list_merge_init(&bios, &blkg->async_bios);
217 	spin_unlock(&blkg->async_bio_lock);
218 
219 	/* start plug only when bio_list contains at least 2 bios */
220 	if (bios.head && bios.head->bi_next) {
221 		need_plug = true;
222 		blk_start_plug(&plug);
223 	}
224 	while ((bio = bio_list_pop(&bios)))
225 		submit_bio(bio);
226 	if (need_plug)
227 		blk_finish_plug(&plug);
228 }
229 
230 /*
231  * When a shared kthread issues a bio for a cgroup, doing so synchronously can
232  * lead to priority inversions as the kthread can be trapped waiting for that
233  * cgroup.  Use this helper instead of submit_bio to punt the actual issuing to
234  * a dedicated per-blkcg work item to avoid such priority inversions.
235  */
236 void blkcg_punt_bio_submit(struct bio *bio)
237 {
238 	struct blkcg_gq *blkg = bio->bi_blkg;
239 
240 	if (blkg->parent) {
241 		spin_lock(&blkg->async_bio_lock);
242 		bio_list_add(&blkg->async_bios, bio);
243 		spin_unlock(&blkg->async_bio_lock);
244 		queue_work(blkcg_punt_bio_wq, &blkg->async_bio_work);
245 	} else {
246 		/* never bounce for the root cgroup */
247 		submit_bio(bio);
248 	}
249 }
250 EXPORT_SYMBOL_GPL(blkcg_punt_bio_submit);
251 
252 static int __init blkcg_punt_bio_init(void)
253 {
254 	blkcg_punt_bio_wq = alloc_workqueue("blkcg_punt_bio",
255 					    WQ_MEM_RECLAIM | WQ_FREEZABLE |
256 					    WQ_UNBOUND | WQ_SYSFS, 0);
257 	if (!blkcg_punt_bio_wq)
258 		return -ENOMEM;
259 	return 0;
260 }
261 subsys_initcall(blkcg_punt_bio_init);
262 #endif /* CONFIG_BLK_CGROUP_PUNT_BIO */
263 
264 /**
265  * bio_blkcg_css - return the blkcg CSS associated with a bio
266  * @bio: target bio
267  *
268  * This returns the CSS for the blkcg associated with a bio, or %NULL if not
269  * associated. Callers are expected to either handle %NULL or know association
270  * has been done prior to calling this.
271  */
272 struct cgroup_subsys_state *bio_blkcg_css(struct bio *bio)
273 {
274 	if (!bio || !bio->bi_blkg)
275 		return NULL;
276 	return &bio->bi_blkg->blkcg->css;
277 }
278 EXPORT_SYMBOL_GPL(bio_blkcg_css);
279 
280 /**
281  * blkcg_parent - get the parent of a blkcg
282  * @blkcg: blkcg of interest
283  *
284  * Return the parent blkcg of @blkcg.  Can be called anytime.
285  */
286 static inline struct blkcg *blkcg_parent(struct blkcg *blkcg)
287 {
288 	return css_to_blkcg(blkcg->css.parent);
289 }
290 
291 /**
292  * blkg_alloc - allocate a blkg
293  * @blkcg: block cgroup the new blkg is associated with
294  * @disk: gendisk the new blkg is associated with
295  * @gfp_mask: allocation mask to use
296  *
297  * Allocate a new blkg associating @blkcg and @disk.
298  */
299 static struct blkcg_gq *blkg_alloc(struct blkcg *blkcg, struct gendisk *disk,
300 				   gfp_t gfp_mask)
301 {
302 	struct blkcg_gq *blkg;
303 	int i, cpu;
304 
305 	/* alloc and init base part */
306 	blkg = kzalloc_node(sizeof(*blkg), gfp_mask, disk->queue->node);
307 	if (!blkg)
308 		return NULL;
309 	if (percpu_ref_init(&blkg->refcnt, blkg_release, 0, gfp_mask))
310 		goto out_free_blkg;
311 	blkg->iostat_cpu = alloc_percpu_gfp(struct blkg_iostat_set, gfp_mask);
312 	if (!blkg->iostat_cpu)
313 		goto out_exit_refcnt;
314 	if (!blk_get_queue(disk->queue))
315 		goto out_free_iostat;
316 
317 	blkg->q = disk->queue;
318 	INIT_LIST_HEAD(&blkg->q_node);
319 	blkg->blkcg = blkcg;
320 	blkg->iostat.blkg = blkg;
321 #ifdef CONFIG_BLK_CGROUP_PUNT_BIO
322 	spin_lock_init(&blkg->async_bio_lock);
323 	bio_list_init(&blkg->async_bios);
324 	INIT_WORK(&blkg->async_bio_work, blkg_async_bio_workfn);
325 #endif
326 
327 	u64_stats_init(&blkg->iostat.sync);
328 	for_each_possible_cpu(cpu) {
329 		u64_stats_init(&per_cpu_ptr(blkg->iostat_cpu, cpu)->sync);
330 		per_cpu_ptr(blkg->iostat_cpu, cpu)->blkg = blkg;
331 	}
332 
333 	for (i = 0; i < BLKCG_MAX_POLS; i++) {
334 		struct blkcg_policy *pol = blkcg_policy[i];
335 		struct blkg_policy_data *pd;
336 
337 		if (!blkcg_policy_enabled(disk->queue, pol))
338 			continue;
339 
340 		/* alloc per-policy data and attach it to blkg */
341 		pd = pol->pd_alloc_fn(disk, blkcg, gfp_mask);
342 		if (!pd)
343 			goto out_free_pds;
344 		blkg->pd[i] = pd;
345 		pd->blkg = blkg;
346 		pd->plid = i;
347 		pd->online = false;
348 	}
349 
350 	return blkg;
351 
352 out_free_pds:
353 	while (--i >= 0)
354 		if (blkg->pd[i])
355 			blkcg_policy[i]->pd_free_fn(blkg->pd[i]);
356 	blk_put_queue(disk->queue);
357 out_free_iostat:
358 	free_percpu(blkg->iostat_cpu);
359 out_exit_refcnt:
360 	percpu_ref_exit(&blkg->refcnt);
361 out_free_blkg:
362 	kfree(blkg);
363 	return NULL;
364 }
365 
366 /*
367  * If @new_blkg is %NULL, this function tries to allocate a new one as
368  * necessary using %GFP_NOWAIT.  @new_blkg is always consumed on return.
369  */
370 static struct blkcg_gq *blkg_create(struct blkcg *blkcg, struct gendisk *disk,
371 				    struct blkcg_gq *new_blkg)
372 {
373 	struct blkcg_gq *blkg;
374 	int i, ret;
375 
376 	lockdep_assert_held(&disk->queue->queue_lock);
377 
378 	/* request_queue is dying, do not create/recreate a blkg */
379 	if (blk_queue_dying(disk->queue)) {
380 		ret = -ENODEV;
381 		goto err_free_blkg;
382 	}
383 
384 	/* blkg holds a reference to blkcg */
385 	if (!css_tryget_online(&blkcg->css)) {
386 		ret = -ENODEV;
387 		goto err_free_blkg;
388 	}
389 
390 	/* allocate */
391 	if (!new_blkg) {
392 		new_blkg = blkg_alloc(blkcg, disk, GFP_NOWAIT);
393 		if (unlikely(!new_blkg)) {
394 			ret = -ENOMEM;
395 			goto err_put_css;
396 		}
397 	}
398 	blkg = new_blkg;
399 
400 	/* link parent */
401 	if (blkcg_parent(blkcg)) {
402 		blkg->parent = blkg_lookup(blkcg_parent(blkcg), disk->queue);
403 		if (WARN_ON_ONCE(!blkg->parent)) {
404 			ret = -ENODEV;
405 			goto err_put_css;
406 		}
407 		blkg_get(blkg->parent);
408 	}
409 
410 	/* invoke per-policy init */
411 	for (i = 0; i < BLKCG_MAX_POLS; i++) {
412 		struct blkcg_policy *pol = blkcg_policy[i];
413 
414 		if (blkg->pd[i] && pol->pd_init_fn)
415 			pol->pd_init_fn(blkg->pd[i]);
416 	}
417 
418 	/* insert */
419 	spin_lock(&blkcg->lock);
420 	ret = radix_tree_insert(&blkcg->blkg_tree, disk->queue->id, blkg);
421 	if (likely(!ret)) {
422 		hlist_add_head_rcu(&blkg->blkcg_node, &blkcg->blkg_list);
423 		list_add(&blkg->q_node, &disk->queue->blkg_list);
424 
425 		for (i = 0; i < BLKCG_MAX_POLS; i++) {
426 			struct blkcg_policy *pol = blkcg_policy[i];
427 
428 			if (blkg->pd[i]) {
429 				if (pol->pd_online_fn)
430 					pol->pd_online_fn(blkg->pd[i]);
431 				blkg->pd[i]->online = true;
432 			}
433 		}
434 	}
435 	blkg->online = true;
436 	spin_unlock(&blkcg->lock);
437 
438 	if (!ret)
439 		return blkg;
440 
441 	/* @blkg failed fully initialized, use the usual release path */
442 	blkg_put(blkg);
443 	return ERR_PTR(ret);
444 
445 err_put_css:
446 	css_put(&blkcg->css);
447 err_free_blkg:
448 	if (new_blkg)
449 		blkg_free(new_blkg);
450 	return ERR_PTR(ret);
451 }
452 
453 /**
454  * blkg_lookup_create - lookup blkg, try to create one if not there
455  * @blkcg: blkcg of interest
456  * @disk: gendisk of interest
457  *
458  * Lookup blkg for the @blkcg - @disk pair.  If it doesn't exist, try to
459  * create one.  blkg creation is performed recursively from blkcg_root such
460  * that all non-root blkg's have access to the parent blkg.  This function
461  * should be called under RCU read lock and takes @disk->queue->queue_lock.
462  *
463  * Returns the blkg or the closest blkg if blkg_create() fails as it walks
464  * down from root.
465  */
466 static struct blkcg_gq *blkg_lookup_create(struct blkcg *blkcg,
467 		struct gendisk *disk)
468 {
469 	struct request_queue *q = disk->queue;
470 	struct blkcg_gq *blkg;
471 	unsigned long flags;
472 
473 	WARN_ON_ONCE(!rcu_read_lock_held());
474 
475 	blkg = blkg_lookup(blkcg, q);
476 	if (blkg)
477 		return blkg;
478 
479 	spin_lock_irqsave(&q->queue_lock, flags);
480 	blkg = blkg_lookup(blkcg, q);
481 	if (blkg) {
482 		if (blkcg != &blkcg_root &&
483 		    blkg != rcu_dereference(blkcg->blkg_hint))
484 			rcu_assign_pointer(blkcg->blkg_hint, blkg);
485 		goto found;
486 	}
487 
488 	/*
489 	 * Create blkgs walking down from blkcg_root to @blkcg, so that all
490 	 * non-root blkgs have access to their parents.  Returns the closest
491 	 * blkg to the intended blkg should blkg_create() fail.
492 	 */
493 	while (true) {
494 		struct blkcg *pos = blkcg;
495 		struct blkcg *parent = blkcg_parent(blkcg);
496 		struct blkcg_gq *ret_blkg = q->root_blkg;
497 
498 		while (parent) {
499 			blkg = blkg_lookup(parent, q);
500 			if (blkg) {
501 				/* remember closest blkg */
502 				ret_blkg = blkg;
503 				break;
504 			}
505 			pos = parent;
506 			parent = blkcg_parent(parent);
507 		}
508 
509 		blkg = blkg_create(pos, disk, NULL);
510 		if (IS_ERR(blkg)) {
511 			blkg = ret_blkg;
512 			break;
513 		}
514 		if (pos == blkcg)
515 			break;
516 	}
517 
518 found:
519 	spin_unlock_irqrestore(&q->queue_lock, flags);
520 	return blkg;
521 }
522 
523 static void blkg_destroy(struct blkcg_gq *blkg)
524 {
525 	struct blkcg *blkcg = blkg->blkcg;
526 	int i;
527 
528 	lockdep_assert_held(&blkg->q->queue_lock);
529 	lockdep_assert_held(&blkcg->lock);
530 
531 	/*
532 	 * blkg stays on the queue list until blkg_free_workfn(), see details in
533 	 * blkg_free_workfn(), hence this function can be called from
534 	 * blkcg_destroy_blkgs() first and again from blkg_destroy_all() before
535 	 * blkg_free_workfn().
536 	 */
537 	if (hlist_unhashed(&blkg->blkcg_node))
538 		return;
539 
540 	for (i = 0; i < BLKCG_MAX_POLS; i++) {
541 		struct blkcg_policy *pol = blkcg_policy[i];
542 
543 		if (blkg->pd[i] && blkg->pd[i]->online) {
544 			blkg->pd[i]->online = false;
545 			if (pol->pd_offline_fn)
546 				pol->pd_offline_fn(blkg->pd[i]);
547 		}
548 	}
549 
550 	blkg->online = false;
551 
552 	radix_tree_delete(&blkcg->blkg_tree, blkg->q->id);
553 	hlist_del_init_rcu(&blkg->blkcg_node);
554 
555 	/*
556 	 * Both setting lookup hint to and clearing it from @blkg are done
557 	 * under queue_lock.  If it's not pointing to @blkg now, it never
558 	 * will.  Hint assignment itself can race safely.
559 	 */
560 	if (rcu_access_pointer(blkcg->blkg_hint) == blkg)
561 		rcu_assign_pointer(blkcg->blkg_hint, NULL);
562 
563 	/*
564 	 * Put the reference taken at the time of creation so that when all
565 	 * queues are gone, group can be destroyed.
566 	 */
567 	percpu_ref_kill(&blkg->refcnt);
568 }
569 
570 static void blkg_destroy_all(struct gendisk *disk)
571 {
572 	struct request_queue *q = disk->queue;
573 	struct blkcg_gq *blkg;
574 	int count = BLKG_DESTROY_BATCH_SIZE;
575 	int i;
576 
577 restart:
578 	spin_lock_irq(&q->queue_lock);
579 	list_for_each_entry(blkg, &q->blkg_list, q_node) {
580 		struct blkcg *blkcg = blkg->blkcg;
581 
582 		if (hlist_unhashed(&blkg->blkcg_node))
583 			continue;
584 
585 		spin_lock(&blkcg->lock);
586 		blkg_destroy(blkg);
587 		spin_unlock(&blkcg->lock);
588 
589 		/*
590 		 * in order to avoid holding the spin lock for too long, release
591 		 * it when a batch of blkgs are destroyed.
592 		 */
593 		if (!(--count)) {
594 			count = BLKG_DESTROY_BATCH_SIZE;
595 			spin_unlock_irq(&q->queue_lock);
596 			cond_resched();
597 			goto restart;
598 		}
599 	}
600 
601 	/*
602 	 * Mark policy deactivated since policy offline has been done, and
603 	 * the free is scheduled, so future blkcg_deactivate_policy() can
604 	 * be bypassed
605 	 */
606 	for (i = 0; i < BLKCG_MAX_POLS; i++) {
607 		struct blkcg_policy *pol = blkcg_policy[i];
608 
609 		if (pol)
610 			__clear_bit(pol->plid, q->blkcg_pols);
611 	}
612 
613 	q->root_blkg = NULL;
614 	spin_unlock_irq(&q->queue_lock);
615 
616 	wake_up_var(&q->root_blkg);
617 }
618 
619 static void blkg_iostat_set(struct blkg_iostat *dst, struct blkg_iostat *src)
620 {
621 	int i;
622 
623 	for (i = 0; i < BLKG_IOSTAT_NR; i++) {
624 		dst->bytes[i] = src->bytes[i];
625 		dst->ios[i] = src->ios[i];
626 	}
627 }
628 
629 static void __blkg_clear_stat(struct blkg_iostat_set *bis)
630 {
631 	struct blkg_iostat cur = {0};
632 	unsigned long flags;
633 
634 	flags = u64_stats_update_begin_irqsave(&bis->sync);
635 	blkg_iostat_set(&bis->cur, &cur);
636 	blkg_iostat_set(&bis->last, &cur);
637 	u64_stats_update_end_irqrestore(&bis->sync, flags);
638 }
639 
640 static void blkg_clear_stat(struct blkcg_gq *blkg)
641 {
642 	int cpu;
643 
644 	for_each_possible_cpu(cpu) {
645 		struct blkg_iostat_set *s = per_cpu_ptr(blkg->iostat_cpu, cpu);
646 
647 		__blkg_clear_stat(s);
648 	}
649 	__blkg_clear_stat(&blkg->iostat);
650 }
651 
652 static int blkcg_reset_stats(struct cgroup_subsys_state *css,
653 			     struct cftype *cftype, u64 val)
654 {
655 	struct blkcg *blkcg = css_to_blkcg(css);
656 	struct blkcg_gq *blkg;
657 	int i;
658 
659 	pr_info_once("blkio.%s is deprecated\n", cftype->name);
660 	mutex_lock(&blkcg_pol_mutex);
661 	spin_lock_irq(&blkcg->lock);
662 
663 	/*
664 	 * Note that stat reset is racy - it doesn't synchronize against
665 	 * stat updates.  This is a debug feature which shouldn't exist
666 	 * anyway.  If you get hit by a race, retry.
667 	 */
668 	hlist_for_each_entry(blkg, &blkcg->blkg_list, blkcg_node) {
669 		blkg_clear_stat(blkg);
670 		for (i = 0; i < BLKCG_MAX_POLS; i++) {
671 			struct blkcg_policy *pol = blkcg_policy[i];
672 
673 			if (blkg->pd[i] && pol->pd_reset_stats_fn)
674 				pol->pd_reset_stats_fn(blkg->pd[i]);
675 		}
676 	}
677 
678 	spin_unlock_irq(&blkcg->lock);
679 	mutex_unlock(&blkcg_pol_mutex);
680 	return 0;
681 }
682 
683 const char *blkg_dev_name(struct blkcg_gq *blkg)
684 {
685 	if (!blkg->q->disk)
686 		return NULL;
687 	return bdi_dev_name(blkg->q->disk->bdi);
688 }
689 
690 /**
691  * blkcg_print_blkgs - helper for printing per-blkg data
692  * @sf: seq_file to print to
693  * @blkcg: blkcg of interest
694  * @prfill: fill function to print out a blkg
695  * @pol: policy in question
696  * @data: data to be passed to @prfill
697  * @show_total: to print out sum of prfill return values or not
698  *
699  * This function invokes @prfill on each blkg of @blkcg if pd for the
700  * policy specified by @pol exists.  @prfill is invoked with @sf, the
701  * policy data and @data and the matching queue lock held.  If @show_total
702  * is %true, the sum of the return values from @prfill is printed with
703  * "Total" label at the end.
704  *
705  * This is to be used to construct print functions for
706  * cftype->read_seq_string method.
707  */
708 void blkcg_print_blkgs(struct seq_file *sf, struct blkcg *blkcg,
709 		       u64 (*prfill)(struct seq_file *,
710 				     struct blkg_policy_data *, int),
711 		       const struct blkcg_policy *pol, int data,
712 		       bool show_total)
713 {
714 	struct blkcg_gq *blkg;
715 	u64 total = 0;
716 
717 	rcu_read_lock();
718 	hlist_for_each_entry_rcu(blkg, &blkcg->blkg_list, blkcg_node) {
719 		spin_lock_irq(&blkg->q->queue_lock);
720 		if (blkcg_policy_enabled(blkg->q, pol))
721 			total += prfill(sf, blkg->pd[pol->plid], data);
722 		spin_unlock_irq(&blkg->q->queue_lock);
723 	}
724 	rcu_read_unlock();
725 
726 	if (show_total)
727 		seq_printf(sf, "Total %llu\n", (unsigned long long)total);
728 }
729 EXPORT_SYMBOL_GPL(blkcg_print_blkgs);
730 
731 /**
732  * __blkg_prfill_u64 - prfill helper for a single u64 value
733  * @sf: seq_file to print to
734  * @pd: policy private data of interest
735  * @v: value to print
736  *
737  * Print @v to @sf for the device associated with @pd.
738  */
739 u64 __blkg_prfill_u64(struct seq_file *sf, struct blkg_policy_data *pd, u64 v)
740 {
741 	const char *dname = blkg_dev_name(pd->blkg);
742 
743 	if (!dname)
744 		return 0;
745 
746 	seq_printf(sf, "%s %llu\n", dname, (unsigned long long)v);
747 	return v;
748 }
749 EXPORT_SYMBOL_GPL(__blkg_prfill_u64);
750 
751 /**
752  * blkg_conf_init - initialize a blkg_conf_ctx
753  * @ctx: blkg_conf_ctx to initialize
754  * @input: input string
755  *
756  * Initialize @ctx which can be used to parse blkg config input string @input.
757  * Once initialized, @ctx can be used with blkg_conf_open_bdev() and
758  * blkg_conf_prep().
759  */
760 void blkg_conf_init(struct blkg_conf_ctx *ctx, char *input)
761 {
762 	*ctx = (struct blkg_conf_ctx){ .input = input };
763 }
764 EXPORT_SYMBOL_GPL(blkg_conf_init);
765 
766 /**
767  * blkg_conf_open_bdev - parse and open bdev for per-blkg config update
768  * @ctx: blkg_conf_ctx initialized with blkg_conf_init()
769  *
770  * Parse the device node prefix part, MAJ:MIN, of per-blkg config update from
771  * @ctx->input and get and store the matching bdev in @ctx->bdev. @ctx->body is
772  * set to point past the device node prefix.
773  *
774  * Returns: -errno on error.
775  */
776 int blkg_conf_open_bdev(struct blkg_conf_ctx *ctx)
777 {
778 	char *input = ctx->input;
779 	unsigned int major, minor;
780 	struct block_device *bdev;
781 	int key_len;
782 
783 	if (WARN_ON_ONCE(ctx->bdev))
784 		return -EINVAL;
785 
786 	if (sscanf(input, "%u:%u%n", &major, &minor, &key_len) != 2)
787 		return -EINVAL;
788 
789 	input += key_len;
790 	if (!isspace(*input))
791 		return -EINVAL;
792 	input = skip_spaces(input);
793 
794 	bdev = blkdev_get_no_open(MKDEV(major, minor), false);
795 	if (!bdev)
796 		return -ENODEV;
797 	if (bdev_is_partition(bdev)) {
798 		blkdev_put_no_open(bdev);
799 		return -ENODEV;
800 	}
801 
802 	mutex_lock(&bdev->bd_queue->rq_qos_mutex);
803 	if (!disk_live(bdev->bd_disk)) {
804 		blkdev_put_no_open(bdev);
805 		mutex_unlock(&bdev->bd_queue->rq_qos_mutex);
806 		return -ENODEV;
807 	}
808 
809 	ctx->body = input;
810 	ctx->bdev = bdev;
811 	return 0;
812 }
813 EXPORT_SYMBOL_GPL(blkg_conf_open_bdev);
814 
815 /**
816  * blkg_conf_prep - parse and prepare for per-blkg config update
817  * @blkcg: target block cgroup
818  * @pol: target policy
819  * @ctx: blkg_conf_ctx initialized with blkg_conf_init()
820  *
821  * Parse per-blkg config update from @ctx->input and initialize @ctx
822  * accordingly. On success, @ctx->body points to the part of @ctx->input
823  * following MAJ:MIN, @ctx->bdev points to the target block device and
824  * @ctx->blkg to the blkg being configured.
825  *
826  * blkg_conf_open_bdev() must be called on @ctx beforehand. On success, this
827  * function returns with queue lock held and must be followed by
828  * blkg_conf_close_bdev().
829  */
830 int blkg_conf_prep(struct blkcg *blkcg, const struct blkcg_policy *pol,
831 		   struct blkg_conf_ctx *ctx)
832 {
833 	struct gendisk *disk;
834 	struct request_queue *q;
835 	struct blkcg_gq *blkg;
836 	int ret;
837 
838 	if (WARN_ON_ONCE(!ctx->bdev))
839 		return -EINVAL;
840 
841 	disk = ctx->bdev->bd_disk;
842 	q = disk->queue;
843 
844 	/* Prevent concurrent with blkcg_deactivate_policy() */
845 	mutex_lock(&q->blkcg_mutex);
846 	spin_lock_irq(&q->queue_lock);
847 
848 	if (!blkcg_policy_enabled(q, pol)) {
849 		ret = -EOPNOTSUPP;
850 		goto fail_unlock;
851 	}
852 
853 	blkg = blkg_lookup(blkcg, q);
854 	if (blkg)
855 		goto success;
856 
857 	/*
858 	 * Create blkgs walking down from blkcg_root to @blkcg, so that all
859 	 * non-root blkgs have access to their parents.
860 	 */
861 	while (true) {
862 		struct blkcg *pos = blkcg;
863 		struct blkcg *parent;
864 		struct blkcg_gq *new_blkg;
865 
866 		parent = blkcg_parent(blkcg);
867 		while (parent && !blkg_lookup(parent, q)) {
868 			pos = parent;
869 			parent = blkcg_parent(parent);
870 		}
871 
872 		/* Drop locks to do new blkg allocation with GFP_KERNEL. */
873 		spin_unlock_irq(&q->queue_lock);
874 
875 		new_blkg = blkg_alloc(pos, disk, GFP_NOIO);
876 		if (unlikely(!new_blkg)) {
877 			ret = -ENOMEM;
878 			goto fail_exit;
879 		}
880 
881 		if (radix_tree_preload(GFP_KERNEL)) {
882 			blkg_free(new_blkg);
883 			ret = -ENOMEM;
884 			goto fail_exit;
885 		}
886 
887 		spin_lock_irq(&q->queue_lock);
888 
889 		if (!blkcg_policy_enabled(q, pol)) {
890 			blkg_free(new_blkg);
891 			ret = -EOPNOTSUPP;
892 			goto fail_preloaded;
893 		}
894 
895 		blkg = blkg_lookup(pos, q);
896 		if (blkg) {
897 			blkg_free(new_blkg);
898 		} else {
899 			blkg = blkg_create(pos, disk, new_blkg);
900 			if (IS_ERR(blkg)) {
901 				ret = PTR_ERR(blkg);
902 				goto fail_preloaded;
903 			}
904 		}
905 
906 		radix_tree_preload_end();
907 
908 		if (pos == blkcg)
909 			goto success;
910 	}
911 success:
912 	mutex_unlock(&q->blkcg_mutex);
913 	ctx->blkg = blkg;
914 	return 0;
915 
916 fail_preloaded:
917 	radix_tree_preload_end();
918 fail_unlock:
919 	spin_unlock_irq(&q->queue_lock);
920 fail_exit:
921 	mutex_unlock(&q->blkcg_mutex);
922 	/*
923 	 * If queue was bypassing, we should retry.  Do so after a
924 	 * short msleep().  It isn't strictly necessary but queue
925 	 * can be bypassing for some time and it's always nice to
926 	 * avoid busy looping.
927 	 */
928 	if (ret == -EBUSY) {
929 		msleep(10);
930 		ret = restart_syscall();
931 	}
932 	return ret;
933 }
934 EXPORT_SYMBOL_GPL(blkg_conf_prep);
935 
936 /**
937  * blkg_conf_unprep - counterpart of blkg_conf_prep()
938  * @ctx: blkg_conf_ctx initialized with blkg_conf_init()
939  */
940 void blkg_conf_unprep(struct blkg_conf_ctx *ctx)
941 {
942 	WARN_ON_ONCE(!ctx->blkg);
943 	spin_unlock_irq(&ctx->bdev->bd_disk->queue->queue_lock);
944 	ctx->blkg = NULL;
945 }
946 EXPORT_SYMBOL_GPL(blkg_conf_unprep);
947 
948 /**
949  * blkg_conf_close_bdev - counterpart of blkg_conf_open_bdev()
950  * @ctx: blkg_conf_ctx initialized with blkg_conf_init()
951  */
952 void blkg_conf_close_bdev(struct blkg_conf_ctx *ctx)
953 {
954 	mutex_unlock(&ctx->bdev->bd_queue->rq_qos_mutex);
955 	blkdev_put_no_open(ctx->bdev);
956 	ctx->body = NULL;
957 	ctx->bdev = NULL;
958 }
959 EXPORT_SYMBOL_GPL(blkg_conf_close_bdev);
960 
961 static void blkg_iostat_add(struct blkg_iostat *dst, struct blkg_iostat *src)
962 {
963 	int i;
964 
965 	for (i = 0; i < BLKG_IOSTAT_NR; i++) {
966 		dst->bytes[i] += src->bytes[i];
967 		dst->ios[i] += src->ios[i];
968 	}
969 }
970 
971 static void blkg_iostat_sub(struct blkg_iostat *dst, struct blkg_iostat *src)
972 {
973 	int i;
974 
975 	for (i = 0; i < BLKG_IOSTAT_NR; i++) {
976 		dst->bytes[i] -= src->bytes[i];
977 		dst->ios[i] -= src->ios[i];
978 	}
979 }
980 
981 static void blkcg_iostat_update(struct blkcg_gq *blkg, struct blkg_iostat *cur,
982 				struct blkg_iostat *last)
983 {
984 	struct blkg_iostat delta;
985 	unsigned long flags;
986 
987 	/* propagate percpu delta to global */
988 	flags = u64_stats_update_begin_irqsave(&blkg->iostat.sync);
989 	blkg_iostat_set(&delta, cur);
990 	blkg_iostat_sub(&delta, last);
991 	blkg_iostat_add(&blkg->iostat.cur, &delta);
992 	blkg_iostat_add(last, &delta);
993 	u64_stats_update_end_irqrestore(&blkg->iostat.sync, flags);
994 }
995 
996 static void __blkcg_rstat_flush(struct blkcg *blkcg, int cpu)
997 {
998 	struct llist_head *lhead = per_cpu_ptr(blkcg->lhead, cpu);
999 	struct llist_node *lnode;
1000 	struct blkg_iostat_set *bisc, *next_bisc;
1001 	unsigned long flags;
1002 
1003 	rcu_read_lock();
1004 
1005 	lnode = llist_del_all(lhead);
1006 	if (!lnode)
1007 		goto out;
1008 
1009 	/*
1010 	 * For covering concurrent parent blkg update from blkg_release().
1011 	 *
1012 	 * When flushing from cgroup, the subsystem rstat lock is always held,
1013 	 * so this lock won't cause contention most of time.
1014 	 */
1015 	raw_spin_lock_irqsave(&blkg_stat_lock, flags);
1016 
1017 	/*
1018 	 * Iterate only the iostat_cpu's queued in the lockless list.
1019 	 */
1020 	llist_for_each_entry_safe(bisc, next_bisc, lnode, lnode) {
1021 		struct blkcg_gq *blkg = bisc->blkg;
1022 		struct blkcg_gq *parent = blkg->parent;
1023 		struct blkg_iostat cur;
1024 		unsigned int seq;
1025 
1026 		/*
1027 		 * Order assignment of `next_bisc` from `bisc->lnode.next` in
1028 		 * llist_for_each_entry_safe and clearing `bisc->lqueued` for
1029 		 * avoiding to assign `next_bisc` with new next pointer added
1030 		 * in blk_cgroup_bio_start() in case of re-ordering.
1031 		 *
1032 		 * The pair barrier is implied in llist_add() in blk_cgroup_bio_start().
1033 		 */
1034 		smp_mb();
1035 
1036 		WRITE_ONCE(bisc->lqueued, false);
1037 		if (bisc == &blkg->iostat)
1038 			goto propagate_up; /* propagate up to parent only */
1039 
1040 		/* fetch the current per-cpu values */
1041 		do {
1042 			seq = u64_stats_fetch_begin(&bisc->sync);
1043 			blkg_iostat_set(&cur, &bisc->cur);
1044 		} while (u64_stats_fetch_retry(&bisc->sync, seq));
1045 
1046 		blkcg_iostat_update(blkg, &cur, &bisc->last);
1047 
1048 propagate_up:
1049 		/* propagate global delta to parent (unless that's root) */
1050 		if (parent && parent->parent) {
1051 			blkcg_iostat_update(parent, &blkg->iostat.cur,
1052 					    &blkg->iostat.last);
1053 			/*
1054 			 * Queue parent->iostat to its blkcg's lockless
1055 			 * list to propagate up to the grandparent if the
1056 			 * iostat hasn't been queued yet.
1057 			 */
1058 			if (!parent->iostat.lqueued) {
1059 				struct llist_head *plhead;
1060 
1061 				plhead = per_cpu_ptr(parent->blkcg->lhead, cpu);
1062 				llist_add(&parent->iostat.lnode, plhead);
1063 				parent->iostat.lqueued = true;
1064 			}
1065 		}
1066 	}
1067 	raw_spin_unlock_irqrestore(&blkg_stat_lock, flags);
1068 out:
1069 	rcu_read_unlock();
1070 }
1071 
1072 static void blkcg_rstat_flush(struct cgroup_subsys_state *css, int cpu)
1073 {
1074 	/* Root-level stats are sourced from system-wide IO stats */
1075 	if (cgroup_parent(css->cgroup))
1076 		__blkcg_rstat_flush(css_to_blkcg(css), cpu);
1077 }
1078 
1079 /*
1080  * We source root cgroup stats from the system-wide stats to avoid
1081  * tracking the same information twice and incurring overhead when no
1082  * cgroups are defined. For that reason, css_rstat_flush in
1083  * blkcg_print_stat does not actually fill out the iostat in the root
1084  * cgroup's blkcg_gq.
1085  *
1086  * However, we would like to re-use the printing code between the root and
1087  * non-root cgroups to the extent possible. For that reason, we simulate
1088  * flushing the root cgroup's stats by explicitly filling in the iostat
1089  * with disk level statistics.
1090  */
1091 static void blkcg_fill_root_iostats(void)
1092 {
1093 	struct class_dev_iter iter;
1094 	struct device *dev;
1095 
1096 	class_dev_iter_init(&iter, &block_class, NULL, &disk_type);
1097 	while ((dev = class_dev_iter_next(&iter))) {
1098 		struct block_device *bdev = dev_to_bdev(dev);
1099 		struct blkcg_gq *blkg = bdev->bd_disk->queue->root_blkg;
1100 		struct blkg_iostat tmp;
1101 		int cpu;
1102 		unsigned long flags;
1103 
1104 		memset(&tmp, 0, sizeof(tmp));
1105 		for_each_possible_cpu(cpu) {
1106 			struct disk_stats *cpu_dkstats;
1107 
1108 			cpu_dkstats = per_cpu_ptr(bdev->bd_stats, cpu);
1109 			tmp.ios[BLKG_IOSTAT_READ] +=
1110 				cpu_dkstats->ios[STAT_READ];
1111 			tmp.ios[BLKG_IOSTAT_WRITE] +=
1112 				cpu_dkstats->ios[STAT_WRITE];
1113 			tmp.ios[BLKG_IOSTAT_DISCARD] +=
1114 				cpu_dkstats->ios[STAT_DISCARD];
1115 			// convert sectors to bytes
1116 			tmp.bytes[BLKG_IOSTAT_READ] +=
1117 				cpu_dkstats->sectors[STAT_READ] << 9;
1118 			tmp.bytes[BLKG_IOSTAT_WRITE] +=
1119 				cpu_dkstats->sectors[STAT_WRITE] << 9;
1120 			tmp.bytes[BLKG_IOSTAT_DISCARD] +=
1121 				cpu_dkstats->sectors[STAT_DISCARD] << 9;
1122 		}
1123 
1124 		flags = u64_stats_update_begin_irqsave(&blkg->iostat.sync);
1125 		blkg_iostat_set(&blkg->iostat.cur, &tmp);
1126 		u64_stats_update_end_irqrestore(&blkg->iostat.sync, flags);
1127 	}
1128 	class_dev_iter_exit(&iter);
1129 }
1130 
1131 static void blkcg_print_one_stat(struct blkcg_gq *blkg, struct seq_file *s)
1132 {
1133 	struct blkg_iostat_set *bis = &blkg->iostat;
1134 	u64 rbytes, wbytes, rios, wios, dbytes, dios;
1135 	const char *dname;
1136 	unsigned seq;
1137 	int i;
1138 
1139 	if (!blkg->online)
1140 		return;
1141 
1142 	dname = blkg_dev_name(blkg);
1143 	if (!dname)
1144 		return;
1145 
1146 	seq_printf(s, "%s ", dname);
1147 
1148 	do {
1149 		seq = u64_stats_fetch_begin(&bis->sync);
1150 
1151 		rbytes = bis->cur.bytes[BLKG_IOSTAT_READ];
1152 		wbytes = bis->cur.bytes[BLKG_IOSTAT_WRITE];
1153 		dbytes = bis->cur.bytes[BLKG_IOSTAT_DISCARD];
1154 		rios = bis->cur.ios[BLKG_IOSTAT_READ];
1155 		wios = bis->cur.ios[BLKG_IOSTAT_WRITE];
1156 		dios = bis->cur.ios[BLKG_IOSTAT_DISCARD];
1157 	} while (u64_stats_fetch_retry(&bis->sync, seq));
1158 
1159 	if (rbytes || wbytes || rios || wios) {
1160 		seq_printf(s, "rbytes=%llu wbytes=%llu rios=%llu wios=%llu dbytes=%llu dios=%llu",
1161 			rbytes, wbytes, rios, wios,
1162 			dbytes, dios);
1163 	}
1164 
1165 	if (blkcg_debug_stats && atomic_read(&blkg->use_delay)) {
1166 		seq_printf(s, " use_delay=%d delay_nsec=%llu",
1167 			atomic_read(&blkg->use_delay),
1168 			atomic64_read(&blkg->delay_nsec));
1169 	}
1170 
1171 	for (i = 0; i < BLKCG_MAX_POLS; i++) {
1172 		struct blkcg_policy *pol = blkcg_policy[i];
1173 
1174 		if (!blkg->pd[i] || !pol->pd_stat_fn)
1175 			continue;
1176 
1177 		pol->pd_stat_fn(blkg->pd[i], s);
1178 	}
1179 
1180 	seq_puts(s, "\n");
1181 }
1182 
1183 static int blkcg_print_stat(struct seq_file *sf, void *v)
1184 {
1185 	struct blkcg *blkcg = css_to_blkcg(seq_css(sf));
1186 	struct blkcg_gq *blkg;
1187 
1188 	if (!seq_css(sf)->parent)
1189 		blkcg_fill_root_iostats();
1190 	else
1191 		css_rstat_flush(&blkcg->css);
1192 
1193 	rcu_read_lock();
1194 	hlist_for_each_entry_rcu(blkg, &blkcg->blkg_list, blkcg_node) {
1195 		spin_lock_irq(&blkg->q->queue_lock);
1196 		blkcg_print_one_stat(blkg, sf);
1197 		spin_unlock_irq(&blkg->q->queue_lock);
1198 	}
1199 	rcu_read_unlock();
1200 	return 0;
1201 }
1202 
1203 static struct cftype blkcg_files[] = {
1204 	{
1205 		.name = "stat",
1206 		.seq_show = blkcg_print_stat,
1207 	},
1208 	{ }	/* terminate */
1209 };
1210 
1211 static struct cftype blkcg_legacy_files[] = {
1212 	{
1213 		.name = "reset_stats",
1214 		.write_u64 = blkcg_reset_stats,
1215 	},
1216 	{ }	/* terminate */
1217 };
1218 
1219 #ifdef CONFIG_CGROUP_WRITEBACK
1220 struct list_head *blkcg_get_cgwb_list(struct cgroup_subsys_state *css)
1221 {
1222 	return &css_to_blkcg(css)->cgwb_list;
1223 }
1224 #endif
1225 
1226 /*
1227  * blkcg destruction is a three-stage process.
1228  *
1229  * 1. Destruction starts.  The blkcg_css_offline() callback is invoked
1230  *    which offlines writeback.  Here we tie the next stage of blkg destruction
1231  *    to the completion of writeback associated with the blkcg.  This lets us
1232  *    avoid punting potentially large amounts of outstanding writeback to root
1233  *    while maintaining any ongoing policies.  The next stage is triggered when
1234  *    the nr_cgwbs count goes to zero.
1235  *
1236  * 2. When the nr_cgwbs count goes to zero, blkcg_destroy_blkgs() is called
1237  *    and handles the destruction of blkgs.  Here the css reference held by
1238  *    the blkg is put back eventually allowing blkcg_css_free() to be called.
1239  *    This work may occur in cgwb_release_workfn() on the cgwb_release
1240  *    workqueue.  Any submitted ios that fail to get the blkg ref will be
1241  *    punted to the root_blkg.
1242  *
1243  * 3. Once the blkcg ref count goes to zero, blkcg_css_free() is called.
1244  *    This finally frees the blkcg.
1245  */
1246 
1247 /**
1248  * blkcg_destroy_blkgs - responsible for shooting down blkgs
1249  * @blkcg: blkcg of interest
1250  *
1251  * blkgs should be removed while holding both q and blkcg locks.  As blkcg lock
1252  * is nested inside q lock, this function performs reverse double lock dancing.
1253  * Destroying the blkgs releases the reference held on the blkcg's css allowing
1254  * blkcg_css_free to eventually be called.
1255  *
1256  * This is the blkcg counterpart of ioc_release_fn().
1257  */
1258 static void blkcg_destroy_blkgs(struct blkcg *blkcg)
1259 {
1260 	might_sleep();
1261 
1262 	spin_lock_irq(&blkcg->lock);
1263 
1264 	while (!hlist_empty(&blkcg->blkg_list)) {
1265 		struct blkcg_gq *blkg = hlist_entry(blkcg->blkg_list.first,
1266 						struct blkcg_gq, blkcg_node);
1267 		struct request_queue *q = blkg->q;
1268 
1269 		if (need_resched() || !spin_trylock(&q->queue_lock)) {
1270 			/*
1271 			 * Given that the system can accumulate a huge number
1272 			 * of blkgs in pathological cases, check to see if we
1273 			 * need to rescheduling to avoid softlockup.
1274 			 */
1275 			spin_unlock_irq(&blkcg->lock);
1276 			cond_resched();
1277 			spin_lock_irq(&blkcg->lock);
1278 			continue;
1279 		}
1280 
1281 		blkg_destroy(blkg);
1282 		spin_unlock(&q->queue_lock);
1283 	}
1284 
1285 	spin_unlock_irq(&blkcg->lock);
1286 }
1287 
1288 /**
1289  * blkcg_pin_online - pin online state
1290  * @blkcg_css: blkcg of interest
1291  *
1292  * While pinned, a blkcg is kept online.  This is primarily used to
1293  * impedance-match blkg and cgwb lifetimes so that blkg doesn't go offline
1294  * while an associated cgwb is still active.
1295  */
1296 void blkcg_pin_online(struct cgroup_subsys_state *blkcg_css)
1297 {
1298 	refcount_inc(&css_to_blkcg(blkcg_css)->online_pin);
1299 }
1300 
1301 /**
1302  * blkcg_unpin_online - unpin online state
1303  * @blkcg_css: blkcg of interest
1304  *
1305  * This is primarily used to impedance-match blkg and cgwb lifetimes so
1306  * that blkg doesn't go offline while an associated cgwb is still active.
1307  * When this count goes to zero, all active cgwbs have finished so the
1308  * blkcg can continue destruction by calling blkcg_destroy_blkgs().
1309  */
1310 void blkcg_unpin_online(struct cgroup_subsys_state *blkcg_css)
1311 {
1312 	struct blkcg *blkcg = css_to_blkcg(blkcg_css);
1313 
1314 	do {
1315 		struct blkcg *parent;
1316 
1317 		if (!refcount_dec_and_test(&blkcg->online_pin))
1318 			break;
1319 
1320 		parent = blkcg_parent(blkcg);
1321 		blkcg_destroy_blkgs(blkcg);
1322 		blkcg = parent;
1323 	} while (blkcg);
1324 }
1325 
1326 /**
1327  * blkcg_css_offline - cgroup css_offline callback
1328  * @css: css of interest
1329  *
1330  * This function is called when @css is about to go away.  Here the cgwbs are
1331  * offlined first and only once writeback associated with the blkcg has
1332  * finished do we start step 2 (see above).
1333  */
1334 static void blkcg_css_offline(struct cgroup_subsys_state *css)
1335 {
1336 	/* this prevents anyone from attaching or migrating to this blkcg */
1337 	wb_blkcg_offline(css);
1338 
1339 	/* put the base online pin allowing step 2 to be triggered */
1340 	blkcg_unpin_online(css);
1341 }
1342 
1343 static void blkcg_css_free(struct cgroup_subsys_state *css)
1344 {
1345 	struct blkcg *blkcg = css_to_blkcg(css);
1346 	int i;
1347 
1348 	mutex_lock(&blkcg_pol_mutex);
1349 
1350 	list_del(&blkcg->all_blkcgs_node);
1351 
1352 	for (i = 0; i < BLKCG_MAX_POLS; i++)
1353 		if (blkcg->cpd[i])
1354 			blkcg_policy[i]->cpd_free_fn(blkcg->cpd[i]);
1355 
1356 	mutex_unlock(&blkcg_pol_mutex);
1357 
1358 	free_percpu(blkcg->lhead);
1359 	kfree(blkcg);
1360 }
1361 
1362 static struct cgroup_subsys_state *
1363 blkcg_css_alloc(struct cgroup_subsys_state *parent_css)
1364 {
1365 	struct blkcg *blkcg;
1366 	int i;
1367 
1368 	mutex_lock(&blkcg_pol_mutex);
1369 
1370 	if (!parent_css) {
1371 		blkcg = &blkcg_root;
1372 	} else {
1373 		blkcg = kzalloc_obj(*blkcg);
1374 		if (!blkcg)
1375 			goto unlock;
1376 	}
1377 
1378 	if (init_blkcg_llists(blkcg))
1379 		goto free_blkcg;
1380 
1381 	for (i = 0; i < BLKCG_MAX_POLS ; i++) {
1382 		struct blkcg_policy *pol = blkcg_policy[i];
1383 		struct blkcg_policy_data *cpd;
1384 
1385 		/*
1386 		 * If the policy hasn't been attached yet, wait for it
1387 		 * to be attached before doing anything else. Otherwise,
1388 		 * check if the policy requires any specific per-cgroup
1389 		 * data: if it does, allocate and initialize it.
1390 		 */
1391 		if (!pol || !pol->cpd_alloc_fn)
1392 			continue;
1393 
1394 		cpd = pol->cpd_alloc_fn(GFP_KERNEL);
1395 		if (!cpd)
1396 			goto free_pd_blkcg;
1397 
1398 		blkcg->cpd[i] = cpd;
1399 		cpd->blkcg = blkcg;
1400 		cpd->plid = i;
1401 	}
1402 
1403 	spin_lock_init(&blkcg->lock);
1404 	refcount_set(&blkcg->online_pin, 1);
1405 	INIT_RADIX_TREE(&blkcg->blkg_tree, GFP_NOWAIT);
1406 	INIT_HLIST_HEAD(&blkcg->blkg_list);
1407 #ifdef CONFIG_CGROUP_WRITEBACK
1408 	INIT_LIST_HEAD(&blkcg->cgwb_list);
1409 #endif
1410 	list_add_tail(&blkcg->all_blkcgs_node, &all_blkcgs);
1411 
1412 	mutex_unlock(&blkcg_pol_mutex);
1413 	return &blkcg->css;
1414 
1415 free_pd_blkcg:
1416 	for (i--; i >= 0; i--)
1417 		if (blkcg->cpd[i])
1418 			blkcg_policy[i]->cpd_free_fn(blkcg->cpd[i]);
1419 	free_percpu(blkcg->lhead);
1420 free_blkcg:
1421 	if (blkcg != &blkcg_root)
1422 		kfree(blkcg);
1423 unlock:
1424 	mutex_unlock(&blkcg_pol_mutex);
1425 	return ERR_PTR(-ENOMEM);
1426 }
1427 
1428 static int blkcg_css_online(struct cgroup_subsys_state *css)
1429 {
1430 	struct blkcg *parent = blkcg_parent(css_to_blkcg(css));
1431 
1432 	/*
1433 	 * blkcg_pin_online() is used to delay blkcg offline so that blkgs
1434 	 * don't go offline while cgwbs are still active on them.  Pin the
1435 	 * parent so that offline always happens towards the root.
1436 	 */
1437 	if (parent)
1438 		blkcg_pin_online(&parent->css);
1439 	return 0;
1440 }
1441 
1442 void blkg_init_queue(struct request_queue *q)
1443 {
1444 	INIT_LIST_HEAD(&q->blkg_list);
1445 	mutex_init(&q->blkcg_mutex);
1446 }
1447 
1448 int blkcg_init_disk(struct gendisk *disk)
1449 {
1450 	struct request_queue *q = disk->queue;
1451 	struct blkcg_gq *new_blkg, *blkg;
1452 	bool preloaded;
1453 
1454 	/*
1455 	 * If the queue is shared across disk rebind (e.g., SCSI), the
1456 	 * previous disk's blkcg state is cleaned up asynchronously via
1457 	 * disk_release() -> blkcg_exit_disk(). Wait for that cleanup to
1458 	 * finish (indicated by root_blkg becoming NULL) before setting up
1459 	 * new blkcg state. Otherwise, we may overwrite q->root_blkg while
1460 	 * the old one is still alive, and radix_tree_insert() in
1461 	 * blkg_create() will fail with -EEXIST because the old entries
1462 	 * still occupy the same queue id slot in blkcg->blkg_tree.
1463 	 */
1464 	wait_var_event(&q->root_blkg, !READ_ONCE(q->root_blkg));
1465 
1466 	new_blkg = blkg_alloc(&blkcg_root, disk, GFP_KERNEL);
1467 	if (!new_blkg)
1468 		return -ENOMEM;
1469 
1470 	preloaded = !radix_tree_preload(GFP_KERNEL);
1471 
1472 	/* Make sure the root blkg exists. */
1473 	/* spin_lock_irq can serve as RCU read-side critical section. */
1474 	spin_lock_irq(&q->queue_lock);
1475 	blkg = blkg_create(&blkcg_root, disk, new_blkg);
1476 	if (IS_ERR(blkg))
1477 		goto err_unlock;
1478 	q->root_blkg = blkg;
1479 	spin_unlock_irq(&q->queue_lock);
1480 
1481 	if (preloaded)
1482 		radix_tree_preload_end();
1483 
1484 	return 0;
1485 
1486 err_unlock:
1487 	spin_unlock_irq(&q->queue_lock);
1488 	if (preloaded)
1489 		radix_tree_preload_end();
1490 	return PTR_ERR(blkg);
1491 }
1492 
1493 void blkcg_exit_disk(struct gendisk *disk)
1494 {
1495 	blkg_destroy_all(disk);
1496 	blk_throtl_exit(disk);
1497 }
1498 
1499 static void blkcg_exit(struct task_struct *tsk)
1500 {
1501 	if (tsk->throttle_disk)
1502 		put_disk(tsk->throttle_disk);
1503 	tsk->throttle_disk = NULL;
1504 }
1505 
1506 struct cgroup_subsys io_cgrp_subsys = {
1507 	.css_alloc = blkcg_css_alloc,
1508 	.css_online = blkcg_css_online,
1509 	.css_offline = blkcg_css_offline,
1510 	.css_free = blkcg_css_free,
1511 	.css_rstat_flush = blkcg_rstat_flush,
1512 	.dfl_cftypes = blkcg_files,
1513 	.legacy_cftypes = blkcg_legacy_files,
1514 	.legacy_name = "blkio",
1515 	.exit = blkcg_exit,
1516 #ifdef CONFIG_MEMCG
1517 	/*
1518 	 * This ensures that, if available, memcg is automatically enabled
1519 	 * together on the default hierarchy so that the owner cgroup can
1520 	 * be retrieved from writeback pages.
1521 	 */
1522 	.depends_on = 1 << memory_cgrp_id,
1523 #endif
1524 };
1525 EXPORT_SYMBOL_GPL(io_cgrp_subsys);
1526 
1527 /**
1528  * blkcg_activate_policy - activate a blkcg policy on a gendisk
1529  * @disk: gendisk of interest
1530  * @pol: blkcg policy to activate
1531  *
1532  * Activate @pol on @disk.  Requires %GFP_KERNEL context.  @disk goes through
1533  * bypass mode to populate its blkgs with policy_data for @pol.
1534  *
1535  * Activation happens with @disk bypassed, so nobody would be accessing blkgs
1536  * from IO path.  Update of each blkg is protected by both queue and blkcg
1537  * locks so that holding either lock and testing blkcg_policy_enabled() is
1538  * always enough for dereferencing policy data.
1539  *
1540  * The caller is responsible for synchronizing [de]activations and policy
1541  * [un]registerations.  Returns 0 on success, -errno on failure.
1542  */
1543 int blkcg_activate_policy(struct gendisk *disk, const struct blkcg_policy *pol)
1544 {
1545 	struct request_queue *q = disk->queue;
1546 	struct blkg_policy_data *pd_prealloc = NULL;
1547 	struct blkcg_gq *blkg, *pinned_blkg = NULL;
1548 	unsigned int memflags;
1549 	int ret;
1550 
1551 	if (blkcg_policy_enabled(q, pol))
1552 		return 0;
1553 
1554 	/*
1555 	 * Policy is allowed to be registered without pd_alloc_fn/pd_free_fn,
1556 	 * for example, ioprio. Such policy will work on blkcg level, not disk
1557 	 * level, and don't need to be activated.
1558 	 */
1559 	if (WARN_ON_ONCE(!pol->pd_alloc_fn || !pol->pd_free_fn))
1560 		return -EINVAL;
1561 
1562 	if (queue_is_mq(q))
1563 		memflags = blk_mq_freeze_queue(q);
1564 retry:
1565 	spin_lock_irq(&q->queue_lock);
1566 
1567 	/* blkg_list is pushed at the head, reverse walk to initialize parents first */
1568 	list_for_each_entry_reverse(blkg, &q->blkg_list, q_node) {
1569 		struct blkg_policy_data *pd;
1570 
1571 		if (blkg->pd[pol->plid])
1572 			continue;
1573 
1574 		/* If prealloc matches, use it; otherwise try GFP_NOWAIT */
1575 		if (blkg == pinned_blkg) {
1576 			pd = pd_prealloc;
1577 			pd_prealloc = NULL;
1578 		} else {
1579 			pd = pol->pd_alloc_fn(disk, blkg->blkcg,
1580 					      GFP_NOWAIT);
1581 		}
1582 
1583 		if (!pd) {
1584 			/*
1585 			 * GFP_NOWAIT failed.  Free the existing one and
1586 			 * prealloc for @blkg w/ GFP_KERNEL.
1587 			 */
1588 			if (pinned_blkg)
1589 				blkg_put(pinned_blkg);
1590 			blkg_get(blkg);
1591 			pinned_blkg = blkg;
1592 
1593 			spin_unlock_irq(&q->queue_lock);
1594 
1595 			if (pd_prealloc)
1596 				pol->pd_free_fn(pd_prealloc);
1597 			pd_prealloc = pol->pd_alloc_fn(disk, blkg->blkcg,
1598 						       GFP_KERNEL);
1599 			if (pd_prealloc)
1600 				goto retry;
1601 			else
1602 				goto enomem;
1603 		}
1604 
1605 		spin_lock(&blkg->blkcg->lock);
1606 
1607 		pd->blkg = blkg;
1608 		pd->plid = pol->plid;
1609 		blkg->pd[pol->plid] = pd;
1610 
1611 		if (pol->pd_init_fn)
1612 			pol->pd_init_fn(pd);
1613 
1614 		if (pol->pd_online_fn)
1615 			pol->pd_online_fn(pd);
1616 		pd->online = true;
1617 
1618 		spin_unlock(&blkg->blkcg->lock);
1619 	}
1620 
1621 	__set_bit(pol->plid, q->blkcg_pols);
1622 	ret = 0;
1623 
1624 	spin_unlock_irq(&q->queue_lock);
1625 out:
1626 	if (queue_is_mq(q))
1627 		blk_mq_unfreeze_queue(q, memflags);
1628 	if (pinned_blkg)
1629 		blkg_put(pinned_blkg);
1630 	if (pd_prealloc)
1631 		pol->pd_free_fn(pd_prealloc);
1632 	return ret;
1633 
1634 enomem:
1635 	/* alloc failed, take down everything */
1636 	spin_lock_irq(&q->queue_lock);
1637 	list_for_each_entry(blkg, &q->blkg_list, q_node) {
1638 		struct blkcg *blkcg = blkg->blkcg;
1639 		struct blkg_policy_data *pd;
1640 
1641 		spin_lock(&blkcg->lock);
1642 		pd = blkg->pd[pol->plid];
1643 		if (pd) {
1644 			if (pd->online && pol->pd_offline_fn)
1645 				pol->pd_offline_fn(pd);
1646 			pd->online = false;
1647 			pol->pd_free_fn(pd);
1648 			blkg->pd[pol->plid] = NULL;
1649 		}
1650 		spin_unlock(&blkcg->lock);
1651 	}
1652 	spin_unlock_irq(&q->queue_lock);
1653 	ret = -ENOMEM;
1654 	goto out;
1655 }
1656 EXPORT_SYMBOL_GPL(blkcg_activate_policy);
1657 
1658 /**
1659  * blkcg_deactivate_policy - deactivate a blkcg policy on a gendisk
1660  * @disk: gendisk of interest
1661  * @pol: blkcg policy to deactivate
1662  *
1663  * Deactivate @pol on @disk.  Follows the same synchronization rules as
1664  * blkcg_activate_policy().
1665  */
1666 void blkcg_deactivate_policy(struct gendisk *disk,
1667 			     const struct blkcg_policy *pol)
1668 {
1669 	struct request_queue *q = disk->queue;
1670 	struct blkcg_gq *blkg;
1671 	unsigned int memflags;
1672 
1673 	if (!blkcg_policy_enabled(q, pol))
1674 		return;
1675 
1676 	if (queue_is_mq(q))
1677 		memflags = blk_mq_freeze_queue(q);
1678 
1679 	mutex_lock(&q->blkcg_mutex);
1680 	spin_lock_irq(&q->queue_lock);
1681 
1682 	__clear_bit(pol->plid, q->blkcg_pols);
1683 
1684 	list_for_each_entry(blkg, &q->blkg_list, q_node) {
1685 		struct blkcg *blkcg = blkg->blkcg;
1686 
1687 		spin_lock(&blkcg->lock);
1688 		if (blkg->pd[pol->plid]) {
1689 			if (blkg->pd[pol->plid]->online && pol->pd_offline_fn)
1690 				pol->pd_offline_fn(blkg->pd[pol->plid]);
1691 			pol->pd_free_fn(blkg->pd[pol->plid]);
1692 			blkg->pd[pol->plid] = NULL;
1693 		}
1694 		spin_unlock(&blkcg->lock);
1695 	}
1696 
1697 	spin_unlock_irq(&q->queue_lock);
1698 	mutex_unlock(&q->blkcg_mutex);
1699 
1700 	if (queue_is_mq(q))
1701 		blk_mq_unfreeze_queue(q, memflags);
1702 }
1703 EXPORT_SYMBOL_GPL(blkcg_deactivate_policy);
1704 
1705 static void blkcg_free_all_cpd(struct blkcg_policy *pol)
1706 {
1707 	struct blkcg *blkcg;
1708 
1709 	list_for_each_entry(blkcg, &all_blkcgs, all_blkcgs_node) {
1710 		if (blkcg->cpd[pol->plid]) {
1711 			pol->cpd_free_fn(blkcg->cpd[pol->plid]);
1712 			blkcg->cpd[pol->plid] = NULL;
1713 		}
1714 	}
1715 }
1716 
1717 /**
1718  * blkcg_policy_register - register a blkcg policy
1719  * @pol: blkcg policy to register
1720  *
1721  * Register @pol with blkcg core.  Might sleep and @pol may be modified on
1722  * successful registration.  Returns 0 on success and -errno on failure.
1723  */
1724 int blkcg_policy_register(struct blkcg_policy *pol)
1725 {
1726 	struct blkcg *blkcg;
1727 	int i, ret;
1728 
1729 	/*
1730 	 * Make sure cpd/pd_alloc_fn and cpd/pd_free_fn in pairs, and policy
1731 	 * without pd_alloc_fn/pd_free_fn can't be activated.
1732 	 */
1733 	if ((!pol->cpd_alloc_fn ^ !pol->cpd_free_fn) ||
1734 	    (!pol->pd_alloc_fn ^ !pol->pd_free_fn))
1735 		return -EINVAL;
1736 
1737 	mutex_lock(&blkcg_pol_register_mutex);
1738 	mutex_lock(&blkcg_pol_mutex);
1739 
1740 	/* find an empty slot */
1741 	for (i = 0; i < BLKCG_MAX_POLS; i++)
1742 		if (!blkcg_policy[i])
1743 			break;
1744 	if (i >= BLKCG_MAX_POLS) {
1745 		pr_warn("blkcg_policy_register: BLKCG_MAX_POLS too small\n");
1746 		ret = -ENOSPC;
1747 		goto err_unlock;
1748 	}
1749 
1750 	/* register @pol */
1751 	pol->plid = i;
1752 	blkcg_policy[pol->plid] = pol;
1753 
1754 	/* allocate and install cpd's */
1755 	if (pol->cpd_alloc_fn) {
1756 		list_for_each_entry(blkcg, &all_blkcgs, all_blkcgs_node) {
1757 			struct blkcg_policy_data *cpd;
1758 
1759 			cpd = pol->cpd_alloc_fn(GFP_KERNEL);
1760 			if (!cpd) {
1761 				ret = -ENOMEM;
1762 				goto err_free_cpds;
1763 			}
1764 
1765 			blkcg->cpd[pol->plid] = cpd;
1766 			cpd->blkcg = blkcg;
1767 			cpd->plid = pol->plid;
1768 		}
1769 	}
1770 
1771 	mutex_unlock(&blkcg_pol_mutex);
1772 
1773 	/* everything is in place, add intf files for the new policy */
1774 	if (pol->dfl_cftypes == pol->legacy_cftypes) {
1775 		WARN_ON(cgroup_add_cftypes(&io_cgrp_subsys,
1776 					   pol->dfl_cftypes));
1777 	} else {
1778 		WARN_ON(cgroup_add_dfl_cftypes(&io_cgrp_subsys,
1779 					       pol->dfl_cftypes));
1780 		WARN_ON(cgroup_add_legacy_cftypes(&io_cgrp_subsys,
1781 						  pol->legacy_cftypes));
1782 	}
1783 	mutex_unlock(&blkcg_pol_register_mutex);
1784 	return 0;
1785 
1786 err_free_cpds:
1787 	if (pol->cpd_free_fn)
1788 		blkcg_free_all_cpd(pol);
1789 
1790 	blkcg_policy[pol->plid] = NULL;
1791 err_unlock:
1792 	mutex_unlock(&blkcg_pol_mutex);
1793 	mutex_unlock(&blkcg_pol_register_mutex);
1794 	return ret;
1795 }
1796 EXPORT_SYMBOL_GPL(blkcg_policy_register);
1797 
1798 /**
1799  * blkcg_policy_unregister - unregister a blkcg policy
1800  * @pol: blkcg policy to unregister
1801  *
1802  * Undo blkcg_policy_register(@pol).  Might sleep.
1803  */
1804 void blkcg_policy_unregister(struct blkcg_policy *pol)
1805 {
1806 	mutex_lock(&blkcg_pol_register_mutex);
1807 
1808 	if (WARN_ON(blkcg_policy[pol->plid] != pol))
1809 		goto out_unlock;
1810 
1811 	/* kill the intf files first */
1812 	if (pol->dfl_cftypes)
1813 		cgroup_rm_cftypes(pol->dfl_cftypes);
1814 	if (pol->legacy_cftypes)
1815 		cgroup_rm_cftypes(pol->legacy_cftypes);
1816 
1817 	/* remove cpds and unregister */
1818 	mutex_lock(&blkcg_pol_mutex);
1819 
1820 	if (pol->cpd_free_fn)
1821 		blkcg_free_all_cpd(pol);
1822 
1823 	blkcg_policy[pol->plid] = NULL;
1824 
1825 	mutex_unlock(&blkcg_pol_mutex);
1826 out_unlock:
1827 	mutex_unlock(&blkcg_pol_register_mutex);
1828 }
1829 EXPORT_SYMBOL_GPL(blkcg_policy_unregister);
1830 
1831 /*
1832  * Scale the accumulated delay based on how long it has been since we updated
1833  * the delay.  We only call this when we are adding delay, in case it's been a
1834  * while since we added delay, and when we are checking to see if we need to
1835  * delay a task, to account for any delays that may have occurred.
1836  */
1837 static void blkcg_scale_delay(struct blkcg_gq *blkg, u64 now)
1838 {
1839 	u64 old = atomic64_read(&blkg->delay_start);
1840 
1841 	/* negative use_delay means no scaling, see blkcg_set_delay() */
1842 	if (atomic_read(&blkg->use_delay) < 0)
1843 		return;
1844 
1845 	/*
1846 	 * We only want to scale down every second.  The idea here is that we
1847 	 * want to delay people for min(delay_nsec, NSEC_PER_SEC) in a certain
1848 	 * time window.  We only want to throttle tasks for recent delay that
1849 	 * has occurred, in 1 second time windows since that's the maximum
1850 	 * things can be throttled.  We save the current delay window in
1851 	 * blkg->last_delay so we know what amount is still left to be charged
1852 	 * to the blkg from this point onward.  blkg->last_use keeps track of
1853 	 * the use_delay counter.  The idea is if we're unthrottling the blkg we
1854 	 * are ok with whatever is happening now, and we can take away more of
1855 	 * the accumulated delay as we've already throttled enough that
1856 	 * everybody is happy with their IO latencies.
1857 	 */
1858 	if (time_before64(old + NSEC_PER_SEC, now) &&
1859 	    atomic64_try_cmpxchg(&blkg->delay_start, &old, now)) {
1860 		u64 cur = atomic64_read(&blkg->delay_nsec);
1861 		u64 sub = min_t(u64, blkg->last_delay, now - old);
1862 		int cur_use = atomic_read(&blkg->use_delay);
1863 
1864 		/*
1865 		 * We've been unthrottled, subtract a larger chunk of our
1866 		 * accumulated delay.
1867 		 */
1868 		if (cur_use < blkg->last_use)
1869 			sub = max_t(u64, sub, blkg->last_delay >> 1);
1870 
1871 		/*
1872 		 * This shouldn't happen, but handle it anyway.  Our delay_nsec
1873 		 * should only ever be growing except here where we subtract out
1874 		 * min(last_delay, 1 second), but lord knows bugs happen and I'd
1875 		 * rather not end up with negative numbers.
1876 		 */
1877 		if (unlikely(cur < sub)) {
1878 			atomic64_set(&blkg->delay_nsec, 0);
1879 			blkg->last_delay = 0;
1880 		} else {
1881 			atomic64_sub(sub, &blkg->delay_nsec);
1882 			blkg->last_delay = cur - sub;
1883 		}
1884 		blkg->last_use = cur_use;
1885 	}
1886 }
1887 
1888 /*
1889  * This is called when we want to actually walk up the hierarchy and check to
1890  * see if we need to throttle, and then actually throttle if there is some
1891  * accumulated delay.  This should only be called upon return to user space so
1892  * we're not holding some lock that would induce a priority inversion.
1893  */
1894 static void blkcg_maybe_throttle_blkg(struct blkcg_gq *blkg, bool use_memdelay)
1895 {
1896 	unsigned long pflags;
1897 	bool clamp;
1898 	u64 now = blk_time_get_ns();
1899 	u64 exp;
1900 	u64 delay_nsec = 0;
1901 	int tok;
1902 
1903 	while (blkg->parent) {
1904 		int use_delay = atomic_read(&blkg->use_delay);
1905 
1906 		if (use_delay) {
1907 			u64 this_delay;
1908 
1909 			blkcg_scale_delay(blkg, now);
1910 			this_delay = atomic64_read(&blkg->delay_nsec);
1911 			if (this_delay > delay_nsec) {
1912 				delay_nsec = this_delay;
1913 				clamp = use_delay > 0;
1914 			}
1915 		}
1916 		blkg = blkg->parent;
1917 	}
1918 
1919 	if (!delay_nsec)
1920 		return;
1921 
1922 	/*
1923 	 * Let's not sleep for all eternity if we've amassed a huge delay.
1924 	 * Swapping or metadata IO can accumulate 10's of seconds worth of
1925 	 * delay, and we want userspace to be able to do _something_ so cap the
1926 	 * delays at 0.25s. If there's 10's of seconds worth of delay then the
1927 	 * tasks will be delayed for 0.25 second for every syscall. If
1928 	 * blkcg_set_delay() was used as indicated by negative use_delay, the
1929 	 * caller is responsible for regulating the range.
1930 	 */
1931 	if (clamp)
1932 		delay_nsec = min_t(u64, delay_nsec, 250 * NSEC_PER_MSEC);
1933 
1934 	if (use_memdelay)
1935 		psi_memstall_enter(&pflags);
1936 
1937 	exp = ktime_add_ns(now, delay_nsec);
1938 	tok = io_schedule_prepare();
1939 	do {
1940 		__set_current_state(TASK_KILLABLE);
1941 		if (!schedule_hrtimeout(&exp, HRTIMER_MODE_ABS))
1942 			break;
1943 	} while (!fatal_signal_pending(current));
1944 	io_schedule_finish(tok);
1945 
1946 	if (use_memdelay)
1947 		psi_memstall_leave(&pflags);
1948 }
1949 
1950 /**
1951  * blkcg_maybe_throttle_current - throttle the current task if it has been marked
1952  *
1953  * This is only called if we've been marked with set_notify_resume().  Obviously
1954  * we can be set_notify_resume() for reasons other than blkcg throttling, so we
1955  * check to see if current->throttle_disk is set and if not this doesn't do
1956  * anything.  This should only ever be called by the resume code, it's not meant
1957  * to be called by people willy-nilly as it will actually do the work to
1958  * throttle the task if it is setup for throttling.
1959  */
1960 void blkcg_maybe_throttle_current(void)
1961 {
1962 	struct gendisk *disk = current->throttle_disk;
1963 	struct blkcg *blkcg;
1964 	struct blkcg_gq *blkg;
1965 	bool use_memdelay = current->use_memdelay;
1966 
1967 	if (!disk)
1968 		return;
1969 
1970 	current->throttle_disk = NULL;
1971 	current->use_memdelay = false;
1972 
1973 	rcu_read_lock();
1974 	blkcg = css_to_blkcg(blkcg_css());
1975 	if (!blkcg)
1976 		goto out;
1977 	blkg = blkg_lookup(blkcg, disk->queue);
1978 	if (!blkg)
1979 		goto out;
1980 	if (!blkg_tryget(blkg))
1981 		goto out;
1982 	rcu_read_unlock();
1983 
1984 	blkcg_maybe_throttle_blkg(blkg, use_memdelay);
1985 	blkg_put(blkg);
1986 	put_disk(disk);
1987 	return;
1988 out:
1989 	rcu_read_unlock();
1990 	put_disk(disk);
1991 }
1992 
1993 /**
1994  * blkcg_schedule_throttle - this task needs to check for throttling
1995  * @disk: disk to throttle
1996  * @use_memdelay: do we charge this to memory delay for PSI
1997  *
1998  * This is called by the IO controller when we know there's delay accumulated
1999  * for the blkg for this task.  We do not pass the blkg because there are places
2000  * we call this that may not have that information, the swapping code for
2001  * instance will only have a block_device at that point.  This set's the
2002  * notify_resume for the task to check and see if it requires throttling before
2003  * returning to user space.
2004  *
2005  * We will only schedule once per syscall.  You can call this over and over
2006  * again and it will only do the check once upon return to user space, and only
2007  * throttle once.  If the task needs to be throttled again it'll need to be
2008  * re-set at the next time we see the task.
2009  */
2010 void blkcg_schedule_throttle(struct gendisk *disk, bool use_memdelay)
2011 {
2012 	if (unlikely(current->flags & PF_KTHREAD))
2013 		return;
2014 
2015 	if (current->throttle_disk != disk) {
2016 		if (test_bit(GD_DEAD, &disk->state))
2017 			return;
2018 		get_device(disk_to_dev(disk));
2019 
2020 		if (current->throttle_disk)
2021 			put_disk(current->throttle_disk);
2022 		current->throttle_disk = disk;
2023 	}
2024 
2025 	if (use_memdelay)
2026 		current->use_memdelay = use_memdelay;
2027 	set_notify_resume(current);
2028 }
2029 
2030 /**
2031  * blkcg_add_delay - add delay to this blkg
2032  * @blkg: blkg of interest
2033  * @now: the current time in nanoseconds
2034  * @delta: how many nanoseconds of delay to add
2035  *
2036  * Charge @delta to the blkg's current delay accumulation.  This is used to
2037  * throttle tasks if an IO controller thinks we need more throttling.
2038  */
2039 void blkcg_add_delay(struct blkcg_gq *blkg, u64 now, u64 delta)
2040 {
2041 	if (WARN_ON_ONCE(atomic_read(&blkg->use_delay) < 0))
2042 		return;
2043 	blkcg_scale_delay(blkg, now);
2044 	atomic64_add(delta, &blkg->delay_nsec);
2045 }
2046 
2047 /**
2048  * blkg_tryget_closest - try and get a blkg ref on the closet blkg
2049  * @bio: target bio
2050  * @css: target css
2051  *
2052  * As the failure mode here is to walk up the blkg tree, this ensure that the
2053  * blkg->parent pointers are always valid.  This returns the blkg that it ended
2054  * up taking a reference on or %NULL if no reference was taken.
2055  */
2056 static inline struct blkcg_gq *blkg_tryget_closest(struct bio *bio,
2057 		struct cgroup_subsys_state *css)
2058 {
2059 	struct blkcg_gq *blkg, *ret_blkg = NULL;
2060 
2061 	rcu_read_lock();
2062 	blkg = blkg_lookup_create(css_to_blkcg(css), bio->bi_bdev->bd_disk);
2063 	while (blkg) {
2064 		if (blkg_tryget(blkg)) {
2065 			ret_blkg = blkg;
2066 			break;
2067 		}
2068 		blkg = blkg->parent;
2069 	}
2070 	rcu_read_unlock();
2071 
2072 	return ret_blkg;
2073 }
2074 
2075 /**
2076  * bio_associate_blkg_from_css - associate a bio with a specified css
2077  * @bio: target bio
2078  * @css: target css
2079  *
2080  * Associate @bio with the blkg found by combining the css's blkg and the
2081  * request_queue of the @bio.  An association failure is handled by walking up
2082  * the blkg tree.  Therefore, the blkg associated can be anything between @blkg
2083  * and q->root_blkg.  This situation only happens when a cgroup is dying and
2084  * then the remaining bios will spill to the closest alive blkg.
2085  *
2086  * A reference will be taken on the blkg and will be released when @bio is
2087  * freed.
2088  */
2089 void bio_associate_blkg_from_css(struct bio *bio,
2090 				 struct cgroup_subsys_state *css)
2091 {
2092 	if (bio->bi_blkg)
2093 		blkg_put(bio->bi_blkg);
2094 
2095 	if (css && css->parent) {
2096 		bio->bi_blkg = blkg_tryget_closest(bio, css);
2097 	} else {
2098 		blkg_get(bdev_get_queue(bio->bi_bdev)->root_blkg);
2099 		bio->bi_blkg = bdev_get_queue(bio->bi_bdev)->root_blkg;
2100 	}
2101 }
2102 EXPORT_SYMBOL_GPL(bio_associate_blkg_from_css);
2103 
2104 /**
2105  * bio_associate_blkg - associate a bio with a blkg
2106  * @bio: target bio
2107  *
2108  * Associate @bio with the blkg found from the bio's css and request_queue.
2109  * If one is not found, bio_lookup_blkg() creates the blkg.  If a blkg is
2110  * already associated, the css is reused and association redone as the
2111  * request_queue may have changed.
2112  */
2113 void bio_associate_blkg(struct bio *bio)
2114 {
2115 	struct cgroup_subsys_state *css;
2116 
2117 	if (blk_op_is_passthrough(bio->bi_opf))
2118 		return;
2119 
2120 	rcu_read_lock();
2121 
2122 	if (bio->bi_blkg)
2123 		css = bio_blkcg_css(bio);
2124 	else
2125 		css = blkcg_css();
2126 
2127 	bio_associate_blkg_from_css(bio, css);
2128 
2129 	rcu_read_unlock();
2130 }
2131 EXPORT_SYMBOL_GPL(bio_associate_blkg);
2132 
2133 /**
2134  * bio_clone_blkg_association - clone blkg association from src to dst bio
2135  * @dst: destination bio
2136  * @src: source bio
2137  */
2138 void bio_clone_blkg_association(struct bio *dst, struct bio *src)
2139 {
2140 	if (src->bi_blkg)
2141 		bio_associate_blkg_from_css(dst, bio_blkcg_css(src));
2142 }
2143 EXPORT_SYMBOL_GPL(bio_clone_blkg_association);
2144 
2145 static int blk_cgroup_io_type(struct bio *bio)
2146 {
2147 	if (op_is_discard(bio->bi_opf))
2148 		return BLKG_IOSTAT_DISCARD;
2149 	if (op_is_write(bio->bi_opf))
2150 		return BLKG_IOSTAT_WRITE;
2151 	return BLKG_IOSTAT_READ;
2152 }
2153 
2154 void blk_cgroup_bio_start(struct bio *bio)
2155 {
2156 	struct blkcg *blkcg = bio->bi_blkg->blkcg;
2157 	int rwd = blk_cgroup_io_type(bio), cpu;
2158 	struct blkg_iostat_set *bis;
2159 	unsigned long flags;
2160 
2161 	if (!cgroup_subsys_on_dfl(io_cgrp_subsys))
2162 		return;
2163 
2164 	/* Root-level stats are sourced from system-wide IO stats */
2165 	if (!cgroup_parent(blkcg->css.cgroup))
2166 		return;
2167 
2168 	cpu = get_cpu();
2169 	bis = per_cpu_ptr(bio->bi_blkg->iostat_cpu, cpu);
2170 	flags = u64_stats_update_begin_irqsave(&bis->sync);
2171 
2172 	/*
2173 	 * If the bio is flagged with BIO_CGROUP_ACCT it means this is a split
2174 	 * bio and we would have already accounted for the size of the bio.
2175 	 */
2176 	if (!bio_flagged(bio, BIO_CGROUP_ACCT)) {
2177 		bio_set_flag(bio, BIO_CGROUP_ACCT);
2178 		bis->cur.bytes[rwd] += bio->bi_iter.bi_size;
2179 	}
2180 	bis->cur.ios[rwd]++;
2181 
2182 	/*
2183 	 * If the iostat_cpu isn't in a lockless list, put it into the
2184 	 * list to indicate that a stat update is pending.
2185 	 */
2186 	if (!READ_ONCE(bis->lqueued)) {
2187 		struct llist_head *lhead = this_cpu_ptr(blkcg->lhead);
2188 
2189 		llist_add(&bis->lnode, lhead);
2190 		WRITE_ONCE(bis->lqueued, true);
2191 	}
2192 
2193 	u64_stats_update_end_irqrestore(&bis->sync, flags);
2194 	__css_rstat_updated(&blkcg->css, cpu);
2195 	put_cpu();
2196 }
2197 
2198 bool blk_cgroup_congested(void)
2199 {
2200 	struct blkcg *blkcg;
2201 	bool ret = false;
2202 
2203 	rcu_read_lock();
2204 	for (blkcg = css_to_blkcg(blkcg_css()); blkcg;
2205 	     blkcg = blkcg_parent(blkcg)) {
2206 		if (atomic_read(&blkcg->congestion_count)) {
2207 			ret = true;
2208 			break;
2209 		}
2210 	}
2211 	rcu_read_unlock();
2212 	return ret;
2213 }
2214 
2215 module_param(blkcg_debug_stats, bool, 0644);
2216 MODULE_PARM_DESC(blkcg_debug_stats, "True if you want debug stats, false if not");
2217