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