blk-throttle.c 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Interface for controlling IO bandwidth on a request queue
  4. *
  5. * Copyright (C) 2010 Vivek Goyal <vgoyal@redhat.com>
  6. */
  7. #include <linux/module.h>
  8. #include <linux/slab.h>
  9. #include <linux/blkdev.h>
  10. #include <linux/bio.h>
  11. #include <linux/blktrace_api.h>
  12. #include <linux/blk-cgroup.h>
  13. #include "blk.h"
  14. /* Max dispatch from a group in 1 round */
  15. static int throtl_grp_quantum = 8;
  16. /* Total max dispatch from all groups in one round */
  17. static int throtl_quantum = 32;
  18. /* Throttling is performed over a slice and after that slice is renewed */
  19. #define DFL_THROTL_SLICE_HD (HZ / 10)
  20. #define DFL_THROTL_SLICE_SSD (HZ / 50)
  21. #define MAX_THROTL_SLICE (HZ)
  22. #define MAX_IDLE_TIME (5L * 1000 * 1000) /* 5 s */
  23. #define MIN_THROTL_BPS (320 * 1024)
  24. #define MIN_THROTL_IOPS (10)
  25. #define DFL_LATENCY_TARGET (-1L)
  26. #define DFL_IDLE_THRESHOLD (0)
  27. #define DFL_HD_BASELINE_LATENCY (4000L) /* 4ms */
  28. #define LATENCY_FILTERED_SSD (0)
  29. /*
  30. * For HD, very small latency comes from sequential IO. Such IO is helpless to
  31. * help determine if its IO is impacted by others, hence we ignore the IO
  32. */
  33. #define LATENCY_FILTERED_HD (1000L) /* 1ms */
  34. static struct blkcg_policy blkcg_policy_throtl;
  35. /* A workqueue to queue throttle related work */
  36. static struct workqueue_struct *kthrotld_workqueue;
  37. /*
  38. * To implement hierarchical throttling, throtl_grps form a tree and bios
  39. * are dispatched upwards level by level until they reach the top and get
  40. * issued. When dispatching bios from the children and local group at each
  41. * level, if the bios are dispatched into a single bio_list, there's a risk
  42. * of a local or child group which can queue many bios at once filling up
  43. * the list starving others.
  44. *
  45. * To avoid such starvation, dispatched bios are queued separately
  46. * according to where they came from. When they are again dispatched to
  47. * the parent, they're popped in round-robin order so that no single source
  48. * hogs the dispatch window.
  49. *
  50. * throtl_qnode is used to keep the queued bios separated by their sources.
  51. * Bios are queued to throtl_qnode which in turn is queued to
  52. * throtl_service_queue and then dispatched in round-robin order.
  53. *
  54. * It's also used to track the reference counts on blkg's. A qnode always
  55. * belongs to a throtl_grp and gets queued on itself or the parent, so
  56. * incrementing the reference of the associated throtl_grp when a qnode is
  57. * queued and decrementing when dequeued is enough to keep the whole blkg
  58. * tree pinned while bios are in flight.
  59. */
  60. struct throtl_qnode {
  61. struct list_head node; /* service_queue->queued[] */
  62. struct bio_list bios; /* queued bios */
  63. struct throtl_grp *tg; /* tg this qnode belongs to */
  64. };
  65. struct throtl_service_queue {
  66. struct throtl_service_queue *parent_sq; /* the parent service_queue */
  67. /*
  68. * Bios queued directly to this service_queue or dispatched from
  69. * children throtl_grp's.
  70. */
  71. struct list_head queued[2]; /* throtl_qnode [READ/WRITE] */
  72. unsigned int nr_queued[2]; /* number of queued bios */
  73. /*
  74. * RB tree of active children throtl_grp's, which are sorted by
  75. * their ->disptime.
  76. */
  77. struct rb_root_cached pending_tree; /* RB tree of active tgs */
  78. unsigned int nr_pending; /* # queued in the tree */
  79. unsigned long first_pending_disptime; /* disptime of the first tg */
  80. struct timer_list pending_timer; /* fires on first_pending_disptime */
  81. };
  82. enum tg_state_flags {
  83. THROTL_TG_PENDING = 1 << 0, /* on parent's pending tree */
  84. THROTL_TG_WAS_EMPTY = 1 << 1, /* bio_lists[] became non-empty */
  85. };
  86. #define rb_entry_tg(node) rb_entry((node), struct throtl_grp, rb_node)
  87. enum {
  88. LIMIT_LOW,
  89. LIMIT_MAX,
  90. LIMIT_CNT,
  91. };
  92. struct throtl_grp {
  93. /* must be the first member */
  94. struct blkg_policy_data pd;
  95. /* active throtl group service_queue member */
  96. struct rb_node rb_node;
  97. /* throtl_data this group belongs to */
  98. struct throtl_data *td;
  99. /* this group's service queue */
  100. struct throtl_service_queue service_queue;
  101. /*
  102. * qnode_on_self is used when bios are directly queued to this
  103. * throtl_grp so that local bios compete fairly with bios
  104. * dispatched from children. qnode_on_parent is used when bios are
  105. * dispatched from this throtl_grp into its parent and will compete
  106. * with the sibling qnode_on_parents and the parent's
  107. * qnode_on_self.
  108. */
  109. struct throtl_qnode qnode_on_self[2];
  110. struct throtl_qnode qnode_on_parent[2];
  111. /*
  112. * Dispatch time in jiffies. This is the estimated time when group
  113. * will unthrottle and is ready to dispatch more bio. It is used as
  114. * key to sort active groups in service tree.
  115. */
  116. unsigned long disptime;
  117. unsigned int flags;
  118. /* are there any throtl rules between this group and td? */
  119. bool has_rules[2];
  120. /* internally used bytes per second rate limits */
  121. uint64_t bps[2][LIMIT_CNT];
  122. /* user configured bps limits */
  123. uint64_t bps_conf[2][LIMIT_CNT];
  124. /* internally used IOPS limits */
  125. unsigned int iops[2][LIMIT_CNT];
  126. /* user configured IOPS limits */
  127. unsigned int iops_conf[2][LIMIT_CNT];
  128. /* Number of bytes disptached in current slice */
  129. uint64_t bytes_disp[2];
  130. /* Number of bio's dispatched in current slice */
  131. unsigned int io_disp[2];
  132. unsigned long last_low_overflow_time[2];
  133. uint64_t last_bytes_disp[2];
  134. unsigned int last_io_disp[2];
  135. unsigned long last_check_time;
  136. unsigned long latency_target; /* us */
  137. unsigned long latency_target_conf; /* us */
  138. /* When did we start a new slice */
  139. unsigned long slice_start[2];
  140. unsigned long slice_end[2];
  141. unsigned long last_finish_time; /* ns / 1024 */
  142. unsigned long checked_last_finish_time; /* ns / 1024 */
  143. unsigned long avg_idletime; /* ns / 1024 */
  144. unsigned long idletime_threshold; /* us */
  145. unsigned long idletime_threshold_conf; /* us */
  146. unsigned int bio_cnt; /* total bios */
  147. unsigned int bad_bio_cnt; /* bios exceeding latency threshold */
  148. unsigned long bio_cnt_reset_time;
  149. };
  150. /* We measure latency for request size from <= 4k to >= 1M */
  151. #define LATENCY_BUCKET_SIZE 9
  152. struct latency_bucket {
  153. unsigned long total_latency; /* ns / 1024 */
  154. int samples;
  155. };
  156. struct avg_latency_bucket {
  157. unsigned long latency; /* ns / 1024 */
  158. bool valid;
  159. };
  160. struct throtl_data
  161. {
  162. /* service tree for active throtl groups */
  163. struct throtl_service_queue service_queue;
  164. struct request_queue *queue;
  165. /* Total Number of queued bios on READ and WRITE lists */
  166. unsigned int nr_queued[2];
  167. unsigned int throtl_slice;
  168. /* Work for dispatching throttled bios */
  169. struct work_struct dispatch_work;
  170. unsigned int limit_index;
  171. bool limit_valid[LIMIT_CNT];
  172. unsigned long low_upgrade_time;
  173. unsigned long low_downgrade_time;
  174. unsigned int scale;
  175. struct latency_bucket tmp_buckets[2][LATENCY_BUCKET_SIZE];
  176. struct avg_latency_bucket avg_buckets[2][LATENCY_BUCKET_SIZE];
  177. struct latency_bucket __percpu *latency_buckets[2];
  178. unsigned long last_calculate_time;
  179. unsigned long filtered_latency;
  180. bool track_bio_latency;
  181. };
  182. static void throtl_pending_timer_fn(struct timer_list *t);
  183. static inline struct throtl_grp *pd_to_tg(struct blkg_policy_data *pd)
  184. {
  185. return pd ? container_of(pd, struct throtl_grp, pd) : NULL;
  186. }
  187. static inline struct throtl_grp *blkg_to_tg(struct blkcg_gq *blkg)
  188. {
  189. return pd_to_tg(blkg_to_pd(blkg, &blkcg_policy_throtl));
  190. }
  191. static inline struct blkcg_gq *tg_to_blkg(struct throtl_grp *tg)
  192. {
  193. return pd_to_blkg(&tg->pd);
  194. }
  195. /**
  196. * sq_to_tg - return the throl_grp the specified service queue belongs to
  197. * @sq: the throtl_service_queue of interest
  198. *
  199. * Return the throtl_grp @sq belongs to. If @sq is the top-level one
  200. * embedded in throtl_data, %NULL is returned.
  201. */
  202. static struct throtl_grp *sq_to_tg(struct throtl_service_queue *sq)
  203. {
  204. if (sq && sq->parent_sq)
  205. return container_of(sq, struct throtl_grp, service_queue);
  206. else
  207. return NULL;
  208. }
  209. /**
  210. * sq_to_td - return throtl_data the specified service queue belongs to
  211. * @sq: the throtl_service_queue of interest
  212. *
  213. * A service_queue can be embedded in either a throtl_grp or throtl_data.
  214. * Determine the associated throtl_data accordingly and return it.
  215. */
  216. static struct throtl_data *sq_to_td(struct throtl_service_queue *sq)
  217. {
  218. struct throtl_grp *tg = sq_to_tg(sq);
  219. if (tg)
  220. return tg->td;
  221. else
  222. return container_of(sq, struct throtl_data, service_queue);
  223. }
  224. /*
  225. * cgroup's limit in LIMIT_MAX is scaled if low limit is set. This scale is to
  226. * make the IO dispatch more smooth.
  227. * Scale up: linearly scale up according to lapsed time since upgrade. For
  228. * every throtl_slice, the limit scales up 1/2 .low limit till the
  229. * limit hits .max limit
  230. * Scale down: exponentially scale down if a cgroup doesn't hit its .low limit
  231. */
  232. static uint64_t throtl_adjusted_limit(uint64_t low, struct throtl_data *td)
  233. {
  234. /* arbitrary value to avoid too big scale */
  235. if (td->scale < 4096 && time_after_eq(jiffies,
  236. td->low_upgrade_time + td->scale * td->throtl_slice))
  237. td->scale = (jiffies - td->low_upgrade_time) / td->throtl_slice;
  238. return low + (low >> 1) * td->scale;
  239. }
  240. static uint64_t tg_bps_limit(struct throtl_grp *tg, int rw)
  241. {
  242. struct blkcg_gq *blkg = tg_to_blkg(tg);
  243. struct throtl_data *td;
  244. uint64_t ret;
  245. if (cgroup_subsys_on_dfl(io_cgrp_subsys) && !blkg->parent)
  246. return U64_MAX;
  247. td = tg->td;
  248. ret = tg->bps[rw][td->limit_index];
  249. if (ret == 0 && td->limit_index == LIMIT_LOW) {
  250. /* intermediate node or iops isn't 0 */
  251. if (!list_empty(&blkg->blkcg->css.children) ||
  252. tg->iops[rw][td->limit_index])
  253. return U64_MAX;
  254. else
  255. return MIN_THROTL_BPS;
  256. }
  257. if (td->limit_index == LIMIT_MAX && tg->bps[rw][LIMIT_LOW] &&
  258. tg->bps[rw][LIMIT_LOW] != tg->bps[rw][LIMIT_MAX]) {
  259. uint64_t adjusted;
  260. adjusted = throtl_adjusted_limit(tg->bps[rw][LIMIT_LOW], td);
  261. ret = min(tg->bps[rw][LIMIT_MAX], adjusted);
  262. }
  263. return ret;
  264. }
  265. static unsigned int tg_iops_limit(struct throtl_grp *tg, int rw)
  266. {
  267. struct blkcg_gq *blkg = tg_to_blkg(tg);
  268. struct throtl_data *td;
  269. unsigned int ret;
  270. if (cgroup_subsys_on_dfl(io_cgrp_subsys) && !blkg->parent)
  271. return UINT_MAX;
  272. td = tg->td;
  273. ret = tg->iops[rw][td->limit_index];
  274. if (ret == 0 && tg->td->limit_index == LIMIT_LOW) {
  275. /* intermediate node or bps isn't 0 */
  276. if (!list_empty(&blkg->blkcg->css.children) ||
  277. tg->bps[rw][td->limit_index])
  278. return UINT_MAX;
  279. else
  280. return MIN_THROTL_IOPS;
  281. }
  282. if (td->limit_index == LIMIT_MAX && tg->iops[rw][LIMIT_LOW] &&
  283. tg->iops[rw][LIMIT_LOW] != tg->iops[rw][LIMIT_MAX]) {
  284. uint64_t adjusted;
  285. adjusted = throtl_adjusted_limit(tg->iops[rw][LIMIT_LOW], td);
  286. if (adjusted > UINT_MAX)
  287. adjusted = UINT_MAX;
  288. ret = min_t(unsigned int, tg->iops[rw][LIMIT_MAX], adjusted);
  289. }
  290. return ret;
  291. }
  292. #define request_bucket_index(sectors) \
  293. clamp_t(int, order_base_2(sectors) - 3, 0, LATENCY_BUCKET_SIZE - 1)
  294. /**
  295. * throtl_log - log debug message via blktrace
  296. * @sq: the service_queue being reported
  297. * @fmt: printf format string
  298. * @args: printf args
  299. *
  300. * The messages are prefixed with "throtl BLKG_NAME" if @sq belongs to a
  301. * throtl_grp; otherwise, just "throtl".
  302. */
  303. #define throtl_log(sq, fmt, args...) do { \
  304. struct throtl_grp *__tg = sq_to_tg((sq)); \
  305. struct throtl_data *__td = sq_to_td((sq)); \
  306. \
  307. (void)__td; \
  308. if (likely(!blk_trace_note_message_enabled(__td->queue))) \
  309. break; \
  310. if ((__tg)) { \
  311. blk_add_cgroup_trace_msg(__td->queue, \
  312. tg_to_blkg(__tg)->blkcg, "throtl " fmt, ##args);\
  313. } else { \
  314. blk_add_trace_msg(__td->queue, "throtl " fmt, ##args); \
  315. } \
  316. } while (0)
  317. static inline unsigned int throtl_bio_data_size(struct bio *bio)
  318. {
  319. /* assume it's one sector */
  320. if (unlikely(bio_op(bio) == REQ_OP_DISCARD))
  321. return 512;
  322. return bio->bi_iter.bi_size;
  323. }
  324. static void throtl_qnode_init(struct throtl_qnode *qn, struct throtl_grp *tg)
  325. {
  326. INIT_LIST_HEAD(&qn->node);
  327. bio_list_init(&qn->bios);
  328. qn->tg = tg;
  329. }
  330. /**
  331. * throtl_qnode_add_bio - add a bio to a throtl_qnode and activate it
  332. * @bio: bio being added
  333. * @qn: qnode to add bio to
  334. * @queued: the service_queue->queued[] list @qn belongs to
  335. *
  336. * Add @bio to @qn and put @qn on @queued if it's not already on.
  337. * @qn->tg's reference count is bumped when @qn is activated. See the
  338. * comment on top of throtl_qnode definition for details.
  339. */
  340. static void throtl_qnode_add_bio(struct bio *bio, struct throtl_qnode *qn,
  341. struct list_head *queued)
  342. {
  343. bio_list_add(&qn->bios, bio);
  344. if (list_empty(&qn->node)) {
  345. list_add_tail(&qn->node, queued);
  346. blkg_get(tg_to_blkg(qn->tg));
  347. }
  348. }
  349. /**
  350. * throtl_peek_queued - peek the first bio on a qnode list
  351. * @queued: the qnode list to peek
  352. */
  353. static struct bio *throtl_peek_queued(struct list_head *queued)
  354. {
  355. struct throtl_qnode *qn = list_first_entry(queued, struct throtl_qnode, node);
  356. struct bio *bio;
  357. if (list_empty(queued))
  358. return NULL;
  359. bio = bio_list_peek(&qn->bios);
  360. WARN_ON_ONCE(!bio);
  361. return bio;
  362. }
  363. /**
  364. * throtl_pop_queued - pop the first bio form a qnode list
  365. * @queued: the qnode list to pop a bio from
  366. * @tg_to_put: optional out argument for throtl_grp to put
  367. *
  368. * Pop the first bio from the qnode list @queued. After popping, the first
  369. * qnode is removed from @queued if empty or moved to the end of @queued so
  370. * that the popping order is round-robin.
  371. *
  372. * When the first qnode is removed, its associated throtl_grp should be put
  373. * too. If @tg_to_put is NULL, this function automatically puts it;
  374. * otherwise, *@tg_to_put is set to the throtl_grp to put and the caller is
  375. * responsible for putting it.
  376. */
  377. static struct bio *throtl_pop_queued(struct list_head *queued,
  378. struct throtl_grp **tg_to_put)
  379. {
  380. struct throtl_qnode *qn = list_first_entry(queued, struct throtl_qnode, node);
  381. struct bio *bio;
  382. if (list_empty(queued))
  383. return NULL;
  384. bio = bio_list_pop(&qn->bios);
  385. WARN_ON_ONCE(!bio);
  386. if (bio_list_empty(&qn->bios)) {
  387. list_del_init(&qn->node);
  388. if (tg_to_put)
  389. *tg_to_put = qn->tg;
  390. else
  391. blkg_put(tg_to_blkg(qn->tg));
  392. } else {
  393. list_move_tail(&qn->node, queued);
  394. }
  395. return bio;
  396. }
  397. /* init a service_queue, assumes the caller zeroed it */
  398. static void throtl_service_queue_init(struct throtl_service_queue *sq)
  399. {
  400. INIT_LIST_HEAD(&sq->queued[0]);
  401. INIT_LIST_HEAD(&sq->queued[1]);
  402. sq->pending_tree = RB_ROOT_CACHED;
  403. timer_setup(&sq->pending_timer, throtl_pending_timer_fn, 0);
  404. }
  405. static struct blkg_policy_data *throtl_pd_alloc(gfp_t gfp, int node)
  406. {
  407. struct throtl_grp *tg;
  408. int rw;
  409. tg = kzalloc_node(sizeof(*tg), gfp, node);
  410. if (!tg)
  411. return NULL;
  412. throtl_service_queue_init(&tg->service_queue);
  413. for (rw = READ; rw <= WRITE; rw++) {
  414. throtl_qnode_init(&tg->qnode_on_self[rw], tg);
  415. throtl_qnode_init(&tg->qnode_on_parent[rw], tg);
  416. }
  417. RB_CLEAR_NODE(&tg->rb_node);
  418. tg->bps[READ][LIMIT_MAX] = U64_MAX;
  419. tg->bps[WRITE][LIMIT_MAX] = U64_MAX;
  420. tg->iops[READ][LIMIT_MAX] = UINT_MAX;
  421. tg->iops[WRITE][LIMIT_MAX] = UINT_MAX;
  422. tg->bps_conf[READ][LIMIT_MAX] = U64_MAX;
  423. tg->bps_conf[WRITE][LIMIT_MAX] = U64_MAX;
  424. tg->iops_conf[READ][LIMIT_MAX] = UINT_MAX;
  425. tg->iops_conf[WRITE][LIMIT_MAX] = UINT_MAX;
  426. /* LIMIT_LOW will have default value 0 */
  427. tg->latency_target = DFL_LATENCY_TARGET;
  428. tg->latency_target_conf = DFL_LATENCY_TARGET;
  429. tg->idletime_threshold = DFL_IDLE_THRESHOLD;
  430. tg->idletime_threshold_conf = DFL_IDLE_THRESHOLD;
  431. return &tg->pd;
  432. }
  433. static void throtl_pd_init(struct blkg_policy_data *pd)
  434. {
  435. struct throtl_grp *tg = pd_to_tg(pd);
  436. struct blkcg_gq *blkg = tg_to_blkg(tg);
  437. struct throtl_data *td = blkg->q->td;
  438. struct throtl_service_queue *sq = &tg->service_queue;
  439. /*
  440. * If on the default hierarchy, we switch to properly hierarchical
  441. * behavior where limits on a given throtl_grp are applied to the
  442. * whole subtree rather than just the group itself. e.g. If 16M
  443. * read_bps limit is set on the root group, the whole system can't
  444. * exceed 16M for the device.
  445. *
  446. * If not on the default hierarchy, the broken flat hierarchy
  447. * behavior is retained where all throtl_grps are treated as if
  448. * they're all separate root groups right below throtl_data.
  449. * Limits of a group don't interact with limits of other groups
  450. * regardless of the position of the group in the hierarchy.
  451. */
  452. sq->parent_sq = &td->service_queue;
  453. if (cgroup_subsys_on_dfl(io_cgrp_subsys) && blkg->parent)
  454. sq->parent_sq = &blkg_to_tg(blkg->parent)->service_queue;
  455. tg->td = td;
  456. }
  457. /*
  458. * Set has_rules[] if @tg or any of its parents have limits configured.
  459. * This doesn't require walking up to the top of the hierarchy as the
  460. * parent's has_rules[] is guaranteed to be correct.
  461. */
  462. static void tg_update_has_rules(struct throtl_grp *tg)
  463. {
  464. struct throtl_grp *parent_tg = sq_to_tg(tg->service_queue.parent_sq);
  465. struct throtl_data *td = tg->td;
  466. int rw;
  467. for (rw = READ; rw <= WRITE; rw++)
  468. tg->has_rules[rw] = (parent_tg && parent_tg->has_rules[rw]) ||
  469. (td->limit_valid[td->limit_index] &&
  470. (tg_bps_limit(tg, rw) != U64_MAX ||
  471. tg_iops_limit(tg, rw) != UINT_MAX));
  472. }
  473. static void throtl_pd_online(struct blkg_policy_data *pd)
  474. {
  475. struct throtl_grp *tg = pd_to_tg(pd);
  476. /*
  477. * We don't want new groups to escape the limits of its ancestors.
  478. * Update has_rules[] after a new group is brought online.
  479. */
  480. tg_update_has_rules(tg);
  481. }
  482. static void blk_throtl_update_limit_valid(struct throtl_data *td)
  483. {
  484. struct cgroup_subsys_state *pos_css;
  485. struct blkcg_gq *blkg;
  486. bool low_valid = false;
  487. rcu_read_lock();
  488. blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg) {
  489. struct throtl_grp *tg = blkg_to_tg(blkg);
  490. if (tg->bps[READ][LIMIT_LOW] || tg->bps[WRITE][LIMIT_LOW] ||
  491. tg->iops[READ][LIMIT_LOW] || tg->iops[WRITE][LIMIT_LOW]) {
  492. low_valid = true;
  493. break;
  494. }
  495. }
  496. rcu_read_unlock();
  497. td->limit_valid[LIMIT_LOW] = low_valid;
  498. }
  499. static void throtl_upgrade_state(struct throtl_data *td);
  500. static void throtl_pd_offline(struct blkg_policy_data *pd)
  501. {
  502. struct throtl_grp *tg = pd_to_tg(pd);
  503. tg->bps[READ][LIMIT_LOW] = 0;
  504. tg->bps[WRITE][LIMIT_LOW] = 0;
  505. tg->iops[READ][LIMIT_LOW] = 0;
  506. tg->iops[WRITE][LIMIT_LOW] = 0;
  507. blk_throtl_update_limit_valid(tg->td);
  508. if (!tg->td->limit_valid[tg->td->limit_index])
  509. throtl_upgrade_state(tg->td);
  510. }
  511. static void throtl_pd_free(struct blkg_policy_data *pd)
  512. {
  513. struct throtl_grp *tg = pd_to_tg(pd);
  514. del_timer_sync(&tg->service_queue.pending_timer);
  515. kfree(tg);
  516. }
  517. static struct throtl_grp *
  518. throtl_rb_first(struct throtl_service_queue *parent_sq)
  519. {
  520. struct rb_node *n;
  521. /* Service tree is empty */
  522. if (!parent_sq->nr_pending)
  523. return NULL;
  524. n = rb_first_cached(&parent_sq->pending_tree);
  525. WARN_ON_ONCE(!n);
  526. if (!n)
  527. return NULL;
  528. return rb_entry_tg(n);
  529. }
  530. static void throtl_rb_erase(struct rb_node *n,
  531. struct throtl_service_queue *parent_sq)
  532. {
  533. rb_erase_cached(n, &parent_sq->pending_tree);
  534. RB_CLEAR_NODE(n);
  535. --parent_sq->nr_pending;
  536. }
  537. static void update_min_dispatch_time(struct throtl_service_queue *parent_sq)
  538. {
  539. struct throtl_grp *tg;
  540. tg = throtl_rb_first(parent_sq);
  541. if (!tg)
  542. return;
  543. parent_sq->first_pending_disptime = tg->disptime;
  544. }
  545. static void tg_service_queue_add(struct throtl_grp *tg)
  546. {
  547. struct throtl_service_queue *parent_sq = tg->service_queue.parent_sq;
  548. struct rb_node **node = &parent_sq->pending_tree.rb_root.rb_node;
  549. struct rb_node *parent = NULL;
  550. struct throtl_grp *__tg;
  551. unsigned long key = tg->disptime;
  552. bool leftmost = true;
  553. while (*node != NULL) {
  554. parent = *node;
  555. __tg = rb_entry_tg(parent);
  556. if (time_before(key, __tg->disptime))
  557. node = &parent->rb_left;
  558. else {
  559. node = &parent->rb_right;
  560. leftmost = false;
  561. }
  562. }
  563. rb_link_node(&tg->rb_node, parent, node);
  564. rb_insert_color_cached(&tg->rb_node, &parent_sq->pending_tree,
  565. leftmost);
  566. }
  567. static void __throtl_enqueue_tg(struct throtl_grp *tg)
  568. {
  569. tg_service_queue_add(tg);
  570. tg->flags |= THROTL_TG_PENDING;
  571. tg->service_queue.parent_sq->nr_pending++;
  572. }
  573. static void throtl_enqueue_tg(struct throtl_grp *tg)
  574. {
  575. if (!(tg->flags & THROTL_TG_PENDING))
  576. __throtl_enqueue_tg(tg);
  577. }
  578. static void __throtl_dequeue_tg(struct throtl_grp *tg)
  579. {
  580. throtl_rb_erase(&tg->rb_node, tg->service_queue.parent_sq);
  581. tg->flags &= ~THROTL_TG_PENDING;
  582. }
  583. static void throtl_dequeue_tg(struct throtl_grp *tg)
  584. {
  585. if (tg->flags & THROTL_TG_PENDING)
  586. __throtl_dequeue_tg(tg);
  587. }
  588. /* Call with queue lock held */
  589. static void throtl_schedule_pending_timer(struct throtl_service_queue *sq,
  590. unsigned long expires)
  591. {
  592. unsigned long max_expire = jiffies + 8 * sq_to_td(sq)->throtl_slice;
  593. /*
  594. * Since we are adjusting the throttle limit dynamically, the sleep
  595. * time calculated according to previous limit might be invalid. It's
  596. * possible the cgroup sleep time is very long and no other cgroups
  597. * have IO running so notify the limit changes. Make sure the cgroup
  598. * doesn't sleep too long to avoid the missed notification.
  599. */
  600. if (time_after(expires, max_expire))
  601. expires = max_expire;
  602. mod_timer(&sq->pending_timer, expires);
  603. throtl_log(sq, "schedule timer. delay=%lu jiffies=%lu",
  604. expires - jiffies, jiffies);
  605. }
  606. /**
  607. * throtl_schedule_next_dispatch - schedule the next dispatch cycle
  608. * @sq: the service_queue to schedule dispatch for
  609. * @force: force scheduling
  610. *
  611. * Arm @sq->pending_timer so that the next dispatch cycle starts on the
  612. * dispatch time of the first pending child. Returns %true if either timer
  613. * is armed or there's no pending child left. %false if the current
  614. * dispatch window is still open and the caller should continue
  615. * dispatching.
  616. *
  617. * If @force is %true, the dispatch timer is always scheduled and this
  618. * function is guaranteed to return %true. This is to be used when the
  619. * caller can't dispatch itself and needs to invoke pending_timer
  620. * unconditionally. Note that forced scheduling is likely to induce short
  621. * delay before dispatch starts even if @sq->first_pending_disptime is not
  622. * in the future and thus shouldn't be used in hot paths.
  623. */
  624. static bool throtl_schedule_next_dispatch(struct throtl_service_queue *sq,
  625. bool force)
  626. {
  627. /* any pending children left? */
  628. if (!sq->nr_pending)
  629. return true;
  630. update_min_dispatch_time(sq);
  631. /* is the next dispatch time in the future? */
  632. if (force || time_after(sq->first_pending_disptime, jiffies)) {
  633. throtl_schedule_pending_timer(sq, sq->first_pending_disptime);
  634. return true;
  635. }
  636. /* tell the caller to continue dispatching */
  637. return false;
  638. }
  639. static inline void throtl_start_new_slice_with_credit(struct throtl_grp *tg,
  640. bool rw, unsigned long start)
  641. {
  642. tg->bytes_disp[rw] = 0;
  643. tg->io_disp[rw] = 0;
  644. /*
  645. * Previous slice has expired. We must have trimmed it after last
  646. * bio dispatch. That means since start of last slice, we never used
  647. * that bandwidth. Do try to make use of that bandwidth while giving
  648. * credit.
  649. */
  650. if (time_after_eq(start, tg->slice_start[rw]))
  651. tg->slice_start[rw] = start;
  652. tg->slice_end[rw] = jiffies + tg->td->throtl_slice;
  653. throtl_log(&tg->service_queue,
  654. "[%c] new slice with credit start=%lu end=%lu jiffies=%lu",
  655. rw == READ ? 'R' : 'W', tg->slice_start[rw],
  656. tg->slice_end[rw], jiffies);
  657. }
  658. static inline void throtl_start_new_slice(struct throtl_grp *tg, bool rw)
  659. {
  660. tg->bytes_disp[rw] = 0;
  661. tg->io_disp[rw] = 0;
  662. tg->slice_start[rw] = jiffies;
  663. tg->slice_end[rw] = jiffies + tg->td->throtl_slice;
  664. throtl_log(&tg->service_queue,
  665. "[%c] new slice start=%lu end=%lu jiffies=%lu",
  666. rw == READ ? 'R' : 'W', tg->slice_start[rw],
  667. tg->slice_end[rw], jiffies);
  668. }
  669. static inline void throtl_set_slice_end(struct throtl_grp *tg, bool rw,
  670. unsigned long jiffy_end)
  671. {
  672. tg->slice_end[rw] = roundup(jiffy_end, tg->td->throtl_slice);
  673. }
  674. static inline void throtl_extend_slice(struct throtl_grp *tg, bool rw,
  675. unsigned long jiffy_end)
  676. {
  677. tg->slice_end[rw] = roundup(jiffy_end, tg->td->throtl_slice);
  678. throtl_log(&tg->service_queue,
  679. "[%c] extend slice start=%lu end=%lu jiffies=%lu",
  680. rw == READ ? 'R' : 'W', tg->slice_start[rw],
  681. tg->slice_end[rw], jiffies);
  682. }
  683. /* Determine if previously allocated or extended slice is complete or not */
  684. static bool throtl_slice_used(struct throtl_grp *tg, bool rw)
  685. {
  686. if (time_in_range(jiffies, tg->slice_start[rw], tg->slice_end[rw]))
  687. return false;
  688. return true;
  689. }
  690. /* Trim the used slices and adjust slice start accordingly */
  691. static inline void throtl_trim_slice(struct throtl_grp *tg, bool rw)
  692. {
  693. unsigned long nr_slices, time_elapsed, io_trim;
  694. u64 bytes_trim, tmp;
  695. BUG_ON(time_before(tg->slice_end[rw], tg->slice_start[rw]));
  696. /*
  697. * If bps are unlimited (-1), then time slice don't get
  698. * renewed. Don't try to trim the slice if slice is used. A new
  699. * slice will start when appropriate.
  700. */
  701. if (throtl_slice_used(tg, rw))
  702. return;
  703. /*
  704. * A bio has been dispatched. Also adjust slice_end. It might happen
  705. * that initially cgroup limit was very low resulting in high
  706. * slice_end, but later limit was bumped up and bio was dispached
  707. * sooner, then we need to reduce slice_end. A high bogus slice_end
  708. * is bad because it does not allow new slice to start.
  709. */
  710. throtl_set_slice_end(tg, rw, jiffies + tg->td->throtl_slice);
  711. time_elapsed = jiffies - tg->slice_start[rw];
  712. nr_slices = time_elapsed / tg->td->throtl_slice;
  713. if (!nr_slices)
  714. return;
  715. tmp = tg_bps_limit(tg, rw) * tg->td->throtl_slice * nr_slices;
  716. do_div(tmp, HZ);
  717. bytes_trim = tmp;
  718. io_trim = (tg_iops_limit(tg, rw) * tg->td->throtl_slice * nr_slices) /
  719. HZ;
  720. if (!bytes_trim && !io_trim)
  721. return;
  722. if (tg->bytes_disp[rw] >= bytes_trim)
  723. tg->bytes_disp[rw] -= bytes_trim;
  724. else
  725. tg->bytes_disp[rw] = 0;
  726. if (tg->io_disp[rw] >= io_trim)
  727. tg->io_disp[rw] -= io_trim;
  728. else
  729. tg->io_disp[rw] = 0;
  730. tg->slice_start[rw] += nr_slices * tg->td->throtl_slice;
  731. throtl_log(&tg->service_queue,
  732. "[%c] trim slice nr=%lu bytes=%llu io=%lu start=%lu end=%lu jiffies=%lu",
  733. rw == READ ? 'R' : 'W', nr_slices, bytes_trim, io_trim,
  734. tg->slice_start[rw], tg->slice_end[rw], jiffies);
  735. }
  736. static bool tg_with_in_iops_limit(struct throtl_grp *tg, struct bio *bio,
  737. unsigned long *wait)
  738. {
  739. bool rw = bio_data_dir(bio);
  740. unsigned int io_allowed;
  741. unsigned long jiffy_elapsed, jiffy_wait, jiffy_elapsed_rnd;
  742. u64 tmp;
  743. jiffy_elapsed = jiffy_elapsed_rnd = jiffies - tg->slice_start[rw];
  744. /* Slice has just started. Consider one slice interval */
  745. if (!jiffy_elapsed)
  746. jiffy_elapsed_rnd = tg->td->throtl_slice;
  747. jiffy_elapsed_rnd = roundup(jiffy_elapsed_rnd, tg->td->throtl_slice);
  748. /*
  749. * jiffy_elapsed_rnd should not be a big value as minimum iops can be
  750. * 1 then at max jiffy elapsed should be equivalent of 1 second as we
  751. * will allow dispatch after 1 second and after that slice should
  752. * have been trimmed.
  753. */
  754. tmp = (u64)tg_iops_limit(tg, rw) * jiffy_elapsed_rnd;
  755. do_div(tmp, HZ);
  756. if (tmp > UINT_MAX)
  757. io_allowed = UINT_MAX;
  758. else
  759. io_allowed = tmp;
  760. if (tg->io_disp[rw] + 1 <= io_allowed) {
  761. if (wait)
  762. *wait = 0;
  763. return true;
  764. }
  765. /* Calc approx time to dispatch */
  766. jiffy_wait = jiffy_elapsed_rnd - jiffy_elapsed;
  767. if (wait)
  768. *wait = jiffy_wait;
  769. return false;
  770. }
  771. static bool tg_with_in_bps_limit(struct throtl_grp *tg, struct bio *bio,
  772. unsigned long *wait)
  773. {
  774. bool rw = bio_data_dir(bio);
  775. u64 bytes_allowed, extra_bytes, tmp;
  776. unsigned long jiffy_elapsed, jiffy_wait, jiffy_elapsed_rnd;
  777. unsigned int bio_size = throtl_bio_data_size(bio);
  778. jiffy_elapsed = jiffy_elapsed_rnd = jiffies - tg->slice_start[rw];
  779. /* Slice has just started. Consider one slice interval */
  780. if (!jiffy_elapsed)
  781. jiffy_elapsed_rnd = tg->td->throtl_slice;
  782. jiffy_elapsed_rnd = roundup(jiffy_elapsed_rnd, tg->td->throtl_slice);
  783. tmp = tg_bps_limit(tg, rw) * jiffy_elapsed_rnd;
  784. do_div(tmp, HZ);
  785. bytes_allowed = tmp;
  786. if (tg->bytes_disp[rw] + bio_size <= bytes_allowed) {
  787. if (wait)
  788. *wait = 0;
  789. return true;
  790. }
  791. /* Calc approx time to dispatch */
  792. extra_bytes = tg->bytes_disp[rw] + bio_size - bytes_allowed;
  793. jiffy_wait = div64_u64(extra_bytes * HZ, tg_bps_limit(tg, rw));
  794. if (!jiffy_wait)
  795. jiffy_wait = 1;
  796. /*
  797. * This wait time is without taking into consideration the rounding
  798. * up we did. Add that time also.
  799. */
  800. jiffy_wait = jiffy_wait + (jiffy_elapsed_rnd - jiffy_elapsed);
  801. if (wait)
  802. *wait = jiffy_wait;
  803. return false;
  804. }
  805. /*
  806. * Returns whether one can dispatch a bio or not. Also returns approx number
  807. * of jiffies to wait before this bio is with-in IO rate and can be dispatched
  808. */
  809. static bool tg_may_dispatch(struct throtl_grp *tg, struct bio *bio,
  810. unsigned long *wait)
  811. {
  812. bool rw = bio_data_dir(bio);
  813. unsigned long bps_wait = 0, iops_wait = 0, max_wait = 0;
  814. /*
  815. * Currently whole state machine of group depends on first bio
  816. * queued in the group bio list. So one should not be calling
  817. * this function with a different bio if there are other bios
  818. * queued.
  819. */
  820. BUG_ON(tg->service_queue.nr_queued[rw] &&
  821. bio != throtl_peek_queued(&tg->service_queue.queued[rw]));
  822. /* If tg->bps = -1, then BW is unlimited */
  823. if (tg_bps_limit(tg, rw) == U64_MAX &&
  824. tg_iops_limit(tg, rw) == UINT_MAX) {
  825. if (wait)
  826. *wait = 0;
  827. return true;
  828. }
  829. /*
  830. * If previous slice expired, start a new one otherwise renew/extend
  831. * existing slice to make sure it is at least throtl_slice interval
  832. * long since now. New slice is started only for empty throttle group.
  833. * If there is queued bio, that means there should be an active
  834. * slice and it should be extended instead.
  835. */
  836. if (throtl_slice_used(tg, rw) && !(tg->service_queue.nr_queued[rw]))
  837. throtl_start_new_slice(tg, rw);
  838. else {
  839. if (time_before(tg->slice_end[rw],
  840. jiffies + tg->td->throtl_slice))
  841. throtl_extend_slice(tg, rw,
  842. jiffies + tg->td->throtl_slice);
  843. }
  844. if (tg_with_in_bps_limit(tg, bio, &bps_wait) &&
  845. tg_with_in_iops_limit(tg, bio, &iops_wait)) {
  846. if (wait)
  847. *wait = 0;
  848. return true;
  849. }
  850. max_wait = max(bps_wait, iops_wait);
  851. if (wait)
  852. *wait = max_wait;
  853. if (time_before(tg->slice_end[rw], jiffies + max_wait))
  854. throtl_extend_slice(tg, rw, jiffies + max_wait);
  855. return false;
  856. }
  857. static void throtl_charge_bio(struct throtl_grp *tg, struct bio *bio)
  858. {
  859. bool rw = bio_data_dir(bio);
  860. unsigned int bio_size = throtl_bio_data_size(bio);
  861. /* Charge the bio to the group */
  862. tg->bytes_disp[rw] += bio_size;
  863. tg->io_disp[rw]++;
  864. tg->last_bytes_disp[rw] += bio_size;
  865. tg->last_io_disp[rw]++;
  866. /*
  867. * BIO_THROTTLED is used to prevent the same bio to be throttled
  868. * more than once as a throttled bio will go through blk-throtl the
  869. * second time when it eventually gets issued. Set it when a bio
  870. * is being charged to a tg.
  871. */
  872. if (!bio_flagged(bio, BIO_THROTTLED))
  873. bio_set_flag(bio, BIO_THROTTLED);
  874. }
  875. /**
  876. * throtl_add_bio_tg - add a bio to the specified throtl_grp
  877. * @bio: bio to add
  878. * @qn: qnode to use
  879. * @tg: the target throtl_grp
  880. *
  881. * Add @bio to @tg's service_queue using @qn. If @qn is not specified,
  882. * tg->qnode_on_self[] is used.
  883. */
  884. static void throtl_add_bio_tg(struct bio *bio, struct throtl_qnode *qn,
  885. struct throtl_grp *tg)
  886. {
  887. struct throtl_service_queue *sq = &tg->service_queue;
  888. bool rw = bio_data_dir(bio);
  889. if (!qn)
  890. qn = &tg->qnode_on_self[rw];
  891. /*
  892. * If @tg doesn't currently have any bios queued in the same
  893. * direction, queueing @bio can change when @tg should be
  894. * dispatched. Mark that @tg was empty. This is automatically
  895. * cleaered on the next tg_update_disptime().
  896. */
  897. if (!sq->nr_queued[rw])
  898. tg->flags |= THROTL_TG_WAS_EMPTY;
  899. throtl_qnode_add_bio(bio, qn, &sq->queued[rw]);
  900. sq->nr_queued[rw]++;
  901. throtl_enqueue_tg(tg);
  902. }
  903. static void tg_update_disptime(struct throtl_grp *tg)
  904. {
  905. struct throtl_service_queue *sq = &tg->service_queue;
  906. unsigned long read_wait = -1, write_wait = -1, min_wait = -1, disptime;
  907. struct bio *bio;
  908. bio = throtl_peek_queued(&sq->queued[READ]);
  909. if (bio)
  910. tg_may_dispatch(tg, bio, &read_wait);
  911. bio = throtl_peek_queued(&sq->queued[WRITE]);
  912. if (bio)
  913. tg_may_dispatch(tg, bio, &write_wait);
  914. min_wait = min(read_wait, write_wait);
  915. disptime = jiffies + min_wait;
  916. /* Update dispatch time */
  917. throtl_dequeue_tg(tg);
  918. tg->disptime = disptime;
  919. throtl_enqueue_tg(tg);
  920. /* see throtl_add_bio_tg() */
  921. tg->flags &= ~THROTL_TG_WAS_EMPTY;
  922. }
  923. static void start_parent_slice_with_credit(struct throtl_grp *child_tg,
  924. struct throtl_grp *parent_tg, bool rw)
  925. {
  926. if (throtl_slice_used(parent_tg, rw)) {
  927. throtl_start_new_slice_with_credit(parent_tg, rw,
  928. child_tg->slice_start[rw]);
  929. }
  930. }
  931. static void tg_dispatch_one_bio(struct throtl_grp *tg, bool rw)
  932. {
  933. struct throtl_service_queue *sq = &tg->service_queue;
  934. struct throtl_service_queue *parent_sq = sq->parent_sq;
  935. struct throtl_grp *parent_tg = sq_to_tg(parent_sq);
  936. struct throtl_grp *tg_to_put = NULL;
  937. struct bio *bio;
  938. /*
  939. * @bio is being transferred from @tg to @parent_sq. Popping a bio
  940. * from @tg may put its reference and @parent_sq might end up
  941. * getting released prematurely. Remember the tg to put and put it
  942. * after @bio is transferred to @parent_sq.
  943. */
  944. bio = throtl_pop_queued(&sq->queued[rw], &tg_to_put);
  945. sq->nr_queued[rw]--;
  946. throtl_charge_bio(tg, bio);
  947. /*
  948. * If our parent is another tg, we just need to transfer @bio to
  949. * the parent using throtl_add_bio_tg(). If our parent is
  950. * @td->service_queue, @bio is ready to be issued. Put it on its
  951. * bio_lists[] and decrease total number queued. The caller is
  952. * responsible for issuing these bios.
  953. */
  954. if (parent_tg) {
  955. throtl_add_bio_tg(bio, &tg->qnode_on_parent[rw], parent_tg);
  956. start_parent_slice_with_credit(tg, parent_tg, rw);
  957. } else {
  958. throtl_qnode_add_bio(bio, &tg->qnode_on_parent[rw],
  959. &parent_sq->queued[rw]);
  960. BUG_ON(tg->td->nr_queued[rw] <= 0);
  961. tg->td->nr_queued[rw]--;
  962. }
  963. throtl_trim_slice(tg, rw);
  964. if (tg_to_put)
  965. blkg_put(tg_to_blkg(tg_to_put));
  966. }
  967. static int throtl_dispatch_tg(struct throtl_grp *tg)
  968. {
  969. struct throtl_service_queue *sq = &tg->service_queue;
  970. unsigned int nr_reads = 0, nr_writes = 0;
  971. unsigned int max_nr_reads = throtl_grp_quantum*3/4;
  972. unsigned int max_nr_writes = throtl_grp_quantum - max_nr_reads;
  973. struct bio *bio;
  974. /* Try to dispatch 75% READS and 25% WRITES */
  975. while ((bio = throtl_peek_queued(&sq->queued[READ])) &&
  976. tg_may_dispatch(tg, bio, NULL)) {
  977. tg_dispatch_one_bio(tg, bio_data_dir(bio));
  978. nr_reads++;
  979. if (nr_reads >= max_nr_reads)
  980. break;
  981. }
  982. while ((bio = throtl_peek_queued(&sq->queued[WRITE])) &&
  983. tg_may_dispatch(tg, bio, NULL)) {
  984. tg_dispatch_one_bio(tg, bio_data_dir(bio));
  985. nr_writes++;
  986. if (nr_writes >= max_nr_writes)
  987. break;
  988. }
  989. return nr_reads + nr_writes;
  990. }
  991. static int throtl_select_dispatch(struct throtl_service_queue *parent_sq)
  992. {
  993. unsigned int nr_disp = 0;
  994. while (1) {
  995. struct throtl_grp *tg = throtl_rb_first(parent_sq);
  996. struct throtl_service_queue *sq;
  997. if (!tg)
  998. break;
  999. if (time_before(jiffies, tg->disptime))
  1000. break;
  1001. throtl_dequeue_tg(tg);
  1002. nr_disp += throtl_dispatch_tg(tg);
  1003. sq = &tg->service_queue;
  1004. if (sq->nr_queued[0] || sq->nr_queued[1])
  1005. tg_update_disptime(tg);
  1006. if (nr_disp >= throtl_quantum)
  1007. break;
  1008. }
  1009. return nr_disp;
  1010. }
  1011. static bool throtl_can_upgrade(struct throtl_data *td,
  1012. struct throtl_grp *this_tg);
  1013. /**
  1014. * throtl_pending_timer_fn - timer function for service_queue->pending_timer
  1015. * @arg: the throtl_service_queue being serviced
  1016. *
  1017. * This timer is armed when a child throtl_grp with active bio's become
  1018. * pending and queued on the service_queue's pending_tree and expires when
  1019. * the first child throtl_grp should be dispatched. This function
  1020. * dispatches bio's from the children throtl_grps to the parent
  1021. * service_queue.
  1022. *
  1023. * If the parent's parent is another throtl_grp, dispatching is propagated
  1024. * by either arming its pending_timer or repeating dispatch directly. If
  1025. * the top-level service_tree is reached, throtl_data->dispatch_work is
  1026. * kicked so that the ready bio's are issued.
  1027. */
  1028. static void throtl_pending_timer_fn(struct timer_list *t)
  1029. {
  1030. struct throtl_service_queue *sq = from_timer(sq, t, pending_timer);
  1031. struct throtl_grp *tg = sq_to_tg(sq);
  1032. struct throtl_data *td = sq_to_td(sq);
  1033. struct request_queue *q = td->queue;
  1034. struct throtl_service_queue *parent_sq;
  1035. bool dispatched;
  1036. int ret;
  1037. spin_lock_irq(q->queue_lock);
  1038. if (throtl_can_upgrade(td, NULL))
  1039. throtl_upgrade_state(td);
  1040. again:
  1041. parent_sq = sq->parent_sq;
  1042. dispatched = false;
  1043. while (true) {
  1044. throtl_log(sq, "dispatch nr_queued=%u read=%u write=%u",
  1045. sq->nr_queued[READ] + sq->nr_queued[WRITE],
  1046. sq->nr_queued[READ], sq->nr_queued[WRITE]);
  1047. ret = throtl_select_dispatch(sq);
  1048. if (ret) {
  1049. throtl_log(sq, "bios disp=%u", ret);
  1050. dispatched = true;
  1051. }
  1052. if (throtl_schedule_next_dispatch(sq, false))
  1053. break;
  1054. /* this dispatch windows is still open, relax and repeat */
  1055. spin_unlock_irq(q->queue_lock);
  1056. cpu_relax();
  1057. spin_lock_irq(q->queue_lock);
  1058. }
  1059. if (!dispatched)
  1060. goto out_unlock;
  1061. if (parent_sq) {
  1062. /* @parent_sq is another throl_grp, propagate dispatch */
  1063. if (tg->flags & THROTL_TG_WAS_EMPTY) {
  1064. tg_update_disptime(tg);
  1065. if (!throtl_schedule_next_dispatch(parent_sq, false)) {
  1066. /* window is already open, repeat dispatching */
  1067. sq = parent_sq;
  1068. tg = sq_to_tg(sq);
  1069. goto again;
  1070. }
  1071. }
  1072. } else {
  1073. /* reached the top-level, queue issueing */
  1074. queue_work(kthrotld_workqueue, &td->dispatch_work);
  1075. }
  1076. out_unlock:
  1077. spin_unlock_irq(q->queue_lock);
  1078. }
  1079. /**
  1080. * blk_throtl_dispatch_work_fn - work function for throtl_data->dispatch_work
  1081. * @work: work item being executed
  1082. *
  1083. * This function is queued for execution when bio's reach the bio_lists[]
  1084. * of throtl_data->service_queue. Those bio's are ready and issued by this
  1085. * function.
  1086. */
  1087. static void blk_throtl_dispatch_work_fn(struct work_struct *work)
  1088. {
  1089. struct throtl_data *td = container_of(work, struct throtl_data,
  1090. dispatch_work);
  1091. struct throtl_service_queue *td_sq = &td->service_queue;
  1092. struct request_queue *q = td->queue;
  1093. struct bio_list bio_list_on_stack;
  1094. struct bio *bio;
  1095. struct blk_plug plug;
  1096. int rw;
  1097. bio_list_init(&bio_list_on_stack);
  1098. spin_lock_irq(q->queue_lock);
  1099. for (rw = READ; rw <= WRITE; rw++)
  1100. while ((bio = throtl_pop_queued(&td_sq->queued[rw], NULL)))
  1101. bio_list_add(&bio_list_on_stack, bio);
  1102. spin_unlock_irq(q->queue_lock);
  1103. if (!bio_list_empty(&bio_list_on_stack)) {
  1104. blk_start_plug(&plug);
  1105. while((bio = bio_list_pop(&bio_list_on_stack)))
  1106. generic_make_request(bio);
  1107. blk_finish_plug(&plug);
  1108. }
  1109. }
  1110. static u64 tg_prfill_conf_u64(struct seq_file *sf, struct blkg_policy_data *pd,
  1111. int off)
  1112. {
  1113. struct throtl_grp *tg = pd_to_tg(pd);
  1114. u64 v = *(u64 *)((void *)tg + off);
  1115. if (v == U64_MAX)
  1116. return 0;
  1117. return __blkg_prfill_u64(sf, pd, v);
  1118. }
  1119. static u64 tg_prfill_conf_uint(struct seq_file *sf, struct blkg_policy_data *pd,
  1120. int off)
  1121. {
  1122. struct throtl_grp *tg = pd_to_tg(pd);
  1123. unsigned int v = *(unsigned int *)((void *)tg + off);
  1124. if (v == UINT_MAX)
  1125. return 0;
  1126. return __blkg_prfill_u64(sf, pd, v);
  1127. }
  1128. static int tg_print_conf_u64(struct seq_file *sf, void *v)
  1129. {
  1130. blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_conf_u64,
  1131. &blkcg_policy_throtl, seq_cft(sf)->private, false);
  1132. return 0;
  1133. }
  1134. static int tg_print_conf_uint(struct seq_file *sf, void *v)
  1135. {
  1136. blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_conf_uint,
  1137. &blkcg_policy_throtl, seq_cft(sf)->private, false);
  1138. return 0;
  1139. }
  1140. static void tg_conf_updated(struct throtl_grp *tg, bool global)
  1141. {
  1142. struct throtl_service_queue *sq = &tg->service_queue;
  1143. struct cgroup_subsys_state *pos_css;
  1144. struct blkcg_gq *blkg;
  1145. throtl_log(&tg->service_queue,
  1146. "limit change rbps=%llu wbps=%llu riops=%u wiops=%u",
  1147. tg_bps_limit(tg, READ), tg_bps_limit(tg, WRITE),
  1148. tg_iops_limit(tg, READ), tg_iops_limit(tg, WRITE));
  1149. /*
  1150. * Update has_rules[] flags for the updated tg's subtree. A tg is
  1151. * considered to have rules if either the tg itself or any of its
  1152. * ancestors has rules. This identifies groups without any
  1153. * restrictions in the whole hierarchy and allows them to bypass
  1154. * blk-throttle.
  1155. */
  1156. blkg_for_each_descendant_pre(blkg, pos_css,
  1157. global ? tg->td->queue->root_blkg : tg_to_blkg(tg)) {
  1158. struct throtl_grp *this_tg = blkg_to_tg(blkg);
  1159. struct throtl_grp *parent_tg;
  1160. tg_update_has_rules(this_tg);
  1161. /* ignore root/second level */
  1162. if (!cgroup_subsys_on_dfl(io_cgrp_subsys) || !blkg->parent ||
  1163. !blkg->parent->parent)
  1164. continue;
  1165. parent_tg = blkg_to_tg(blkg->parent);
  1166. /*
  1167. * make sure all children has lower idle time threshold and
  1168. * higher latency target
  1169. */
  1170. this_tg->idletime_threshold = min(this_tg->idletime_threshold,
  1171. parent_tg->idletime_threshold);
  1172. this_tg->latency_target = max(this_tg->latency_target,
  1173. parent_tg->latency_target);
  1174. }
  1175. /*
  1176. * We're already holding queue_lock and know @tg is valid. Let's
  1177. * apply the new config directly.
  1178. *
  1179. * Restart the slices for both READ and WRITES. It might happen
  1180. * that a group's limit are dropped suddenly and we don't want to
  1181. * account recently dispatched IO with new low rate.
  1182. */
  1183. throtl_start_new_slice(tg, 0);
  1184. throtl_start_new_slice(tg, 1);
  1185. if (tg->flags & THROTL_TG_PENDING) {
  1186. tg_update_disptime(tg);
  1187. throtl_schedule_next_dispatch(sq->parent_sq, true);
  1188. }
  1189. }
  1190. static ssize_t tg_set_conf(struct kernfs_open_file *of,
  1191. char *buf, size_t nbytes, loff_t off, bool is_u64)
  1192. {
  1193. struct blkcg *blkcg = css_to_blkcg(of_css(of));
  1194. struct blkg_conf_ctx ctx;
  1195. struct throtl_grp *tg;
  1196. int ret;
  1197. u64 v;
  1198. ret = blkg_conf_prep(blkcg, &blkcg_policy_throtl, buf, &ctx);
  1199. if (ret)
  1200. return ret;
  1201. ret = -EINVAL;
  1202. if (sscanf(ctx.body, "%llu", &v) != 1)
  1203. goto out_finish;
  1204. if (!v)
  1205. v = U64_MAX;
  1206. tg = blkg_to_tg(ctx.blkg);
  1207. if (is_u64)
  1208. *(u64 *)((void *)tg + of_cft(of)->private) = v;
  1209. else
  1210. *(unsigned int *)((void *)tg + of_cft(of)->private) = v;
  1211. tg_conf_updated(tg, false);
  1212. ret = 0;
  1213. out_finish:
  1214. blkg_conf_finish(&ctx);
  1215. return ret ?: nbytes;
  1216. }
  1217. static ssize_t tg_set_conf_u64(struct kernfs_open_file *of,
  1218. char *buf, size_t nbytes, loff_t off)
  1219. {
  1220. return tg_set_conf(of, buf, nbytes, off, true);
  1221. }
  1222. static ssize_t tg_set_conf_uint(struct kernfs_open_file *of,
  1223. char *buf, size_t nbytes, loff_t off)
  1224. {
  1225. return tg_set_conf(of, buf, nbytes, off, false);
  1226. }
  1227. static struct cftype throtl_legacy_files[] = {
  1228. {
  1229. .name = "throttle.read_bps_device",
  1230. .private = offsetof(struct throtl_grp, bps[READ][LIMIT_MAX]),
  1231. .seq_show = tg_print_conf_u64,
  1232. .write = tg_set_conf_u64,
  1233. },
  1234. {
  1235. .name = "throttle.write_bps_device",
  1236. .private = offsetof(struct throtl_grp, bps[WRITE][LIMIT_MAX]),
  1237. .seq_show = tg_print_conf_u64,
  1238. .write = tg_set_conf_u64,
  1239. },
  1240. {
  1241. .name = "throttle.read_iops_device",
  1242. .private = offsetof(struct throtl_grp, iops[READ][LIMIT_MAX]),
  1243. .seq_show = tg_print_conf_uint,
  1244. .write = tg_set_conf_uint,
  1245. },
  1246. {
  1247. .name = "throttle.write_iops_device",
  1248. .private = offsetof(struct throtl_grp, iops[WRITE][LIMIT_MAX]),
  1249. .seq_show = tg_print_conf_uint,
  1250. .write = tg_set_conf_uint,
  1251. },
  1252. {
  1253. .name = "throttle.io_service_bytes",
  1254. .private = (unsigned long)&blkcg_policy_throtl,
  1255. .seq_show = blkg_print_stat_bytes,
  1256. },
  1257. {
  1258. .name = "throttle.io_service_bytes_recursive",
  1259. .private = (unsigned long)&blkcg_policy_throtl,
  1260. .seq_show = blkg_print_stat_bytes_recursive,
  1261. },
  1262. {
  1263. .name = "throttle.io_serviced",
  1264. .private = (unsigned long)&blkcg_policy_throtl,
  1265. .seq_show = blkg_print_stat_ios,
  1266. },
  1267. {
  1268. .name = "throttle.io_serviced_recursive",
  1269. .private = (unsigned long)&blkcg_policy_throtl,
  1270. .seq_show = blkg_print_stat_ios_recursive,
  1271. },
  1272. { } /* terminate */
  1273. };
  1274. static u64 tg_prfill_limit(struct seq_file *sf, struct blkg_policy_data *pd,
  1275. int off)
  1276. {
  1277. struct throtl_grp *tg = pd_to_tg(pd);
  1278. const char *dname = blkg_dev_name(pd->blkg);
  1279. char bufs[4][21] = { "max", "max", "max", "max" };
  1280. u64 bps_dft;
  1281. unsigned int iops_dft;
  1282. char idle_time[26] = "";
  1283. char latency_time[26] = "";
  1284. if (!dname)
  1285. return 0;
  1286. if (off == LIMIT_LOW) {
  1287. bps_dft = 0;
  1288. iops_dft = 0;
  1289. } else {
  1290. bps_dft = U64_MAX;
  1291. iops_dft = UINT_MAX;
  1292. }
  1293. if (tg->bps_conf[READ][off] == bps_dft &&
  1294. tg->bps_conf[WRITE][off] == bps_dft &&
  1295. tg->iops_conf[READ][off] == iops_dft &&
  1296. tg->iops_conf[WRITE][off] == iops_dft &&
  1297. (off != LIMIT_LOW ||
  1298. (tg->idletime_threshold_conf == DFL_IDLE_THRESHOLD &&
  1299. tg->latency_target_conf == DFL_LATENCY_TARGET)))
  1300. return 0;
  1301. if (tg->bps_conf[READ][off] != U64_MAX)
  1302. snprintf(bufs[0], sizeof(bufs[0]), "%llu",
  1303. tg->bps_conf[READ][off]);
  1304. if (tg->bps_conf[WRITE][off] != U64_MAX)
  1305. snprintf(bufs[1], sizeof(bufs[1]), "%llu",
  1306. tg->bps_conf[WRITE][off]);
  1307. if (tg->iops_conf[READ][off] != UINT_MAX)
  1308. snprintf(bufs[2], sizeof(bufs[2]), "%u",
  1309. tg->iops_conf[READ][off]);
  1310. if (tg->iops_conf[WRITE][off] != UINT_MAX)
  1311. snprintf(bufs[3], sizeof(bufs[3]), "%u",
  1312. tg->iops_conf[WRITE][off]);
  1313. if (off == LIMIT_LOW) {
  1314. if (tg->idletime_threshold_conf == ULONG_MAX)
  1315. strcpy(idle_time, " idle=max");
  1316. else
  1317. snprintf(idle_time, sizeof(idle_time), " idle=%lu",
  1318. tg->idletime_threshold_conf);
  1319. if (tg->latency_target_conf == ULONG_MAX)
  1320. strcpy(latency_time, " latency=max");
  1321. else
  1322. snprintf(latency_time, sizeof(latency_time),
  1323. " latency=%lu", tg->latency_target_conf);
  1324. }
  1325. seq_printf(sf, "%s rbps=%s wbps=%s riops=%s wiops=%s%s%s\n",
  1326. dname, bufs[0], bufs[1], bufs[2], bufs[3], idle_time,
  1327. latency_time);
  1328. return 0;
  1329. }
  1330. static int tg_print_limit(struct seq_file *sf, void *v)
  1331. {
  1332. blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_limit,
  1333. &blkcg_policy_throtl, seq_cft(sf)->private, false);
  1334. return 0;
  1335. }
  1336. static ssize_t tg_set_limit(struct kernfs_open_file *of,
  1337. char *buf, size_t nbytes, loff_t off)
  1338. {
  1339. struct blkcg *blkcg = css_to_blkcg(of_css(of));
  1340. struct blkg_conf_ctx ctx;
  1341. struct throtl_grp *tg;
  1342. u64 v[4];
  1343. unsigned long idle_time;
  1344. unsigned long latency_time;
  1345. int ret;
  1346. int index = of_cft(of)->private;
  1347. ret = blkg_conf_prep(blkcg, &blkcg_policy_throtl, buf, &ctx);
  1348. if (ret)
  1349. return ret;
  1350. tg = blkg_to_tg(ctx.blkg);
  1351. v[0] = tg->bps_conf[READ][index];
  1352. v[1] = tg->bps_conf[WRITE][index];
  1353. v[2] = tg->iops_conf[READ][index];
  1354. v[3] = tg->iops_conf[WRITE][index];
  1355. idle_time = tg->idletime_threshold_conf;
  1356. latency_time = tg->latency_target_conf;
  1357. while (true) {
  1358. char tok[27]; /* wiops=18446744073709551616 */
  1359. char *p;
  1360. u64 val = U64_MAX;
  1361. int len;
  1362. if (sscanf(ctx.body, "%26s%n", tok, &len) != 1)
  1363. break;
  1364. if (tok[0] == '\0')
  1365. break;
  1366. ctx.body += len;
  1367. ret = -EINVAL;
  1368. p = tok;
  1369. strsep(&p, "=");
  1370. if (!p || (sscanf(p, "%llu", &val) != 1 && strcmp(p, "max")))
  1371. goto out_finish;
  1372. ret = -ERANGE;
  1373. if (!val)
  1374. goto out_finish;
  1375. ret = -EINVAL;
  1376. if (!strcmp(tok, "rbps"))
  1377. v[0] = val;
  1378. else if (!strcmp(tok, "wbps"))
  1379. v[1] = val;
  1380. else if (!strcmp(tok, "riops"))
  1381. v[2] = min_t(u64, val, UINT_MAX);
  1382. else if (!strcmp(tok, "wiops"))
  1383. v[3] = min_t(u64, val, UINT_MAX);
  1384. else if (off == LIMIT_LOW && !strcmp(tok, "idle"))
  1385. idle_time = val;
  1386. else if (off == LIMIT_LOW && !strcmp(tok, "latency"))
  1387. latency_time = val;
  1388. else
  1389. goto out_finish;
  1390. }
  1391. tg->bps_conf[READ][index] = v[0];
  1392. tg->bps_conf[WRITE][index] = v[1];
  1393. tg->iops_conf[READ][index] = v[2];
  1394. tg->iops_conf[WRITE][index] = v[3];
  1395. if (index == LIMIT_MAX) {
  1396. tg->bps[READ][index] = v[0];
  1397. tg->bps[WRITE][index] = v[1];
  1398. tg->iops[READ][index] = v[2];
  1399. tg->iops[WRITE][index] = v[3];
  1400. }
  1401. tg->bps[READ][LIMIT_LOW] = min(tg->bps_conf[READ][LIMIT_LOW],
  1402. tg->bps_conf[READ][LIMIT_MAX]);
  1403. tg->bps[WRITE][LIMIT_LOW] = min(tg->bps_conf[WRITE][LIMIT_LOW],
  1404. tg->bps_conf[WRITE][LIMIT_MAX]);
  1405. tg->iops[READ][LIMIT_LOW] = min(tg->iops_conf[READ][LIMIT_LOW],
  1406. tg->iops_conf[READ][LIMIT_MAX]);
  1407. tg->iops[WRITE][LIMIT_LOW] = min(tg->iops_conf[WRITE][LIMIT_LOW],
  1408. tg->iops_conf[WRITE][LIMIT_MAX]);
  1409. tg->idletime_threshold_conf = idle_time;
  1410. tg->latency_target_conf = latency_time;
  1411. /* force user to configure all settings for low limit */
  1412. if (!(tg->bps[READ][LIMIT_LOW] || tg->iops[READ][LIMIT_LOW] ||
  1413. tg->bps[WRITE][LIMIT_LOW] || tg->iops[WRITE][LIMIT_LOW]) ||
  1414. tg->idletime_threshold_conf == DFL_IDLE_THRESHOLD ||
  1415. tg->latency_target_conf == DFL_LATENCY_TARGET) {
  1416. tg->bps[READ][LIMIT_LOW] = 0;
  1417. tg->bps[WRITE][LIMIT_LOW] = 0;
  1418. tg->iops[READ][LIMIT_LOW] = 0;
  1419. tg->iops[WRITE][LIMIT_LOW] = 0;
  1420. tg->idletime_threshold = DFL_IDLE_THRESHOLD;
  1421. tg->latency_target = DFL_LATENCY_TARGET;
  1422. } else if (index == LIMIT_LOW) {
  1423. tg->idletime_threshold = tg->idletime_threshold_conf;
  1424. tg->latency_target = tg->latency_target_conf;
  1425. }
  1426. blk_throtl_update_limit_valid(tg->td);
  1427. if (tg->td->limit_valid[LIMIT_LOW]) {
  1428. if (index == LIMIT_LOW)
  1429. tg->td->limit_index = LIMIT_LOW;
  1430. } else
  1431. tg->td->limit_index = LIMIT_MAX;
  1432. tg_conf_updated(tg, index == LIMIT_LOW &&
  1433. tg->td->limit_valid[LIMIT_LOW]);
  1434. ret = 0;
  1435. out_finish:
  1436. blkg_conf_finish(&ctx);
  1437. return ret ?: nbytes;
  1438. }
  1439. static struct cftype throtl_files[] = {
  1440. #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
  1441. {
  1442. .name = "low",
  1443. .flags = CFTYPE_NOT_ON_ROOT,
  1444. .seq_show = tg_print_limit,
  1445. .write = tg_set_limit,
  1446. .private = LIMIT_LOW,
  1447. },
  1448. #endif
  1449. {
  1450. .name = "max",
  1451. .flags = CFTYPE_NOT_ON_ROOT,
  1452. .seq_show = tg_print_limit,
  1453. .write = tg_set_limit,
  1454. .private = LIMIT_MAX,
  1455. },
  1456. { } /* terminate */
  1457. };
  1458. static void throtl_shutdown_wq(struct request_queue *q)
  1459. {
  1460. struct throtl_data *td = q->td;
  1461. cancel_work_sync(&td->dispatch_work);
  1462. }
  1463. static struct blkcg_policy blkcg_policy_throtl = {
  1464. .dfl_cftypes = throtl_files,
  1465. .legacy_cftypes = throtl_legacy_files,
  1466. .pd_alloc_fn = throtl_pd_alloc,
  1467. .pd_init_fn = throtl_pd_init,
  1468. .pd_online_fn = throtl_pd_online,
  1469. .pd_offline_fn = throtl_pd_offline,
  1470. .pd_free_fn = throtl_pd_free,
  1471. };
  1472. static unsigned long __tg_last_low_overflow_time(struct throtl_grp *tg)
  1473. {
  1474. unsigned long rtime = jiffies, wtime = jiffies;
  1475. if (tg->bps[READ][LIMIT_LOW] || tg->iops[READ][LIMIT_LOW])
  1476. rtime = tg->last_low_overflow_time[READ];
  1477. if (tg->bps[WRITE][LIMIT_LOW] || tg->iops[WRITE][LIMIT_LOW])
  1478. wtime = tg->last_low_overflow_time[WRITE];
  1479. return min(rtime, wtime);
  1480. }
  1481. /* tg should not be an intermediate node */
  1482. static unsigned long tg_last_low_overflow_time(struct throtl_grp *tg)
  1483. {
  1484. struct throtl_service_queue *parent_sq;
  1485. struct throtl_grp *parent = tg;
  1486. unsigned long ret = __tg_last_low_overflow_time(tg);
  1487. while (true) {
  1488. parent_sq = parent->service_queue.parent_sq;
  1489. parent = sq_to_tg(parent_sq);
  1490. if (!parent)
  1491. break;
  1492. /*
  1493. * The parent doesn't have low limit, it always reaches low
  1494. * limit. Its overflow time is useless for children
  1495. */
  1496. if (!parent->bps[READ][LIMIT_LOW] &&
  1497. !parent->iops[READ][LIMIT_LOW] &&
  1498. !parent->bps[WRITE][LIMIT_LOW] &&
  1499. !parent->iops[WRITE][LIMIT_LOW])
  1500. continue;
  1501. if (time_after(__tg_last_low_overflow_time(parent), ret))
  1502. ret = __tg_last_low_overflow_time(parent);
  1503. }
  1504. return ret;
  1505. }
  1506. static bool throtl_tg_is_idle(struct throtl_grp *tg)
  1507. {
  1508. /*
  1509. * cgroup is idle if:
  1510. * - single idle is too long, longer than a fixed value (in case user
  1511. * configure a too big threshold) or 4 times of idletime threshold
  1512. * - average think time is more than threshold
  1513. * - IO latency is largely below threshold
  1514. */
  1515. unsigned long time;
  1516. bool ret;
  1517. time = min_t(unsigned long, MAX_IDLE_TIME, 4 * tg->idletime_threshold);
  1518. ret = tg->latency_target == DFL_LATENCY_TARGET ||
  1519. tg->idletime_threshold == DFL_IDLE_THRESHOLD ||
  1520. (ktime_get_ns() >> 10) - tg->last_finish_time > time ||
  1521. tg->avg_idletime > tg->idletime_threshold ||
  1522. (tg->latency_target && tg->bio_cnt &&
  1523. tg->bad_bio_cnt * 5 < tg->bio_cnt);
  1524. throtl_log(&tg->service_queue,
  1525. "avg_idle=%ld, idle_threshold=%ld, bad_bio=%d, total_bio=%d, is_idle=%d, scale=%d",
  1526. tg->avg_idletime, tg->idletime_threshold, tg->bad_bio_cnt,
  1527. tg->bio_cnt, ret, tg->td->scale);
  1528. return ret;
  1529. }
  1530. static bool throtl_tg_can_upgrade(struct throtl_grp *tg)
  1531. {
  1532. struct throtl_service_queue *sq = &tg->service_queue;
  1533. bool read_limit, write_limit;
  1534. /*
  1535. * if cgroup reaches low limit (if low limit is 0, the cgroup always
  1536. * reaches), it's ok to upgrade to next limit
  1537. */
  1538. read_limit = tg->bps[READ][LIMIT_LOW] || tg->iops[READ][LIMIT_LOW];
  1539. write_limit = tg->bps[WRITE][LIMIT_LOW] || tg->iops[WRITE][LIMIT_LOW];
  1540. if (!read_limit && !write_limit)
  1541. return true;
  1542. if (read_limit && sq->nr_queued[READ] &&
  1543. (!write_limit || sq->nr_queued[WRITE]))
  1544. return true;
  1545. if (write_limit && sq->nr_queued[WRITE] &&
  1546. (!read_limit || sq->nr_queued[READ]))
  1547. return true;
  1548. if (time_after_eq(jiffies,
  1549. tg_last_low_overflow_time(tg) + tg->td->throtl_slice) &&
  1550. throtl_tg_is_idle(tg))
  1551. return true;
  1552. return false;
  1553. }
  1554. static bool throtl_hierarchy_can_upgrade(struct throtl_grp *tg)
  1555. {
  1556. while (true) {
  1557. if (throtl_tg_can_upgrade(tg))
  1558. return true;
  1559. tg = sq_to_tg(tg->service_queue.parent_sq);
  1560. if (!tg || !tg_to_blkg(tg)->parent)
  1561. return false;
  1562. }
  1563. return false;
  1564. }
  1565. static bool throtl_can_upgrade(struct throtl_data *td,
  1566. struct throtl_grp *this_tg)
  1567. {
  1568. struct cgroup_subsys_state *pos_css;
  1569. struct blkcg_gq *blkg;
  1570. if (td->limit_index != LIMIT_LOW)
  1571. return false;
  1572. if (time_before(jiffies, td->low_downgrade_time + td->throtl_slice))
  1573. return false;
  1574. rcu_read_lock();
  1575. blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg) {
  1576. struct throtl_grp *tg = blkg_to_tg(blkg);
  1577. if (tg == this_tg)
  1578. continue;
  1579. if (!list_empty(&tg_to_blkg(tg)->blkcg->css.children))
  1580. continue;
  1581. if (!throtl_hierarchy_can_upgrade(tg)) {
  1582. rcu_read_unlock();
  1583. return false;
  1584. }
  1585. }
  1586. rcu_read_unlock();
  1587. return true;
  1588. }
  1589. static void throtl_upgrade_check(struct throtl_grp *tg)
  1590. {
  1591. unsigned long now = jiffies;
  1592. if (tg->td->limit_index != LIMIT_LOW)
  1593. return;
  1594. if (time_after(tg->last_check_time + tg->td->throtl_slice, now))
  1595. return;
  1596. tg->last_check_time = now;
  1597. if (!time_after_eq(now,
  1598. __tg_last_low_overflow_time(tg) + tg->td->throtl_slice))
  1599. return;
  1600. if (throtl_can_upgrade(tg->td, NULL))
  1601. throtl_upgrade_state(tg->td);
  1602. }
  1603. static void throtl_upgrade_state(struct throtl_data *td)
  1604. {
  1605. struct cgroup_subsys_state *pos_css;
  1606. struct blkcg_gq *blkg;
  1607. throtl_log(&td->service_queue, "upgrade to max");
  1608. td->limit_index = LIMIT_MAX;
  1609. td->low_upgrade_time = jiffies;
  1610. td->scale = 0;
  1611. rcu_read_lock();
  1612. blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg) {
  1613. struct throtl_grp *tg = blkg_to_tg(blkg);
  1614. struct throtl_service_queue *sq = &tg->service_queue;
  1615. tg->disptime = jiffies - 1;
  1616. throtl_select_dispatch(sq);
  1617. throtl_schedule_next_dispatch(sq, true);
  1618. }
  1619. rcu_read_unlock();
  1620. throtl_select_dispatch(&td->service_queue);
  1621. throtl_schedule_next_dispatch(&td->service_queue, true);
  1622. queue_work(kthrotld_workqueue, &td->dispatch_work);
  1623. }
  1624. static void throtl_downgrade_state(struct throtl_data *td, int new)
  1625. {
  1626. td->scale /= 2;
  1627. throtl_log(&td->service_queue, "downgrade, scale %d", td->scale);
  1628. if (td->scale) {
  1629. td->low_upgrade_time = jiffies - td->scale * td->throtl_slice;
  1630. return;
  1631. }
  1632. td->limit_index = new;
  1633. td->low_downgrade_time = jiffies;
  1634. }
  1635. static bool throtl_tg_can_downgrade(struct throtl_grp *tg)
  1636. {
  1637. struct throtl_data *td = tg->td;
  1638. unsigned long now = jiffies;
  1639. /*
  1640. * If cgroup is below low limit, consider downgrade and throttle other
  1641. * cgroups
  1642. */
  1643. if (time_after_eq(now, td->low_upgrade_time + td->throtl_slice) &&
  1644. time_after_eq(now, tg_last_low_overflow_time(tg) +
  1645. td->throtl_slice) &&
  1646. (!throtl_tg_is_idle(tg) ||
  1647. !list_empty(&tg_to_blkg(tg)->blkcg->css.children)))
  1648. return true;
  1649. return false;
  1650. }
  1651. static bool throtl_hierarchy_can_downgrade(struct throtl_grp *tg)
  1652. {
  1653. while (true) {
  1654. if (!throtl_tg_can_downgrade(tg))
  1655. return false;
  1656. tg = sq_to_tg(tg->service_queue.parent_sq);
  1657. if (!tg || !tg_to_blkg(tg)->parent)
  1658. break;
  1659. }
  1660. return true;
  1661. }
  1662. static void throtl_downgrade_check(struct throtl_grp *tg)
  1663. {
  1664. uint64_t bps;
  1665. unsigned int iops;
  1666. unsigned long elapsed_time;
  1667. unsigned long now = jiffies;
  1668. if (tg->td->limit_index != LIMIT_MAX ||
  1669. !tg->td->limit_valid[LIMIT_LOW])
  1670. return;
  1671. if (!list_empty(&tg_to_blkg(tg)->blkcg->css.children))
  1672. return;
  1673. if (time_after(tg->last_check_time + tg->td->throtl_slice, now))
  1674. return;
  1675. elapsed_time = now - tg->last_check_time;
  1676. tg->last_check_time = now;
  1677. if (time_before(now, tg_last_low_overflow_time(tg) +
  1678. tg->td->throtl_slice))
  1679. return;
  1680. if (tg->bps[READ][LIMIT_LOW]) {
  1681. bps = tg->last_bytes_disp[READ] * HZ;
  1682. do_div(bps, elapsed_time);
  1683. if (bps >= tg->bps[READ][LIMIT_LOW])
  1684. tg->last_low_overflow_time[READ] = now;
  1685. }
  1686. if (tg->bps[WRITE][LIMIT_LOW]) {
  1687. bps = tg->last_bytes_disp[WRITE] * HZ;
  1688. do_div(bps, elapsed_time);
  1689. if (bps >= tg->bps[WRITE][LIMIT_LOW])
  1690. tg->last_low_overflow_time[WRITE] = now;
  1691. }
  1692. if (tg->iops[READ][LIMIT_LOW]) {
  1693. iops = tg->last_io_disp[READ] * HZ / elapsed_time;
  1694. if (iops >= tg->iops[READ][LIMIT_LOW])
  1695. tg->last_low_overflow_time[READ] = now;
  1696. }
  1697. if (tg->iops[WRITE][LIMIT_LOW]) {
  1698. iops = tg->last_io_disp[WRITE] * HZ / elapsed_time;
  1699. if (iops >= tg->iops[WRITE][LIMIT_LOW])
  1700. tg->last_low_overflow_time[WRITE] = now;
  1701. }
  1702. /*
  1703. * If cgroup is below low limit, consider downgrade and throttle other
  1704. * cgroups
  1705. */
  1706. if (throtl_hierarchy_can_downgrade(tg))
  1707. throtl_downgrade_state(tg->td, LIMIT_LOW);
  1708. tg->last_bytes_disp[READ] = 0;
  1709. tg->last_bytes_disp[WRITE] = 0;
  1710. tg->last_io_disp[READ] = 0;
  1711. tg->last_io_disp[WRITE] = 0;
  1712. }
  1713. static void blk_throtl_update_idletime(struct throtl_grp *tg)
  1714. {
  1715. unsigned long now = ktime_get_ns() >> 10;
  1716. unsigned long last_finish_time = tg->last_finish_time;
  1717. if (now <= last_finish_time || last_finish_time == 0 ||
  1718. last_finish_time == tg->checked_last_finish_time)
  1719. return;
  1720. tg->avg_idletime = (tg->avg_idletime * 7 + now - last_finish_time) >> 3;
  1721. tg->checked_last_finish_time = last_finish_time;
  1722. }
  1723. #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
  1724. static void throtl_update_latency_buckets(struct throtl_data *td)
  1725. {
  1726. struct avg_latency_bucket avg_latency[2][LATENCY_BUCKET_SIZE];
  1727. int i, cpu, rw;
  1728. unsigned long last_latency[2] = { 0 };
  1729. unsigned long latency[2];
  1730. if (!blk_queue_nonrot(td->queue))
  1731. return;
  1732. if (time_before(jiffies, td->last_calculate_time + HZ))
  1733. return;
  1734. td->last_calculate_time = jiffies;
  1735. memset(avg_latency, 0, sizeof(avg_latency));
  1736. for (rw = READ; rw <= WRITE; rw++) {
  1737. for (i = 0; i < LATENCY_BUCKET_SIZE; i++) {
  1738. struct latency_bucket *tmp = &td->tmp_buckets[rw][i];
  1739. for_each_possible_cpu(cpu) {
  1740. struct latency_bucket *bucket;
  1741. /* this isn't race free, but ok in practice */
  1742. bucket = per_cpu_ptr(td->latency_buckets[rw],
  1743. cpu);
  1744. tmp->total_latency += bucket[i].total_latency;
  1745. tmp->samples += bucket[i].samples;
  1746. bucket[i].total_latency = 0;
  1747. bucket[i].samples = 0;
  1748. }
  1749. if (tmp->samples >= 32) {
  1750. int samples = tmp->samples;
  1751. latency[rw] = tmp->total_latency;
  1752. tmp->total_latency = 0;
  1753. tmp->samples = 0;
  1754. latency[rw] /= samples;
  1755. if (latency[rw] == 0)
  1756. continue;
  1757. avg_latency[rw][i].latency = latency[rw];
  1758. }
  1759. }
  1760. }
  1761. for (rw = READ; rw <= WRITE; rw++) {
  1762. for (i = 0; i < LATENCY_BUCKET_SIZE; i++) {
  1763. if (!avg_latency[rw][i].latency) {
  1764. if (td->avg_buckets[rw][i].latency < last_latency[rw])
  1765. td->avg_buckets[rw][i].latency =
  1766. last_latency[rw];
  1767. continue;
  1768. }
  1769. if (!td->avg_buckets[rw][i].valid)
  1770. latency[rw] = avg_latency[rw][i].latency;
  1771. else
  1772. latency[rw] = (td->avg_buckets[rw][i].latency * 7 +
  1773. avg_latency[rw][i].latency) >> 3;
  1774. td->avg_buckets[rw][i].latency = max(latency[rw],
  1775. last_latency[rw]);
  1776. td->avg_buckets[rw][i].valid = true;
  1777. last_latency[rw] = td->avg_buckets[rw][i].latency;
  1778. }
  1779. }
  1780. for (i = 0; i < LATENCY_BUCKET_SIZE; i++)
  1781. throtl_log(&td->service_queue,
  1782. "Latency bucket %d: read latency=%ld, read valid=%d, "
  1783. "write latency=%ld, write valid=%d", i,
  1784. td->avg_buckets[READ][i].latency,
  1785. td->avg_buckets[READ][i].valid,
  1786. td->avg_buckets[WRITE][i].latency,
  1787. td->avg_buckets[WRITE][i].valid);
  1788. }
  1789. #else
  1790. static inline void throtl_update_latency_buckets(struct throtl_data *td)
  1791. {
  1792. }
  1793. #endif
  1794. static void blk_throtl_assoc_bio(struct throtl_grp *tg, struct bio *bio)
  1795. {
  1796. #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
  1797. /* fallback to root_blkg if we fail to get a blkg ref */
  1798. if (bio->bi_css && (bio_associate_blkg(bio, tg_to_blkg(tg)) == -ENODEV))
  1799. bio_associate_blkg(bio, bio->bi_disk->queue->root_blkg);
  1800. bio_issue_init(&bio->bi_issue, bio_sectors(bio));
  1801. #endif
  1802. }
  1803. bool blk_throtl_bio(struct request_queue *q, struct blkcg_gq *blkg,
  1804. struct bio *bio)
  1805. {
  1806. struct throtl_qnode *qn = NULL;
  1807. struct throtl_grp *tg = blkg_to_tg(blkg ?: q->root_blkg);
  1808. struct throtl_service_queue *sq;
  1809. bool rw = bio_data_dir(bio);
  1810. bool throttled = false;
  1811. struct throtl_data *td = tg->td;
  1812. WARN_ON_ONCE(!rcu_read_lock_held());
  1813. /* see throtl_charge_bio() */
  1814. if (bio_flagged(bio, BIO_THROTTLED) || !tg->has_rules[rw])
  1815. goto out;
  1816. spin_lock_irq(q->queue_lock);
  1817. throtl_update_latency_buckets(td);
  1818. if (unlikely(blk_queue_bypass(q)))
  1819. goto out_unlock;
  1820. blk_throtl_assoc_bio(tg, bio);
  1821. blk_throtl_update_idletime(tg);
  1822. sq = &tg->service_queue;
  1823. again:
  1824. while (true) {
  1825. if (tg->last_low_overflow_time[rw] == 0)
  1826. tg->last_low_overflow_time[rw] = jiffies;
  1827. throtl_downgrade_check(tg);
  1828. throtl_upgrade_check(tg);
  1829. /* throtl is FIFO - if bios are already queued, should queue */
  1830. if (sq->nr_queued[rw])
  1831. break;
  1832. /* if above limits, break to queue */
  1833. if (!tg_may_dispatch(tg, bio, NULL)) {
  1834. tg->last_low_overflow_time[rw] = jiffies;
  1835. if (throtl_can_upgrade(td, tg)) {
  1836. throtl_upgrade_state(td);
  1837. goto again;
  1838. }
  1839. break;
  1840. }
  1841. /* within limits, let's charge and dispatch directly */
  1842. throtl_charge_bio(tg, bio);
  1843. /*
  1844. * We need to trim slice even when bios are not being queued
  1845. * otherwise it might happen that a bio is not queued for
  1846. * a long time and slice keeps on extending and trim is not
  1847. * called for a long time. Now if limits are reduced suddenly
  1848. * we take into account all the IO dispatched so far at new
  1849. * low rate and * newly queued IO gets a really long dispatch
  1850. * time.
  1851. *
  1852. * So keep on trimming slice even if bio is not queued.
  1853. */
  1854. throtl_trim_slice(tg, rw);
  1855. /*
  1856. * @bio passed through this layer without being throttled.
  1857. * Climb up the ladder. If we''re already at the top, it
  1858. * can be executed directly.
  1859. */
  1860. qn = &tg->qnode_on_parent[rw];
  1861. sq = sq->parent_sq;
  1862. tg = sq_to_tg(sq);
  1863. if (!tg)
  1864. goto out_unlock;
  1865. }
  1866. /* out-of-limit, queue to @tg */
  1867. throtl_log(sq, "[%c] bio. bdisp=%llu sz=%u bps=%llu iodisp=%u iops=%u queued=%d/%d",
  1868. rw == READ ? 'R' : 'W',
  1869. tg->bytes_disp[rw], bio->bi_iter.bi_size,
  1870. tg_bps_limit(tg, rw),
  1871. tg->io_disp[rw], tg_iops_limit(tg, rw),
  1872. sq->nr_queued[READ], sq->nr_queued[WRITE]);
  1873. tg->last_low_overflow_time[rw] = jiffies;
  1874. td->nr_queued[rw]++;
  1875. throtl_add_bio_tg(bio, qn, tg);
  1876. throttled = true;
  1877. /*
  1878. * Update @tg's dispatch time and force schedule dispatch if @tg
  1879. * was empty before @bio. The forced scheduling isn't likely to
  1880. * cause undue delay as @bio is likely to be dispatched directly if
  1881. * its @tg's disptime is not in the future.
  1882. */
  1883. if (tg->flags & THROTL_TG_WAS_EMPTY) {
  1884. tg_update_disptime(tg);
  1885. throtl_schedule_next_dispatch(tg->service_queue.parent_sq, true);
  1886. }
  1887. out_unlock:
  1888. spin_unlock_irq(q->queue_lock);
  1889. out:
  1890. bio_set_flag(bio, BIO_THROTTLED);
  1891. #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
  1892. if (throttled || !td->track_bio_latency)
  1893. bio->bi_issue.value |= BIO_ISSUE_THROTL_SKIP_LATENCY;
  1894. #endif
  1895. return throttled;
  1896. }
  1897. #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
  1898. static void throtl_track_latency(struct throtl_data *td, sector_t size,
  1899. int op, unsigned long time)
  1900. {
  1901. struct latency_bucket *latency;
  1902. int index;
  1903. if (!td || td->limit_index != LIMIT_LOW ||
  1904. !(op == REQ_OP_READ || op == REQ_OP_WRITE) ||
  1905. !blk_queue_nonrot(td->queue))
  1906. return;
  1907. index = request_bucket_index(size);
  1908. latency = get_cpu_ptr(td->latency_buckets[op]);
  1909. latency[index].total_latency += time;
  1910. latency[index].samples++;
  1911. put_cpu_ptr(td->latency_buckets[op]);
  1912. }
  1913. void blk_throtl_stat_add(struct request *rq, u64 time_ns)
  1914. {
  1915. struct request_queue *q = rq->q;
  1916. struct throtl_data *td = q->td;
  1917. throtl_track_latency(td, rq->throtl_size, req_op(rq), time_ns >> 10);
  1918. }
  1919. void blk_throtl_bio_endio(struct bio *bio)
  1920. {
  1921. struct blkcg_gq *blkg;
  1922. struct throtl_grp *tg;
  1923. u64 finish_time_ns;
  1924. unsigned long finish_time;
  1925. unsigned long start_time;
  1926. unsigned long lat;
  1927. int rw = bio_data_dir(bio);
  1928. blkg = bio->bi_blkg;
  1929. if (!blkg)
  1930. return;
  1931. tg = blkg_to_tg(blkg);
  1932. finish_time_ns = ktime_get_ns();
  1933. tg->last_finish_time = finish_time_ns >> 10;
  1934. start_time = bio_issue_time(&bio->bi_issue) >> 10;
  1935. finish_time = __bio_issue_time(finish_time_ns) >> 10;
  1936. if (!start_time || finish_time <= start_time)
  1937. return;
  1938. lat = finish_time - start_time;
  1939. /* this is only for bio based driver */
  1940. if (!(bio->bi_issue.value & BIO_ISSUE_THROTL_SKIP_LATENCY))
  1941. throtl_track_latency(tg->td, bio_issue_size(&bio->bi_issue),
  1942. bio_op(bio), lat);
  1943. if (tg->latency_target && lat >= tg->td->filtered_latency) {
  1944. int bucket;
  1945. unsigned int threshold;
  1946. bucket = request_bucket_index(bio_issue_size(&bio->bi_issue));
  1947. threshold = tg->td->avg_buckets[rw][bucket].latency +
  1948. tg->latency_target;
  1949. if (lat > threshold)
  1950. tg->bad_bio_cnt++;
  1951. /*
  1952. * Not race free, could get wrong count, which means cgroups
  1953. * will be throttled
  1954. */
  1955. tg->bio_cnt++;
  1956. }
  1957. if (time_after(jiffies, tg->bio_cnt_reset_time) || tg->bio_cnt > 1024) {
  1958. tg->bio_cnt_reset_time = tg->td->throtl_slice + jiffies;
  1959. tg->bio_cnt /= 2;
  1960. tg->bad_bio_cnt /= 2;
  1961. }
  1962. }
  1963. #endif
  1964. /*
  1965. * Dispatch all bios from all children tg's queued on @parent_sq. On
  1966. * return, @parent_sq is guaranteed to not have any active children tg's
  1967. * and all bios from previously active tg's are on @parent_sq->bio_lists[].
  1968. */
  1969. static void tg_drain_bios(struct throtl_service_queue *parent_sq)
  1970. {
  1971. struct throtl_grp *tg;
  1972. while ((tg = throtl_rb_first(parent_sq))) {
  1973. struct throtl_service_queue *sq = &tg->service_queue;
  1974. struct bio *bio;
  1975. throtl_dequeue_tg(tg);
  1976. while ((bio = throtl_peek_queued(&sq->queued[READ])))
  1977. tg_dispatch_one_bio(tg, bio_data_dir(bio));
  1978. while ((bio = throtl_peek_queued(&sq->queued[WRITE])))
  1979. tg_dispatch_one_bio(tg, bio_data_dir(bio));
  1980. }
  1981. }
  1982. /**
  1983. * blk_throtl_drain - drain throttled bios
  1984. * @q: request_queue to drain throttled bios for
  1985. *
  1986. * Dispatch all currently throttled bios on @q through ->make_request_fn().
  1987. */
  1988. void blk_throtl_drain(struct request_queue *q)
  1989. __releases(q->queue_lock) __acquires(q->queue_lock)
  1990. {
  1991. struct throtl_data *td = q->td;
  1992. struct blkcg_gq *blkg;
  1993. struct cgroup_subsys_state *pos_css;
  1994. struct bio *bio;
  1995. int rw;
  1996. queue_lockdep_assert_held(q);
  1997. rcu_read_lock();
  1998. /*
  1999. * Drain each tg while doing post-order walk on the blkg tree, so
  2000. * that all bios are propagated to td->service_queue. It'd be
  2001. * better to walk service_queue tree directly but blkg walk is
  2002. * easier.
  2003. */
  2004. blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg)
  2005. tg_drain_bios(&blkg_to_tg(blkg)->service_queue);
  2006. /* finally, transfer bios from top-level tg's into the td */
  2007. tg_drain_bios(&td->service_queue);
  2008. rcu_read_unlock();
  2009. spin_unlock_irq(q->queue_lock);
  2010. /* all bios now should be in td->service_queue, issue them */
  2011. for (rw = READ; rw <= WRITE; rw++)
  2012. while ((bio = throtl_pop_queued(&td->service_queue.queued[rw],
  2013. NULL)))
  2014. generic_make_request(bio);
  2015. spin_lock_irq(q->queue_lock);
  2016. }
  2017. int blk_throtl_init(struct request_queue *q)
  2018. {
  2019. struct throtl_data *td;
  2020. int ret;
  2021. td = kzalloc_node(sizeof(*td), GFP_KERNEL, q->node);
  2022. if (!td)
  2023. return -ENOMEM;
  2024. td->latency_buckets[READ] = __alloc_percpu(sizeof(struct latency_bucket) *
  2025. LATENCY_BUCKET_SIZE, __alignof__(u64));
  2026. if (!td->latency_buckets[READ]) {
  2027. kfree(td);
  2028. return -ENOMEM;
  2029. }
  2030. td->latency_buckets[WRITE] = __alloc_percpu(sizeof(struct latency_bucket) *
  2031. LATENCY_BUCKET_SIZE, __alignof__(u64));
  2032. if (!td->latency_buckets[WRITE]) {
  2033. free_percpu(td->latency_buckets[READ]);
  2034. kfree(td);
  2035. return -ENOMEM;
  2036. }
  2037. INIT_WORK(&td->dispatch_work, blk_throtl_dispatch_work_fn);
  2038. throtl_service_queue_init(&td->service_queue);
  2039. q->td = td;
  2040. td->queue = q;
  2041. td->limit_valid[LIMIT_MAX] = true;
  2042. td->limit_index = LIMIT_MAX;
  2043. td->low_upgrade_time = jiffies;
  2044. td->low_downgrade_time = jiffies;
  2045. /* activate policy */
  2046. ret = blkcg_activate_policy(q, &blkcg_policy_throtl);
  2047. if (ret) {
  2048. free_percpu(td->latency_buckets[READ]);
  2049. free_percpu(td->latency_buckets[WRITE]);
  2050. kfree(td);
  2051. }
  2052. return ret;
  2053. }
  2054. void blk_throtl_exit(struct request_queue *q)
  2055. {
  2056. BUG_ON(!q->td);
  2057. throtl_shutdown_wq(q);
  2058. blkcg_deactivate_policy(q, &blkcg_policy_throtl);
  2059. free_percpu(q->td->latency_buckets[READ]);
  2060. free_percpu(q->td->latency_buckets[WRITE]);
  2061. kfree(q->td);
  2062. }
  2063. void blk_throtl_register_queue(struct request_queue *q)
  2064. {
  2065. struct throtl_data *td;
  2066. int i;
  2067. td = q->td;
  2068. BUG_ON(!td);
  2069. if (blk_queue_nonrot(q)) {
  2070. td->throtl_slice = DFL_THROTL_SLICE_SSD;
  2071. td->filtered_latency = LATENCY_FILTERED_SSD;
  2072. } else {
  2073. td->throtl_slice = DFL_THROTL_SLICE_HD;
  2074. td->filtered_latency = LATENCY_FILTERED_HD;
  2075. for (i = 0; i < LATENCY_BUCKET_SIZE; i++) {
  2076. td->avg_buckets[READ][i].latency = DFL_HD_BASELINE_LATENCY;
  2077. td->avg_buckets[WRITE][i].latency = DFL_HD_BASELINE_LATENCY;
  2078. }
  2079. }
  2080. #ifndef CONFIG_BLK_DEV_THROTTLING_LOW
  2081. /* if no low limit, use previous default */
  2082. td->throtl_slice = DFL_THROTL_SLICE_HD;
  2083. #endif
  2084. td->track_bio_latency = !queue_is_rq_based(q);
  2085. if (!td->track_bio_latency)
  2086. blk_stat_enable_accounting(q);
  2087. }
  2088. #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
  2089. ssize_t blk_throtl_sample_time_show(struct request_queue *q, char *page)
  2090. {
  2091. if (!q->td)
  2092. return -EINVAL;
  2093. return sprintf(page, "%u\n", jiffies_to_msecs(q->td->throtl_slice));
  2094. }
  2095. ssize_t blk_throtl_sample_time_store(struct request_queue *q,
  2096. const char *page, size_t count)
  2097. {
  2098. unsigned long v;
  2099. unsigned long t;
  2100. if (!q->td)
  2101. return -EINVAL;
  2102. if (kstrtoul(page, 10, &v))
  2103. return -EINVAL;
  2104. t = msecs_to_jiffies(v);
  2105. if (t == 0 || t > MAX_THROTL_SLICE)
  2106. return -EINVAL;
  2107. q->td->throtl_slice = t;
  2108. return count;
  2109. }
  2110. #endif
  2111. static int __init throtl_init(void)
  2112. {
  2113. kthrotld_workqueue = alloc_workqueue("kthrotld", WQ_MEM_RECLAIM, 0);
  2114. if (!kthrotld_workqueue)
  2115. panic("Failed to create kthrotld\n");
  2116. return blkcg_policy_register(&blkcg_policy_throtl);
  2117. }
  2118. module_init(throtl_init);