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