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