blk-cgroup.c 58 KB

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