blk-cgroup.c 59 KB

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