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