blk-cgroup.c 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209
  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. mutex_lock(&blkcg_pol_register_mutex);
  1483. mutex_lock(&blkcg_pol_mutex);
  1484. /* find an empty slot */
  1485. ret = -ENOSPC;
  1486. for (i = 0; i < BLKCG_MAX_POLS; i++)
  1487. if (!blkcg_policy[i])
  1488. break;
  1489. if (i >= BLKCG_MAX_POLS) {
  1490. pr_warn("blkcg_policy_register: BLKCG_MAX_POLS too small\n");
  1491. goto err_unlock;
  1492. }
  1493. /*
  1494. * Make sure cpd/pd_alloc_fn and cpd/pd_free_fn in pairs, and policy
  1495. * without pd_alloc_fn/pd_free_fn can't be activated.
  1496. */
  1497. if ((!pol->cpd_alloc_fn ^ !pol->cpd_free_fn) ||
  1498. (!pol->pd_alloc_fn ^ !pol->pd_free_fn))
  1499. goto err_unlock;
  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. goto err_free_cpds;
  1510. blkcg->cpd[pol->plid] = cpd;
  1511. cpd->blkcg = blkcg;
  1512. cpd->plid = pol->plid;
  1513. }
  1514. }
  1515. mutex_unlock(&blkcg_pol_mutex);
  1516. /* everything is in place, add intf files for the new policy */
  1517. if (pol->dfl_cftypes)
  1518. WARN_ON(cgroup_add_dfl_cftypes(&io_cgrp_subsys,
  1519. pol->dfl_cftypes));
  1520. if (pol->legacy_cftypes)
  1521. WARN_ON(cgroup_add_legacy_cftypes(&io_cgrp_subsys,
  1522. pol->legacy_cftypes));
  1523. mutex_unlock(&blkcg_pol_register_mutex);
  1524. return 0;
  1525. err_free_cpds:
  1526. if (pol->cpd_free_fn)
  1527. blkcg_free_all_cpd(pol);
  1528. blkcg_policy[pol->plid] = NULL;
  1529. err_unlock:
  1530. mutex_unlock(&blkcg_pol_mutex);
  1531. mutex_unlock(&blkcg_pol_register_mutex);
  1532. return ret;
  1533. }
  1534. EXPORT_SYMBOL_GPL(blkcg_policy_register);
  1535. /**
  1536. * blkcg_policy_unregister - unregister a blkcg policy
  1537. * @pol: blkcg policy to unregister
  1538. *
  1539. * Undo blkcg_policy_register(@pol). Might sleep.
  1540. */
  1541. void blkcg_policy_unregister(struct blkcg_policy *pol)
  1542. {
  1543. mutex_lock(&blkcg_pol_register_mutex);
  1544. if (WARN_ON(blkcg_policy[pol->plid] != pol))
  1545. goto out_unlock;
  1546. /* kill the intf files first */
  1547. if (pol->dfl_cftypes)
  1548. cgroup_rm_cftypes(pol->dfl_cftypes);
  1549. if (pol->legacy_cftypes)
  1550. cgroup_rm_cftypes(pol->legacy_cftypes);
  1551. /* remove cpds and unregister */
  1552. mutex_lock(&blkcg_pol_mutex);
  1553. if (pol->cpd_free_fn)
  1554. blkcg_free_all_cpd(pol);
  1555. blkcg_policy[pol->plid] = NULL;
  1556. mutex_unlock(&blkcg_pol_mutex);
  1557. out_unlock:
  1558. mutex_unlock(&blkcg_pol_register_mutex);
  1559. }
  1560. EXPORT_SYMBOL_GPL(blkcg_policy_unregister);
  1561. /*
  1562. * Scale the accumulated delay based on how long it has been since we updated
  1563. * the delay. We only call this when we are adding delay, in case it's been a
  1564. * while since we added delay, and when we are checking to see if we need to
  1565. * delay a task, to account for any delays that may have occurred.
  1566. */
  1567. static void blkcg_scale_delay(struct blkcg_gq *blkg, u64 now)
  1568. {
  1569. u64 old = atomic64_read(&blkg->delay_start);
  1570. /* negative use_delay means no scaling, see blkcg_set_delay() */
  1571. if (atomic_read(&blkg->use_delay) < 0)
  1572. return;
  1573. /*
  1574. * We only want to scale down every second. The idea here is that we
  1575. * want to delay people for min(delay_nsec, NSEC_PER_SEC) in a certain
  1576. * time window. We only want to throttle tasks for recent delay that
  1577. * has occurred, in 1 second time windows since that's the maximum
  1578. * things can be throttled. We save the current delay window in
  1579. * blkg->last_delay so we know what amount is still left to be charged
  1580. * to the blkg from this point onward. blkg->last_use keeps track of
  1581. * the use_delay counter. The idea is if we're unthrottling the blkg we
  1582. * are ok with whatever is happening now, and we can take away more of
  1583. * the accumulated delay as we've already throttled enough that
  1584. * everybody is happy with their IO latencies.
  1585. */
  1586. if (time_before64(old + NSEC_PER_SEC, now) &&
  1587. atomic64_try_cmpxchg(&blkg->delay_start, &old, now)) {
  1588. u64 cur = atomic64_read(&blkg->delay_nsec);
  1589. u64 sub = min_t(u64, blkg->last_delay, now - old);
  1590. int cur_use = atomic_read(&blkg->use_delay);
  1591. /*
  1592. * We've been unthrottled, subtract a larger chunk of our
  1593. * accumulated delay.
  1594. */
  1595. if (cur_use < blkg->last_use)
  1596. sub = max_t(u64, sub, blkg->last_delay >> 1);
  1597. /*
  1598. * This shouldn't happen, but handle it anyway. Our delay_nsec
  1599. * should only ever be growing except here where we subtract out
  1600. * min(last_delay, 1 second), but lord knows bugs happen and I'd
  1601. * rather not end up with negative numbers.
  1602. */
  1603. if (unlikely(cur < sub)) {
  1604. atomic64_set(&blkg->delay_nsec, 0);
  1605. blkg->last_delay = 0;
  1606. } else {
  1607. atomic64_sub(sub, &blkg->delay_nsec);
  1608. blkg->last_delay = cur - sub;
  1609. }
  1610. blkg->last_use = cur_use;
  1611. }
  1612. }
  1613. /*
  1614. * This is called when we want to actually walk up the hierarchy and check to
  1615. * see if we need to throttle, and then actually throttle if there is some
  1616. * accumulated delay. This should only be called upon return to user space so
  1617. * we're not holding some lock that would induce a priority inversion.
  1618. */
  1619. static void blkcg_maybe_throttle_blkg(struct blkcg_gq *blkg, bool use_memdelay)
  1620. {
  1621. unsigned long pflags;
  1622. bool clamp;
  1623. u64 now = blk_time_get_ns();
  1624. u64 exp;
  1625. u64 delay_nsec = 0;
  1626. int tok;
  1627. while (blkg->parent) {
  1628. int use_delay = atomic_read(&blkg->use_delay);
  1629. if (use_delay) {
  1630. u64 this_delay;
  1631. blkcg_scale_delay(blkg, now);
  1632. this_delay = atomic64_read(&blkg->delay_nsec);
  1633. if (this_delay > delay_nsec) {
  1634. delay_nsec = this_delay;
  1635. clamp = use_delay > 0;
  1636. }
  1637. }
  1638. blkg = blkg->parent;
  1639. }
  1640. if (!delay_nsec)
  1641. return;
  1642. /*
  1643. * Let's not sleep for all eternity if we've amassed a huge delay.
  1644. * Swapping or metadata IO can accumulate 10's of seconds worth of
  1645. * delay, and we want userspace to be able to do _something_ so cap the
  1646. * delays at 0.25s. If there's 10's of seconds worth of delay then the
  1647. * tasks will be delayed for 0.25 second for every syscall. If
  1648. * blkcg_set_delay() was used as indicated by negative use_delay, the
  1649. * caller is responsible for regulating the range.
  1650. */
  1651. if (clamp)
  1652. delay_nsec = min_t(u64, delay_nsec, 250 * NSEC_PER_MSEC);
  1653. if (use_memdelay)
  1654. psi_memstall_enter(&pflags);
  1655. exp = ktime_add_ns(now, delay_nsec);
  1656. tok = io_schedule_prepare();
  1657. do {
  1658. __set_current_state(TASK_KILLABLE);
  1659. if (!schedule_hrtimeout(&exp, HRTIMER_MODE_ABS))
  1660. break;
  1661. } while (!fatal_signal_pending(current));
  1662. io_schedule_finish(tok);
  1663. if (use_memdelay)
  1664. psi_memstall_leave(&pflags);
  1665. }
  1666. /**
  1667. * blkcg_maybe_throttle_current - throttle the current task if it has been marked
  1668. *
  1669. * This is only called if we've been marked with set_notify_resume(). Obviously
  1670. * we can be set_notify_resume() for reasons other than blkcg throttling, so we
  1671. * check to see if current->throttle_disk is set and if not this doesn't do
  1672. * anything. This should only ever be called by the resume code, it's not meant
  1673. * to be called by people willy-nilly as it will actually do the work to
  1674. * throttle the task if it is setup for throttling.
  1675. */
  1676. void blkcg_maybe_throttle_current(void)
  1677. {
  1678. struct gendisk *disk = current->throttle_disk;
  1679. struct blkcg *blkcg;
  1680. struct blkcg_gq *blkg;
  1681. bool use_memdelay = current->use_memdelay;
  1682. if (!disk)
  1683. return;
  1684. current->throttle_disk = NULL;
  1685. current->use_memdelay = false;
  1686. rcu_read_lock();
  1687. blkcg = css_to_blkcg(blkcg_css());
  1688. if (!blkcg)
  1689. goto out;
  1690. blkg = blkg_lookup(blkcg, disk->queue);
  1691. if (!blkg)
  1692. goto out;
  1693. if (!blkg_tryget(blkg))
  1694. goto out;
  1695. rcu_read_unlock();
  1696. blkcg_maybe_throttle_blkg(blkg, use_memdelay);
  1697. blkg_put(blkg);
  1698. put_disk(disk);
  1699. return;
  1700. out:
  1701. rcu_read_unlock();
  1702. }
  1703. /**
  1704. * blkcg_schedule_throttle - this task needs to check for throttling
  1705. * @disk: disk to throttle
  1706. * @use_memdelay: do we charge this to memory delay for PSI
  1707. *
  1708. * This is called by the IO controller when we know there's delay accumulated
  1709. * for the blkg for this task. We do not pass the blkg because there are places
  1710. * we call this that may not have that information, the swapping code for
  1711. * instance will only have a block_device at that point. This set's the
  1712. * notify_resume for the task to check and see if it requires throttling before
  1713. * returning to user space.
  1714. *
  1715. * We will only schedule once per syscall. You can call this over and over
  1716. * again and it will only do the check once upon return to user space, and only
  1717. * throttle once. If the task needs to be throttled again it'll need to be
  1718. * re-set at the next time we see the task.
  1719. */
  1720. void blkcg_schedule_throttle(struct gendisk *disk, bool use_memdelay)
  1721. {
  1722. if (unlikely(current->flags & PF_KTHREAD))
  1723. return;
  1724. if (current->throttle_disk != disk) {
  1725. if (test_bit(GD_DEAD, &disk->state))
  1726. return;
  1727. get_device(disk_to_dev(disk));
  1728. if (current->throttle_disk)
  1729. put_disk(current->throttle_disk);
  1730. current->throttle_disk = disk;
  1731. }
  1732. if (use_memdelay)
  1733. current->use_memdelay = use_memdelay;
  1734. set_notify_resume(current);
  1735. }
  1736. /**
  1737. * blkcg_add_delay - add delay to this blkg
  1738. * @blkg: blkg of interest
  1739. * @now: the current time in nanoseconds
  1740. * @delta: how many nanoseconds of delay to add
  1741. *
  1742. * Charge @delta to the blkg's current delay accumulation. This is used to
  1743. * throttle tasks if an IO controller thinks we need more throttling.
  1744. */
  1745. void blkcg_add_delay(struct blkcg_gq *blkg, u64 now, u64 delta)
  1746. {
  1747. if (WARN_ON_ONCE(atomic_read(&blkg->use_delay) < 0))
  1748. return;
  1749. blkcg_scale_delay(blkg, now);
  1750. atomic64_add(delta, &blkg->delay_nsec);
  1751. }
  1752. /**
  1753. * blkg_tryget_closest - try and get a blkg ref on the closet blkg
  1754. * @bio: target bio
  1755. * @css: target css
  1756. *
  1757. * As the failure mode here is to walk up the blkg tree, this ensure that the
  1758. * blkg->parent pointers are always valid. This returns the blkg that it ended
  1759. * up taking a reference on or %NULL if no reference was taken.
  1760. */
  1761. static inline struct blkcg_gq *blkg_tryget_closest(struct bio *bio,
  1762. struct cgroup_subsys_state *css)
  1763. {
  1764. struct blkcg_gq *blkg, *ret_blkg = NULL;
  1765. rcu_read_lock();
  1766. blkg = blkg_lookup_create(css_to_blkcg(css), bio->bi_bdev->bd_disk);
  1767. while (blkg) {
  1768. if (blkg_tryget(blkg)) {
  1769. ret_blkg = blkg;
  1770. break;
  1771. }
  1772. blkg = blkg->parent;
  1773. }
  1774. rcu_read_unlock();
  1775. return ret_blkg;
  1776. }
  1777. /**
  1778. * bio_associate_blkg_from_css - associate a bio with a specified css
  1779. * @bio: target bio
  1780. * @css: target css
  1781. *
  1782. * Associate @bio with the blkg found by combining the css's blkg and the
  1783. * request_queue of the @bio. An association failure is handled by walking up
  1784. * the blkg tree. Therefore, the blkg associated can be anything between @blkg
  1785. * and q->root_blkg. This situation only happens when a cgroup is dying and
  1786. * then the remaining bios will spill to the closest alive blkg.
  1787. *
  1788. * A reference will be taken on the blkg and will be released when @bio is
  1789. * freed.
  1790. */
  1791. void bio_associate_blkg_from_css(struct bio *bio,
  1792. struct cgroup_subsys_state *css)
  1793. {
  1794. if (bio->bi_blkg)
  1795. blkg_put(bio->bi_blkg);
  1796. if (css && css->parent) {
  1797. bio->bi_blkg = blkg_tryget_closest(bio, css);
  1798. } else {
  1799. blkg_get(bdev_get_queue(bio->bi_bdev)->root_blkg);
  1800. bio->bi_blkg = bdev_get_queue(bio->bi_bdev)->root_blkg;
  1801. }
  1802. }
  1803. EXPORT_SYMBOL_GPL(bio_associate_blkg_from_css);
  1804. /**
  1805. * bio_associate_blkg - associate a bio with a blkg
  1806. * @bio: target bio
  1807. *
  1808. * Associate @bio with the blkg found from the bio's css and request_queue.
  1809. * If one is not found, bio_lookup_blkg() creates the blkg. If a blkg is
  1810. * already associated, the css is reused and association redone as the
  1811. * request_queue may have changed.
  1812. */
  1813. void bio_associate_blkg(struct bio *bio)
  1814. {
  1815. struct cgroup_subsys_state *css;
  1816. if (blk_op_is_passthrough(bio->bi_opf))
  1817. return;
  1818. rcu_read_lock();
  1819. if (bio->bi_blkg)
  1820. css = bio_blkcg_css(bio);
  1821. else
  1822. css = blkcg_css();
  1823. bio_associate_blkg_from_css(bio, css);
  1824. rcu_read_unlock();
  1825. }
  1826. EXPORT_SYMBOL_GPL(bio_associate_blkg);
  1827. /**
  1828. * bio_clone_blkg_association - clone blkg association from src to dst bio
  1829. * @dst: destination bio
  1830. * @src: source bio
  1831. */
  1832. void bio_clone_blkg_association(struct bio *dst, struct bio *src)
  1833. {
  1834. if (src->bi_blkg)
  1835. bio_associate_blkg_from_css(dst, bio_blkcg_css(src));
  1836. }
  1837. EXPORT_SYMBOL_GPL(bio_clone_blkg_association);
  1838. static int blk_cgroup_io_type(struct bio *bio)
  1839. {
  1840. if (op_is_discard(bio->bi_opf))
  1841. return BLKG_IOSTAT_DISCARD;
  1842. if (op_is_write(bio->bi_opf))
  1843. return BLKG_IOSTAT_WRITE;
  1844. return BLKG_IOSTAT_READ;
  1845. }
  1846. void blk_cgroup_bio_start(struct bio *bio)
  1847. {
  1848. struct blkcg *blkcg = bio->bi_blkg->blkcg;
  1849. int rwd = blk_cgroup_io_type(bio), cpu;
  1850. struct blkg_iostat_set *bis;
  1851. unsigned long flags;
  1852. if (!cgroup_subsys_on_dfl(io_cgrp_subsys))
  1853. return;
  1854. /* Root-level stats are sourced from system-wide IO stats */
  1855. if (!cgroup_parent(blkcg->css.cgroup))
  1856. return;
  1857. cpu = get_cpu();
  1858. bis = per_cpu_ptr(bio->bi_blkg->iostat_cpu, cpu);
  1859. flags = u64_stats_update_begin_irqsave(&bis->sync);
  1860. /*
  1861. * If the bio is flagged with BIO_CGROUP_ACCT it means this is a split
  1862. * bio and we would have already accounted for the size of the bio.
  1863. */
  1864. if (!bio_flagged(bio, BIO_CGROUP_ACCT)) {
  1865. bio_set_flag(bio, BIO_CGROUP_ACCT);
  1866. bis->cur.bytes[rwd] += bio->bi_iter.bi_size;
  1867. }
  1868. bis->cur.ios[rwd]++;
  1869. /*
  1870. * If the iostat_cpu isn't in a lockless list, put it into the
  1871. * list to indicate that a stat update is pending.
  1872. */
  1873. if (!READ_ONCE(bis->lqueued)) {
  1874. struct llist_head *lhead = this_cpu_ptr(blkcg->lhead);
  1875. llist_add(&bis->lnode, lhead);
  1876. WRITE_ONCE(bis->lqueued, true);
  1877. }
  1878. u64_stats_update_end_irqrestore(&bis->sync, flags);
  1879. cgroup_rstat_updated(blkcg->css.cgroup, cpu);
  1880. put_cpu();
  1881. }
  1882. bool blk_cgroup_congested(void)
  1883. {
  1884. struct blkcg *blkcg;
  1885. bool ret = false;
  1886. rcu_read_lock();
  1887. for (blkcg = css_to_blkcg(blkcg_css()); blkcg;
  1888. blkcg = blkcg_parent(blkcg)) {
  1889. if (atomic_read(&blkcg->congestion_count)) {
  1890. ret = true;
  1891. break;
  1892. }
  1893. }
  1894. rcu_read_unlock();
  1895. return ret;
  1896. }
  1897. module_param(blkcg_debug_stats, bool, 0644);
  1898. MODULE_PARM_DESC(blkcg_debug_stats, "True if you want debug stats, false if not");