blkcg: make blkcg_[rw]stat per-cpu
[cascardo/linux.git] / block / blk-cgroup.c
1 /*
2  * Common Block IO controller cgroup interface
3  *
4  * Based on ideas and code from CFQ, CFS and BFQ:
5  * Copyright (C) 2003 Jens Axboe <axboe@kernel.dk>
6  *
7  * Copyright (C) 2008 Fabio Checconi <fabio@gandalf.sssup.it>
8  *                    Paolo Valente <paolo.valente@unimore.it>
9  *
10  * Copyright (C) 2009 Vivek Goyal <vgoyal@redhat.com>
11  *                    Nauman Rafique <nauman@google.com>
12  *
13  * For policy-specific per-blkcg data:
14  * Copyright (C) 2015 Paolo Valente <paolo.valente@unimore.it>
15  *                    Arianna Avanzini <avanzini.arianna@gmail.com>
16  */
17 #include <linux/ioprio.h>
18 #include <linux/kdev_t.h>
19 #include <linux/module.h>
20 #include <linux/err.h>
21 #include <linux/blkdev.h>
22 #include <linux/backing-dev.h>
23 #include <linux/slab.h>
24 #include <linux/genhd.h>
25 #include <linux/delay.h>
26 #include <linux/atomic.h>
27 #include <linux/blk-cgroup.h>
28 #include "blk.h"
29
30 #define MAX_KEY_LEN 100
31
32 /*
33  * blkcg_pol_mutex protects blkcg_policy[] and policy [de]activation.
34  * blkcg_pol_register_mutex nests outside of it and synchronizes entire
35  * policy [un]register operations including cgroup file additions /
36  * removals.  Putting cgroup file registration outside blkcg_pol_mutex
37  * allows grabbing it from cgroup callbacks.
38  */
39 static DEFINE_MUTEX(blkcg_pol_register_mutex);
40 static DEFINE_MUTEX(blkcg_pol_mutex);
41
42 struct blkcg blkcg_root;
43 EXPORT_SYMBOL_GPL(blkcg_root);
44
45 struct cgroup_subsys_state * const blkcg_root_css = &blkcg_root.css;
46
47 static struct blkcg_policy *blkcg_policy[BLKCG_MAX_POLS];
48
49 static LIST_HEAD(all_blkcgs);           /* protected by blkcg_pol_mutex */
50
51 static bool blkcg_policy_enabled(struct request_queue *q,
52                                  const struct blkcg_policy *pol)
53 {
54         return pol && test_bit(pol->plid, q->blkcg_pols);
55 }
56
57 /**
58  * blkg_free - free a blkg
59  * @blkg: blkg to free
60  *
61  * Free @blkg which may be partially allocated.
62  */
63 static void blkg_free(struct blkcg_gq *blkg)
64 {
65         int i;
66
67         if (!blkg)
68                 return;
69
70         for (i = 0; i < BLKCG_MAX_POLS; i++)
71                 if (blkg->pd[i])
72                         blkcg_policy[i]->pd_free_fn(blkg->pd[i]);
73
74         if (blkg->blkcg != &blkcg_root)
75                 blk_exit_rl(&blkg->rl);
76         kfree(blkg);
77 }
78
79 /**
80  * blkg_alloc - allocate a blkg
81  * @blkcg: block cgroup the new blkg is associated with
82  * @q: request_queue the new blkg is associated with
83  * @gfp_mask: allocation mask to use
84  *
85  * Allocate a new blkg assocating @blkcg and @q.
86  */
87 static struct blkcg_gq *blkg_alloc(struct blkcg *blkcg, struct request_queue *q,
88                                    gfp_t gfp_mask)
89 {
90         struct blkcg_gq *blkg;
91         int i;
92
93         /* alloc and init base part */
94         blkg = kzalloc_node(sizeof(*blkg), gfp_mask, q->node);
95         if (!blkg)
96                 return NULL;
97
98         blkg->q = q;
99         INIT_LIST_HEAD(&blkg->q_node);
100         blkg->blkcg = blkcg;
101         atomic_set(&blkg->refcnt, 1);
102
103         /* root blkg uses @q->root_rl, init rl only for !root blkgs */
104         if (blkcg != &blkcg_root) {
105                 if (blk_init_rl(&blkg->rl, q, gfp_mask))
106                         goto err_free;
107                 blkg->rl.blkg = blkg;
108         }
109
110         for (i = 0; i < BLKCG_MAX_POLS; i++) {
111                 struct blkcg_policy *pol = blkcg_policy[i];
112                 struct blkg_policy_data *pd;
113
114                 if (!blkcg_policy_enabled(q, pol))
115                         continue;
116
117                 /* alloc per-policy data and attach it to blkg */
118                 pd = pol->pd_alloc_fn(gfp_mask, q->node);
119                 if (!pd)
120                         goto err_free;
121
122                 blkg->pd[i] = pd;
123                 pd->blkg = blkg;
124                 pd->plid = i;
125         }
126
127         return blkg;
128
129 err_free:
130         blkg_free(blkg);
131         return NULL;
132 }
133
134 struct blkcg_gq *blkg_lookup_slowpath(struct blkcg *blkcg,
135                                       struct request_queue *q, bool update_hint)
136 {
137         struct blkcg_gq *blkg;
138
139         /*
140          * Hint didn't match.  Look up from the radix tree.  Note that the
141          * hint can only be updated under queue_lock as otherwise @blkg
142          * could have already been removed from blkg_tree.  The caller is
143          * responsible for grabbing queue_lock if @update_hint.
144          */
145         blkg = radix_tree_lookup(&blkcg->blkg_tree, q->id);
146         if (blkg && blkg->q == q) {
147                 if (update_hint) {
148                         lockdep_assert_held(q->queue_lock);
149                         rcu_assign_pointer(blkcg->blkg_hint, blkg);
150                 }
151                 return blkg;
152         }
153
154         return NULL;
155 }
156 EXPORT_SYMBOL_GPL(blkg_lookup_slowpath);
157
158 /*
159  * If @new_blkg is %NULL, this function tries to allocate a new one as
160  * necessary using %GFP_NOWAIT.  @new_blkg is always consumed on return.
161  */
162 static struct blkcg_gq *blkg_create(struct blkcg *blkcg,
163                                     struct request_queue *q,
164                                     struct blkcg_gq *new_blkg)
165 {
166         struct blkcg_gq *blkg;
167         struct bdi_writeback_congested *wb_congested;
168         int i, ret;
169
170         WARN_ON_ONCE(!rcu_read_lock_held());
171         lockdep_assert_held(q->queue_lock);
172
173         /* blkg holds a reference to blkcg */
174         if (!css_tryget_online(&blkcg->css)) {
175                 ret = -EINVAL;
176                 goto err_free_blkg;
177         }
178
179         wb_congested = wb_congested_get_create(&q->backing_dev_info,
180                                                blkcg->css.id, GFP_NOWAIT);
181         if (!wb_congested) {
182                 ret = -ENOMEM;
183                 goto err_put_css;
184         }
185
186         /* allocate */
187         if (!new_blkg) {
188                 new_blkg = blkg_alloc(blkcg, q, GFP_NOWAIT);
189                 if (unlikely(!new_blkg)) {
190                         ret = -ENOMEM;
191                         goto err_put_congested;
192                 }
193         }
194         blkg = new_blkg;
195         blkg->wb_congested = wb_congested;
196
197         /* link parent */
198         if (blkcg_parent(blkcg)) {
199                 blkg->parent = __blkg_lookup(blkcg_parent(blkcg), q, false);
200                 if (WARN_ON_ONCE(!blkg->parent)) {
201                         ret = -EINVAL;
202                         goto err_put_congested;
203                 }
204                 blkg_get(blkg->parent);
205         }
206
207         /* invoke per-policy init */
208         for (i = 0; i < BLKCG_MAX_POLS; i++) {
209                 struct blkcg_policy *pol = blkcg_policy[i];
210
211                 if (blkg->pd[i] && pol->pd_init_fn)
212                         pol->pd_init_fn(blkg->pd[i]);
213         }
214
215         /* insert */
216         spin_lock(&blkcg->lock);
217         ret = radix_tree_insert(&blkcg->blkg_tree, q->id, blkg);
218         if (likely(!ret)) {
219                 hlist_add_head_rcu(&blkg->blkcg_node, &blkcg->blkg_list);
220                 list_add(&blkg->q_node, &q->blkg_list);
221
222                 for (i = 0; i < BLKCG_MAX_POLS; i++) {
223                         struct blkcg_policy *pol = blkcg_policy[i];
224
225                         if (blkg->pd[i] && pol->pd_online_fn)
226                                 pol->pd_online_fn(blkg->pd[i]);
227                 }
228         }
229         blkg->online = true;
230         spin_unlock(&blkcg->lock);
231
232         if (!ret)
233                 return blkg;
234
235         /* @blkg failed fully initialized, use the usual release path */
236         blkg_put(blkg);
237         return ERR_PTR(ret);
238
239 err_put_congested:
240         wb_congested_put(wb_congested);
241 err_put_css:
242         css_put(&blkcg->css);
243 err_free_blkg:
244         blkg_free(new_blkg);
245         return ERR_PTR(ret);
246 }
247
248 /**
249  * blkg_lookup_create - lookup blkg, try to create one if not there
250  * @blkcg: blkcg of interest
251  * @q: request_queue of interest
252  *
253  * Lookup blkg for the @blkcg - @q pair.  If it doesn't exist, try to
254  * create one.  blkg creation is performed recursively from blkcg_root such
255  * that all non-root blkg's have access to the parent blkg.  This function
256  * should be called under RCU read lock and @q->queue_lock.
257  *
258  * Returns pointer to the looked up or created blkg on success, ERR_PTR()
259  * value on error.  If @q is dead, returns ERR_PTR(-EINVAL).  If @q is not
260  * dead and bypassing, returns ERR_PTR(-EBUSY).
261  */
262 struct blkcg_gq *blkg_lookup_create(struct blkcg *blkcg,
263                                     struct request_queue *q)
264 {
265         struct blkcg_gq *blkg;
266
267         WARN_ON_ONCE(!rcu_read_lock_held());
268         lockdep_assert_held(q->queue_lock);
269
270         /*
271          * This could be the first entry point of blkcg implementation and
272          * we shouldn't allow anything to go through for a bypassing queue.
273          */
274         if (unlikely(blk_queue_bypass(q)))
275                 return ERR_PTR(blk_queue_dying(q) ? -EINVAL : -EBUSY);
276
277         blkg = __blkg_lookup(blkcg, q, true);
278         if (blkg)
279                 return blkg;
280
281         /*
282          * Create blkgs walking down from blkcg_root to @blkcg, so that all
283          * non-root blkgs have access to their parents.
284          */
285         while (true) {
286                 struct blkcg *pos = blkcg;
287                 struct blkcg *parent = blkcg_parent(blkcg);
288
289                 while (parent && !__blkg_lookup(parent, q, false)) {
290                         pos = parent;
291                         parent = blkcg_parent(parent);
292                 }
293
294                 blkg = blkg_create(pos, q, NULL);
295                 if (pos == blkcg || IS_ERR(blkg))
296                         return blkg;
297         }
298 }
299
300 static void blkg_destroy(struct blkcg_gq *blkg)
301 {
302         struct blkcg *blkcg = blkg->blkcg;
303         int i;
304
305         lockdep_assert_held(blkg->q->queue_lock);
306         lockdep_assert_held(&blkcg->lock);
307
308         /* Something wrong if we are trying to remove same group twice */
309         WARN_ON_ONCE(list_empty(&blkg->q_node));
310         WARN_ON_ONCE(hlist_unhashed(&blkg->blkcg_node));
311
312         for (i = 0; i < BLKCG_MAX_POLS; i++) {
313                 struct blkcg_policy *pol = blkcg_policy[i];
314
315                 if (blkg->pd[i] && pol->pd_offline_fn)
316                         pol->pd_offline_fn(blkg->pd[i]);
317         }
318         blkg->online = false;
319
320         radix_tree_delete(&blkcg->blkg_tree, blkg->q->id);
321         list_del_init(&blkg->q_node);
322         hlist_del_init_rcu(&blkg->blkcg_node);
323
324         /*
325          * Both setting lookup hint to and clearing it from @blkg are done
326          * under queue_lock.  If it's not pointing to @blkg now, it never
327          * will.  Hint assignment itself can race safely.
328          */
329         if (rcu_access_pointer(blkcg->blkg_hint) == blkg)
330                 rcu_assign_pointer(blkcg->blkg_hint, NULL);
331
332         /*
333          * Put the reference taken at the time of creation so that when all
334          * queues are gone, group can be destroyed.
335          */
336         blkg_put(blkg);
337 }
338
339 /**
340  * blkg_destroy_all - destroy all blkgs associated with a request_queue
341  * @q: request_queue of interest
342  *
343  * Destroy all blkgs associated with @q.
344  */
345 static void blkg_destroy_all(struct request_queue *q)
346 {
347         struct blkcg_gq *blkg, *n;
348
349         lockdep_assert_held(q->queue_lock);
350
351         list_for_each_entry_safe(blkg, n, &q->blkg_list, q_node) {
352                 struct blkcg *blkcg = blkg->blkcg;
353
354                 spin_lock(&blkcg->lock);
355                 blkg_destroy(blkg);
356                 spin_unlock(&blkcg->lock);
357         }
358 }
359
360 /*
361  * A group is RCU protected, but having an rcu lock does not mean that one
362  * can access all the fields of blkg and assume these are valid.  For
363  * example, don't try to follow throtl_data and request queue links.
364  *
365  * Having a reference to blkg under an rcu allows accesses to only values
366  * local to groups like group stats and group rate limits.
367  */
368 void __blkg_release_rcu(struct rcu_head *rcu_head)
369 {
370         struct blkcg_gq *blkg = container_of(rcu_head, struct blkcg_gq, rcu_head);
371
372         /* release the blkcg and parent blkg refs this blkg has been holding */
373         css_put(&blkg->blkcg->css);
374         if (blkg->parent)
375                 blkg_put(blkg->parent);
376
377         wb_congested_put(blkg->wb_congested);
378
379         blkg_free(blkg);
380 }
381 EXPORT_SYMBOL_GPL(__blkg_release_rcu);
382
383 /*
384  * The next function used by blk_queue_for_each_rl().  It's a bit tricky
385  * because the root blkg uses @q->root_rl instead of its own rl.
386  */
387 struct request_list *__blk_queue_next_rl(struct request_list *rl,
388                                          struct request_queue *q)
389 {
390         struct list_head *ent;
391         struct blkcg_gq *blkg;
392
393         /*
394          * Determine the current blkg list_head.  The first entry is
395          * root_rl which is off @q->blkg_list and mapped to the head.
396          */
397         if (rl == &q->root_rl) {
398                 ent = &q->blkg_list;
399                 /* There are no more block groups, hence no request lists */
400                 if (list_empty(ent))
401                         return NULL;
402         } else {
403                 blkg = container_of(rl, struct blkcg_gq, rl);
404                 ent = &blkg->q_node;
405         }
406
407         /* walk to the next list_head, skip root blkcg */
408         ent = ent->next;
409         if (ent == &q->root_blkg->q_node)
410                 ent = ent->next;
411         if (ent == &q->blkg_list)
412                 return NULL;
413
414         blkg = container_of(ent, struct blkcg_gq, q_node);
415         return &blkg->rl;
416 }
417
418 static int blkcg_reset_stats(struct cgroup_subsys_state *css,
419                              struct cftype *cftype, u64 val)
420 {
421         struct blkcg *blkcg = css_to_blkcg(css);
422         struct blkcg_gq *blkg;
423         int i;
424
425         mutex_lock(&blkcg_pol_mutex);
426         spin_lock_irq(&blkcg->lock);
427
428         /*
429          * Note that stat reset is racy - it doesn't synchronize against
430          * stat updates.  This is a debug feature which shouldn't exist
431          * anyway.  If you get hit by a race, retry.
432          */
433         hlist_for_each_entry(blkg, &blkcg->blkg_list, blkcg_node) {
434                 for (i = 0; i < BLKCG_MAX_POLS; i++) {
435                         struct blkcg_policy *pol = blkcg_policy[i];
436
437                         if (blkg->pd[i] && pol->pd_reset_stats_fn)
438                                 pol->pd_reset_stats_fn(blkg->pd[i]);
439                 }
440         }
441
442         spin_unlock_irq(&blkcg->lock);
443         mutex_unlock(&blkcg_pol_mutex);
444         return 0;
445 }
446
447 static const char *blkg_dev_name(struct blkcg_gq *blkg)
448 {
449         /* some drivers (floppy) instantiate a queue w/o disk registered */
450         if (blkg->q->backing_dev_info.dev)
451                 return dev_name(blkg->q->backing_dev_info.dev);
452         return NULL;
453 }
454
455 /**
456  * blkcg_print_blkgs - helper for printing per-blkg data
457  * @sf: seq_file to print to
458  * @blkcg: blkcg of interest
459  * @prfill: fill function to print out a blkg
460  * @pol: policy in question
461  * @data: data to be passed to @prfill
462  * @show_total: to print out sum of prfill return values or not
463  *
464  * This function invokes @prfill on each blkg of @blkcg if pd for the
465  * policy specified by @pol exists.  @prfill is invoked with @sf, the
466  * policy data and @data and the matching queue lock held.  If @show_total
467  * is %true, the sum of the return values from @prfill is printed with
468  * "Total" label at the end.
469  *
470  * This is to be used to construct print functions for
471  * cftype->read_seq_string method.
472  */
473 void blkcg_print_blkgs(struct seq_file *sf, struct blkcg *blkcg,
474                        u64 (*prfill)(struct seq_file *,
475                                      struct blkg_policy_data *, int),
476                        const struct blkcg_policy *pol, int data,
477                        bool show_total)
478 {
479         struct blkcg_gq *blkg;
480         u64 total = 0;
481
482         rcu_read_lock();
483         hlist_for_each_entry_rcu(blkg, &blkcg->blkg_list, blkcg_node) {
484                 spin_lock_irq(blkg->q->queue_lock);
485                 if (blkcg_policy_enabled(blkg->q, pol))
486                         total += prfill(sf, blkg->pd[pol->plid], data);
487                 spin_unlock_irq(blkg->q->queue_lock);
488         }
489         rcu_read_unlock();
490
491         if (show_total)
492                 seq_printf(sf, "Total %llu\n", (unsigned long long)total);
493 }
494 EXPORT_SYMBOL_GPL(blkcg_print_blkgs);
495
496 /**
497  * __blkg_prfill_u64 - prfill helper for a single u64 value
498  * @sf: seq_file to print to
499  * @pd: policy private data of interest
500  * @v: value to print
501  *
502  * Print @v to @sf for the device assocaited with @pd.
503  */
504 u64 __blkg_prfill_u64(struct seq_file *sf, struct blkg_policy_data *pd, u64 v)
505 {
506         const char *dname = blkg_dev_name(pd->blkg);
507
508         if (!dname)
509                 return 0;
510
511         seq_printf(sf, "%s %llu\n", dname, (unsigned long long)v);
512         return v;
513 }
514 EXPORT_SYMBOL_GPL(__blkg_prfill_u64);
515
516 /**
517  * __blkg_prfill_rwstat - prfill helper for a blkg_rwstat
518  * @sf: seq_file to print to
519  * @pd: policy private data of interest
520  * @rwstat: rwstat to print
521  *
522  * Print @rwstat to @sf for the device assocaited with @pd.
523  */
524 u64 __blkg_prfill_rwstat(struct seq_file *sf, struct blkg_policy_data *pd,
525                          const struct blkg_rwstat *rwstat)
526 {
527         static const char *rwstr[] = {
528                 [BLKG_RWSTAT_READ]      = "Read",
529                 [BLKG_RWSTAT_WRITE]     = "Write",
530                 [BLKG_RWSTAT_SYNC]      = "Sync",
531                 [BLKG_RWSTAT_ASYNC]     = "Async",
532         };
533         const char *dname = blkg_dev_name(pd->blkg);
534         u64 v;
535         int i;
536
537         if (!dname)
538                 return 0;
539
540         for (i = 0; i < BLKG_RWSTAT_NR; i++)
541                 seq_printf(sf, "%s %s %llu\n", dname, rwstr[i],
542                            (unsigned long long)atomic64_read(&rwstat->aux_cnt[i]));
543
544         v = atomic64_read(&rwstat->aux_cnt[BLKG_RWSTAT_READ]) +
545                 atomic64_read(&rwstat->aux_cnt[BLKG_RWSTAT_WRITE]);
546         seq_printf(sf, "%s Total %llu\n", dname, (unsigned long long)v);
547         return v;
548 }
549 EXPORT_SYMBOL_GPL(__blkg_prfill_rwstat);
550
551 /**
552  * blkg_prfill_stat - prfill callback for blkg_stat
553  * @sf: seq_file to print to
554  * @pd: policy private data of interest
555  * @off: offset to the blkg_stat in @pd
556  *
557  * prfill callback for printing a blkg_stat.
558  */
559 u64 blkg_prfill_stat(struct seq_file *sf, struct blkg_policy_data *pd, int off)
560 {
561         return __blkg_prfill_u64(sf, pd, blkg_stat_read((void *)pd + off));
562 }
563 EXPORT_SYMBOL_GPL(blkg_prfill_stat);
564
565 /**
566  * blkg_prfill_rwstat - prfill callback for blkg_rwstat
567  * @sf: seq_file to print to
568  * @pd: policy private data of interest
569  * @off: offset to the blkg_rwstat in @pd
570  *
571  * prfill callback for printing a blkg_rwstat.
572  */
573 u64 blkg_prfill_rwstat(struct seq_file *sf, struct blkg_policy_data *pd,
574                        int off)
575 {
576         struct blkg_rwstat rwstat = blkg_rwstat_read((void *)pd + off);
577
578         return __blkg_prfill_rwstat(sf, pd, &rwstat);
579 }
580 EXPORT_SYMBOL_GPL(blkg_prfill_rwstat);
581
582 /**
583  * blkg_stat_recursive_sum - collect hierarchical blkg_stat
584  * @pd: policy private data of interest
585  * @off: offset to the blkg_stat in @pd
586  *
587  * Collect the blkg_stat specified by @off from @pd and all its online
588  * descendants and their aux counts.  The caller must be holding the queue
589  * lock for online tests.
590  */
591 u64 blkg_stat_recursive_sum(struct blkg_policy_data *pd, int off)
592 {
593         struct blkcg_policy *pol = blkcg_policy[pd->plid];
594         struct blkcg_gq *pos_blkg;
595         struct cgroup_subsys_state *pos_css;
596         u64 sum = 0;
597
598         lockdep_assert_held(pd->blkg->q->queue_lock);
599
600         rcu_read_lock();
601         blkg_for_each_descendant_pre(pos_blkg, pos_css, pd_to_blkg(pd)) {
602                 struct blkg_policy_data *pos_pd = blkg_to_pd(pos_blkg, pol);
603                 struct blkg_stat *stat = (void *)pos_pd + off;
604
605                 if (pos_blkg->online)
606                         sum += blkg_stat_read(stat) +
607                                 atomic64_read(&stat->aux_cnt);
608         }
609         rcu_read_unlock();
610
611         return sum;
612 }
613 EXPORT_SYMBOL_GPL(blkg_stat_recursive_sum);
614
615 /**
616  * blkg_rwstat_recursive_sum - collect hierarchical blkg_rwstat
617  * @pd: policy private data of interest
618  * @off: offset to the blkg_stat in @pd
619  *
620  * Collect the blkg_rwstat specified by @off from @pd and all its online
621  * descendants and their aux counts.  The caller must be holding the queue
622  * lock for online tests.
623  */
624 struct blkg_rwstat blkg_rwstat_recursive_sum(struct blkg_policy_data *pd,
625                                              int off)
626 {
627         struct blkcg_policy *pol = blkcg_policy[pd->plid];
628         struct blkcg_gq *pos_blkg;
629         struct cgroup_subsys_state *pos_css;
630         struct blkg_rwstat sum = { };
631         int i;
632
633         lockdep_assert_held(pd->blkg->q->queue_lock);
634
635         rcu_read_lock();
636         blkg_for_each_descendant_pre(pos_blkg, pos_css, pd_to_blkg(pd)) {
637                 struct blkg_policy_data *pos_pd = blkg_to_pd(pos_blkg, pol);
638                 struct blkg_rwstat *rwstat = (void *)pos_pd + off;
639                 struct blkg_rwstat tmp;
640
641                 if (!pos_blkg->online)
642                         continue;
643
644                 tmp = blkg_rwstat_read(rwstat);
645
646                 for (i = 0; i < BLKG_RWSTAT_NR; i++)
647                         atomic64_add(atomic64_read(&tmp.aux_cnt[i]) +
648                                      atomic64_read(&rwstat->aux_cnt[i]),
649                                      &sum.aux_cnt[i]);
650         }
651         rcu_read_unlock();
652
653         return sum;
654 }
655 EXPORT_SYMBOL_GPL(blkg_rwstat_recursive_sum);
656
657 /**
658  * blkg_conf_prep - parse and prepare for per-blkg config update
659  * @blkcg: target block cgroup
660  * @pol: target policy
661  * @input: input string
662  * @ctx: blkg_conf_ctx to be filled
663  *
664  * Parse per-blkg config update from @input and initialize @ctx with the
665  * result.  @ctx->blkg points to the blkg to be updated and @ctx->v the new
666  * value.  This function returns with RCU read lock and queue lock held and
667  * must be paired with blkg_conf_finish().
668  */
669 int blkg_conf_prep(struct blkcg *blkcg, const struct blkcg_policy *pol,
670                    const char *input, struct blkg_conf_ctx *ctx)
671         __acquires(rcu) __acquires(disk->queue->queue_lock)
672 {
673         struct gendisk *disk;
674         struct blkcg_gq *blkg;
675         unsigned int major, minor;
676         unsigned long long v;
677         int part, ret;
678
679         if (sscanf(input, "%u:%u %llu", &major, &minor, &v) != 3)
680                 return -EINVAL;
681
682         disk = get_gendisk(MKDEV(major, minor), &part);
683         if (!disk)
684                 return -EINVAL;
685         if (part) {
686                 put_disk(disk);
687                 return -EINVAL;
688         }
689
690         rcu_read_lock();
691         spin_lock_irq(disk->queue->queue_lock);
692
693         if (blkcg_policy_enabled(disk->queue, pol))
694                 blkg = blkg_lookup_create(blkcg, disk->queue);
695         else
696                 blkg = ERR_PTR(-EINVAL);
697
698         if (IS_ERR(blkg)) {
699                 ret = PTR_ERR(blkg);
700                 rcu_read_unlock();
701                 spin_unlock_irq(disk->queue->queue_lock);
702                 put_disk(disk);
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
716         ctx->disk = disk;
717         ctx->blkg = blkg;
718         ctx->v = v;
719         return 0;
720 }
721 EXPORT_SYMBOL_GPL(blkg_conf_prep);
722
723 /**
724  * blkg_conf_finish - finish up per-blkg config update
725  * @ctx: blkg_conf_ctx intiailized by blkg_conf_prep()
726  *
727  * Finish up after per-blkg config update.  This function must be paired
728  * with blkg_conf_prep().
729  */
730 void blkg_conf_finish(struct blkg_conf_ctx *ctx)
731         __releases(ctx->disk->queue->queue_lock) __releases(rcu)
732 {
733         spin_unlock_irq(ctx->disk->queue->queue_lock);
734         rcu_read_unlock();
735         put_disk(ctx->disk);
736 }
737 EXPORT_SYMBOL_GPL(blkg_conf_finish);
738
739 struct cftype blkcg_files[] = {
740         {
741                 .name = "reset_stats",
742                 .write_u64 = blkcg_reset_stats,
743         },
744         { }     /* terminate */
745 };
746
747 /**
748  * blkcg_css_offline - cgroup css_offline callback
749  * @css: css of interest
750  *
751  * This function is called when @css is about to go away and responsible
752  * for shooting down all blkgs associated with @css.  blkgs should be
753  * removed while holding both q and blkcg locks.  As blkcg lock is nested
754  * inside q lock, this function performs reverse double lock dancing.
755  *
756  * This is the blkcg counterpart of ioc_release_fn().
757  */
758 static void blkcg_css_offline(struct cgroup_subsys_state *css)
759 {
760         struct blkcg *blkcg = css_to_blkcg(css);
761
762         spin_lock_irq(&blkcg->lock);
763
764         while (!hlist_empty(&blkcg->blkg_list)) {
765                 struct blkcg_gq *blkg = hlist_entry(blkcg->blkg_list.first,
766                                                 struct blkcg_gq, blkcg_node);
767                 struct request_queue *q = blkg->q;
768
769                 if (spin_trylock(q->queue_lock)) {
770                         blkg_destroy(blkg);
771                         spin_unlock(q->queue_lock);
772                 } else {
773                         spin_unlock_irq(&blkcg->lock);
774                         cpu_relax();
775                         spin_lock_irq(&blkcg->lock);
776                 }
777         }
778
779         spin_unlock_irq(&blkcg->lock);
780
781         wb_blkcg_offline(blkcg);
782 }
783
784 static void blkcg_css_free(struct cgroup_subsys_state *css)
785 {
786         struct blkcg *blkcg = css_to_blkcg(css);
787         int i;
788
789         mutex_lock(&blkcg_pol_mutex);
790
791         list_del(&blkcg->all_blkcgs_node);
792
793         for (i = 0; i < BLKCG_MAX_POLS; i++)
794                 if (blkcg->cpd[i])
795                         blkcg_policy[i]->cpd_free_fn(blkcg->cpd[i]);
796
797         mutex_unlock(&blkcg_pol_mutex);
798
799         kfree(blkcg);
800 }
801
802 static struct cgroup_subsys_state *
803 blkcg_css_alloc(struct cgroup_subsys_state *parent_css)
804 {
805         struct blkcg *blkcg;
806         struct cgroup_subsys_state *ret;
807         int i;
808
809         mutex_lock(&blkcg_pol_mutex);
810
811         if (!parent_css) {
812                 blkcg = &blkcg_root;
813         } else {
814                 blkcg = kzalloc(sizeof(*blkcg), GFP_KERNEL);
815                 if (!blkcg) {
816                         ret = ERR_PTR(-ENOMEM);
817                         goto free_blkcg;
818                 }
819         }
820
821         for (i = 0; i < BLKCG_MAX_POLS ; i++) {
822                 struct blkcg_policy *pol = blkcg_policy[i];
823                 struct blkcg_policy_data *cpd;
824
825                 /*
826                  * If the policy hasn't been attached yet, wait for it
827                  * to be attached before doing anything else. Otherwise,
828                  * check if the policy requires any specific per-cgroup
829                  * data: if it does, allocate and initialize it.
830                  */
831                 if (!pol || !pol->cpd_alloc_fn)
832                         continue;
833
834                 cpd = pol->cpd_alloc_fn(GFP_KERNEL);
835                 if (!cpd) {
836                         ret = ERR_PTR(-ENOMEM);
837                         goto free_pd_blkcg;
838                 }
839                 blkcg->cpd[i] = cpd;
840                 cpd->blkcg = blkcg;
841                 cpd->plid = i;
842                 if (pol->cpd_init_fn)
843                         pol->cpd_init_fn(cpd);
844         }
845
846         spin_lock_init(&blkcg->lock);
847         INIT_RADIX_TREE(&blkcg->blkg_tree, GFP_NOWAIT);
848         INIT_HLIST_HEAD(&blkcg->blkg_list);
849 #ifdef CONFIG_CGROUP_WRITEBACK
850         INIT_LIST_HEAD(&blkcg->cgwb_list);
851 #endif
852         list_add_tail(&blkcg->all_blkcgs_node, &all_blkcgs);
853
854         mutex_unlock(&blkcg_pol_mutex);
855         return &blkcg->css;
856
857 free_pd_blkcg:
858         for (i--; i >= 0; i--)
859                 if (blkcg->cpd[i])
860                         blkcg_policy[i]->cpd_free_fn(blkcg->cpd[i]);
861 free_blkcg:
862         kfree(blkcg);
863         mutex_unlock(&blkcg_pol_mutex);
864         return ret;
865 }
866
867 /**
868  * blkcg_init_queue - initialize blkcg part of request queue
869  * @q: request_queue to initialize
870  *
871  * Called from blk_alloc_queue_node(). Responsible for initializing blkcg
872  * part of new request_queue @q.
873  *
874  * RETURNS:
875  * 0 on success, -errno on failure.
876  */
877 int blkcg_init_queue(struct request_queue *q)
878 {
879         struct blkcg_gq *new_blkg, *blkg;
880         bool preloaded;
881         int ret;
882
883         new_blkg = blkg_alloc(&blkcg_root, q, GFP_KERNEL);
884         if (!new_blkg)
885                 return -ENOMEM;
886
887         preloaded = !radix_tree_preload(GFP_KERNEL);
888
889         /*
890          * Make sure the root blkg exists and count the existing blkgs.  As
891          * @q is bypassing at this point, blkg_lookup_create() can't be
892          * used.  Open code insertion.
893          */
894         rcu_read_lock();
895         spin_lock_irq(q->queue_lock);
896         blkg = blkg_create(&blkcg_root, q, new_blkg);
897         spin_unlock_irq(q->queue_lock);
898         rcu_read_unlock();
899
900         if (preloaded)
901                 radix_tree_preload_end();
902
903         if (IS_ERR(blkg)) {
904                 blkg_free(new_blkg);
905                 return PTR_ERR(blkg);
906         }
907
908         q->root_blkg = blkg;
909         q->root_rl.blkg = blkg;
910
911         ret = blk_throtl_init(q);
912         if (ret) {
913                 spin_lock_irq(q->queue_lock);
914                 blkg_destroy_all(q);
915                 spin_unlock_irq(q->queue_lock);
916         }
917         return ret;
918 }
919
920 /**
921  * blkcg_drain_queue - drain blkcg part of request_queue
922  * @q: request_queue to drain
923  *
924  * Called from blk_drain_queue().  Responsible for draining blkcg part.
925  */
926 void blkcg_drain_queue(struct request_queue *q)
927 {
928         lockdep_assert_held(q->queue_lock);
929
930         /*
931          * @q could be exiting and already have destroyed all blkgs as
932          * indicated by NULL root_blkg.  If so, don't confuse policies.
933          */
934         if (!q->root_blkg)
935                 return;
936
937         blk_throtl_drain(q);
938 }
939
940 /**
941  * blkcg_exit_queue - exit and release blkcg part of request_queue
942  * @q: request_queue being released
943  *
944  * Called from blk_release_queue().  Responsible for exiting blkcg part.
945  */
946 void blkcg_exit_queue(struct request_queue *q)
947 {
948         spin_lock_irq(q->queue_lock);
949         blkg_destroy_all(q);
950         spin_unlock_irq(q->queue_lock);
951
952         blk_throtl_exit(q);
953 }
954
955 /*
956  * We cannot support shared io contexts, as we have no mean to support
957  * two tasks with the same ioc in two different groups without major rework
958  * of the main cic data structures.  For now we allow a task to change
959  * its cgroup only if it's the only owner of its ioc.
960  */
961 static int blkcg_can_attach(struct cgroup_subsys_state *css,
962                             struct cgroup_taskset *tset)
963 {
964         struct task_struct *task;
965         struct io_context *ioc;
966         int ret = 0;
967
968         /* task_lock() is needed to avoid races with exit_io_context() */
969         cgroup_taskset_for_each(task, tset) {
970                 task_lock(task);
971                 ioc = task->io_context;
972                 if (ioc && atomic_read(&ioc->nr_tasks) > 1)
973                         ret = -EINVAL;
974                 task_unlock(task);
975                 if (ret)
976                         break;
977         }
978         return ret;
979 }
980
981 struct cgroup_subsys blkio_cgrp_subsys = {
982         .css_alloc = blkcg_css_alloc,
983         .css_offline = blkcg_css_offline,
984         .css_free = blkcg_css_free,
985         .can_attach = blkcg_can_attach,
986         .legacy_cftypes = blkcg_files,
987 #ifdef CONFIG_MEMCG
988         /*
989          * This ensures that, if available, memcg is automatically enabled
990          * together on the default hierarchy so that the owner cgroup can
991          * be retrieved from writeback pages.
992          */
993         .depends_on = 1 << memory_cgrp_id,
994 #endif
995 };
996 EXPORT_SYMBOL_GPL(blkio_cgrp_subsys);
997
998 /**
999  * blkcg_activate_policy - activate a blkcg policy on a request_queue
1000  * @q: request_queue of interest
1001  * @pol: blkcg policy to activate
1002  *
1003  * Activate @pol on @q.  Requires %GFP_KERNEL context.  @q goes through
1004  * bypass mode to populate its blkgs with policy_data for @pol.
1005  *
1006  * Activation happens with @q bypassed, so nobody would be accessing blkgs
1007  * from IO path.  Update of each blkg is protected by both queue and blkcg
1008  * locks so that holding either lock and testing blkcg_policy_enabled() is
1009  * always enough for dereferencing policy data.
1010  *
1011  * The caller is responsible for synchronizing [de]activations and policy
1012  * [un]registerations.  Returns 0 on success, -errno on failure.
1013  */
1014 int blkcg_activate_policy(struct request_queue *q,
1015                           const struct blkcg_policy *pol)
1016 {
1017         struct blkg_policy_data *pd_prealloc = NULL;
1018         struct blkcg_gq *blkg;
1019         int ret;
1020
1021         if (blkcg_policy_enabled(q, pol))
1022                 return 0;
1023
1024         blk_queue_bypass_start(q);
1025 pd_prealloc:
1026         if (!pd_prealloc) {
1027                 pd_prealloc = pol->pd_alloc_fn(GFP_KERNEL, q->node);
1028                 if (!pd_prealloc) {
1029                         ret = -ENOMEM;
1030                         goto out_bypass_end;
1031                 }
1032         }
1033
1034         spin_lock_irq(q->queue_lock);
1035
1036         list_for_each_entry(blkg, &q->blkg_list, q_node) {
1037                 struct blkg_policy_data *pd;
1038
1039                 if (blkg->pd[pol->plid])
1040                         continue;
1041
1042                 pd = pol->pd_alloc_fn(GFP_NOWAIT, q->node);
1043                 if (!pd)
1044                         swap(pd, pd_prealloc);
1045                 if (!pd) {
1046                         spin_unlock_irq(q->queue_lock);
1047                         goto pd_prealloc;
1048                 }
1049
1050                 blkg->pd[pol->plid] = pd;
1051                 pd->blkg = blkg;
1052                 pd->plid = pol->plid;
1053                 if (pol->pd_init_fn)
1054                         pol->pd_init_fn(pd);
1055         }
1056
1057         __set_bit(pol->plid, q->blkcg_pols);
1058         ret = 0;
1059
1060         spin_unlock_irq(q->queue_lock);
1061 out_bypass_end:
1062         blk_queue_bypass_end(q);
1063         if (pd_prealloc)
1064                 pol->pd_free_fn(pd_prealloc);
1065         return ret;
1066 }
1067 EXPORT_SYMBOL_GPL(blkcg_activate_policy);
1068
1069 /**
1070  * blkcg_deactivate_policy - deactivate a blkcg policy on a request_queue
1071  * @q: request_queue of interest
1072  * @pol: blkcg policy to deactivate
1073  *
1074  * Deactivate @pol on @q.  Follows the same synchronization rules as
1075  * blkcg_activate_policy().
1076  */
1077 void blkcg_deactivate_policy(struct request_queue *q,
1078                              const struct blkcg_policy *pol)
1079 {
1080         struct blkcg_gq *blkg;
1081
1082         if (!blkcg_policy_enabled(q, pol))
1083                 return;
1084
1085         blk_queue_bypass_start(q);
1086         spin_lock_irq(q->queue_lock);
1087
1088         __clear_bit(pol->plid, q->blkcg_pols);
1089
1090         list_for_each_entry(blkg, &q->blkg_list, q_node) {
1091                 /* grab blkcg lock too while removing @pd from @blkg */
1092                 spin_lock(&blkg->blkcg->lock);
1093
1094                 if (blkg->pd[pol->plid]) {
1095                         if (pol->pd_offline_fn)
1096                                 pol->pd_offline_fn(blkg->pd[pol->plid]);
1097                         pol->pd_free_fn(blkg->pd[pol->plid]);
1098                         blkg->pd[pol->plid] = NULL;
1099                 }
1100
1101                 spin_unlock(&blkg->blkcg->lock);
1102         }
1103
1104         spin_unlock_irq(q->queue_lock);
1105         blk_queue_bypass_end(q);
1106 }
1107 EXPORT_SYMBOL_GPL(blkcg_deactivate_policy);
1108
1109 /**
1110  * blkcg_policy_register - register a blkcg policy
1111  * @pol: blkcg policy to register
1112  *
1113  * Register @pol with blkcg core.  Might sleep and @pol may be modified on
1114  * successful registration.  Returns 0 on success and -errno on failure.
1115  */
1116 int blkcg_policy_register(struct blkcg_policy *pol)
1117 {
1118         struct blkcg *blkcg;
1119         int i, ret;
1120
1121         mutex_lock(&blkcg_pol_register_mutex);
1122         mutex_lock(&blkcg_pol_mutex);
1123
1124         /* find an empty slot */
1125         ret = -ENOSPC;
1126         for (i = 0; i < BLKCG_MAX_POLS; i++)
1127                 if (!blkcg_policy[i])
1128                         break;
1129         if (i >= BLKCG_MAX_POLS)
1130                 goto err_unlock;
1131
1132         /* register @pol */
1133         pol->plid = i;
1134         blkcg_policy[pol->plid] = pol;
1135
1136         /* allocate and install cpd's */
1137         if (pol->cpd_alloc_fn) {
1138                 list_for_each_entry(blkcg, &all_blkcgs, all_blkcgs_node) {
1139                         struct blkcg_policy_data *cpd;
1140
1141                         cpd = pol->cpd_alloc_fn(GFP_KERNEL);
1142                         if (!cpd) {
1143                                 mutex_unlock(&blkcg_pol_mutex);
1144                                 goto err_free_cpds;
1145                         }
1146
1147                         blkcg->cpd[pol->plid] = cpd;
1148                         cpd->blkcg = blkcg;
1149                         cpd->plid = pol->plid;
1150                         pol->cpd_init_fn(cpd);
1151                 }
1152         }
1153
1154         mutex_unlock(&blkcg_pol_mutex);
1155
1156         /* everything is in place, add intf files for the new policy */
1157         if (pol->cftypes)
1158                 WARN_ON(cgroup_add_legacy_cftypes(&blkio_cgrp_subsys,
1159                                                   pol->cftypes));
1160         mutex_unlock(&blkcg_pol_register_mutex);
1161         return 0;
1162
1163 err_free_cpds:
1164         if (pol->cpd_alloc_fn) {
1165                 list_for_each_entry(blkcg, &all_blkcgs, all_blkcgs_node) {
1166                         if (blkcg->cpd[pol->plid]) {
1167                                 pol->cpd_free_fn(blkcg->cpd[pol->plid]);
1168                                 blkcg->cpd[pol->plid] = NULL;
1169                         }
1170                 }
1171         }
1172         blkcg_policy[pol->plid] = NULL;
1173 err_unlock:
1174         mutex_unlock(&blkcg_pol_mutex);
1175         mutex_unlock(&blkcg_pol_register_mutex);
1176         return ret;
1177 }
1178 EXPORT_SYMBOL_GPL(blkcg_policy_register);
1179
1180 /**
1181  * blkcg_policy_unregister - unregister a blkcg policy
1182  * @pol: blkcg policy to unregister
1183  *
1184  * Undo blkcg_policy_register(@pol).  Might sleep.
1185  */
1186 void blkcg_policy_unregister(struct blkcg_policy *pol)
1187 {
1188         struct blkcg *blkcg;
1189
1190         mutex_lock(&blkcg_pol_register_mutex);
1191
1192         if (WARN_ON(blkcg_policy[pol->plid] != pol))
1193                 goto out_unlock;
1194
1195         /* kill the intf files first */
1196         if (pol->cftypes)
1197                 cgroup_rm_cftypes(pol->cftypes);
1198
1199         /* remove cpds and unregister */
1200         mutex_lock(&blkcg_pol_mutex);
1201
1202         if (pol->cpd_alloc_fn) {
1203                 list_for_each_entry(blkcg, &all_blkcgs, all_blkcgs_node) {
1204                         if (blkcg->cpd[pol->plid]) {
1205                                 pol->cpd_free_fn(blkcg->cpd[pol->plid]);
1206                                 blkcg->cpd[pol->plid] = NULL;
1207                         }
1208                 }
1209         }
1210         blkcg_policy[pol->plid] = NULL;
1211
1212         mutex_unlock(&blkcg_pol_mutex);
1213 out_unlock:
1214         mutex_unlock(&blkcg_pol_register_mutex);
1215 }
1216 EXPORT_SYMBOL_GPL(blkcg_policy_unregister);