blk-throttle.c 69 KB

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