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