blk-throttle.c 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486
  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. #define SKIP_LATENCY (((u64)1) << BLK_STAT_RES_SHIFT)
  35. static struct blkcg_policy blkcg_policy_throtl;
  36. /* A workqueue to queue throttle related work */
  37. static struct workqueue_struct *kthrotld_workqueue;
  38. /*
  39. * To implement hierarchical throttling, throtl_grps form a tree and bios
  40. * are dispatched upwards level by level until they reach the top and get
  41. * issued. When dispatching bios from the children and local group at each
  42. * level, if the bios are dispatched into a single bio_list, there's a risk
  43. * of a local or child group which can queue many bios at once filling up
  44. * the list starving others.
  45. *
  46. * To avoid such starvation, dispatched bios are queued separately
  47. * according to where they came from. When they are again dispatched to
  48. * the parent, they're popped in round-robin order so that no single source
  49. * hogs the dispatch window.
  50. *
  51. * throtl_qnode is used to keep the queued bios separated by their sources.
  52. * Bios are queued to throtl_qnode which in turn is queued to
  53. * throtl_service_queue and then dispatched in round-robin order.
  54. *
  55. * It's also used to track the reference counts on blkg's. A qnode always
  56. * belongs to a throtl_grp and gets queued on itself or the parent, so
  57. * incrementing the reference of the associated throtl_grp when a qnode is
  58. * queued and decrementing when dequeued is enough to keep the whole blkg
  59. * tree pinned while bios are in flight.
  60. */
  61. struct throtl_qnode {
  62. struct list_head node; /* service_queue->queued[] */
  63. struct bio_list bios; /* queued bios */
  64. struct throtl_grp *tg; /* tg this qnode belongs to */
  65. };
  66. struct throtl_service_queue {
  67. struct throtl_service_queue *parent_sq; /* the parent service_queue */
  68. /*
  69. * Bios queued directly to this service_queue or dispatched from
  70. * children throtl_grp's.
  71. */
  72. struct list_head queued[2]; /* throtl_qnode [READ/WRITE] */
  73. unsigned int nr_queued[2]; /* number of queued bios */
  74. /*
  75. * RB tree of active children throtl_grp's, which are sorted by
  76. * their ->disptime.
  77. */
  78. struct rb_root pending_tree; /* RB tree of active tgs */
  79. struct rb_node *first_pending; /* first node in the tree */
  80. unsigned int nr_pending; /* # queued in the tree */
  81. unsigned long first_pending_disptime; /* disptime of the first tg */
  82. struct timer_list pending_timer; /* fires on first_pending_disptime */
  83. };
  84. enum tg_state_flags {
  85. THROTL_TG_PENDING = 1 << 0, /* on parent's pending tree */
  86. THROTL_TG_WAS_EMPTY = 1 << 1, /* bio_lists[] became non-empty */
  87. };
  88. #define rb_entry_tg(node) rb_entry((node), struct throtl_grp, rb_node)
  89. enum {
  90. LIMIT_LOW,
  91. LIMIT_MAX,
  92. LIMIT_CNT,
  93. };
  94. struct throtl_grp {
  95. /* must be the first member */
  96. struct blkg_policy_data pd;
  97. /* active throtl group service_queue member */
  98. struct rb_node rb_node;
  99. /* throtl_data this group belongs to */
  100. struct throtl_data *td;
  101. /* this group's service queue */
  102. struct throtl_service_queue service_queue;
  103. /*
  104. * qnode_on_self is used when bios are directly queued to this
  105. * throtl_grp so that local bios compete fairly with bios
  106. * dispatched from children. qnode_on_parent is used when bios are
  107. * dispatched from this throtl_grp into its parent and will compete
  108. * with the sibling qnode_on_parents and the parent's
  109. * qnode_on_self.
  110. */
  111. struct throtl_qnode qnode_on_self[2];
  112. struct throtl_qnode qnode_on_parent[2];
  113. /*
  114. * Dispatch time in jiffies. This is the estimated time when group
  115. * will unthrottle and is ready to dispatch more bio. It is used as
  116. * key to sort active groups in service tree.
  117. */
  118. unsigned long disptime;
  119. unsigned int flags;
  120. /* are there any throtl rules between this group and td? */
  121. bool has_rules[2];
  122. /* internally used bytes per second rate limits */
  123. uint64_t bps[2][LIMIT_CNT];
  124. /* user configured bps limits */
  125. uint64_t bps_conf[2][LIMIT_CNT];
  126. /* internally used IOPS limits */
  127. unsigned int iops[2][LIMIT_CNT];
  128. /* user configured IOPS limits */
  129. unsigned int iops_conf[2][LIMIT_CNT];
  130. /* Number of bytes disptached in current slice */
  131. uint64_t bytes_disp[2];
  132. /* Number of bio's dispatched in current slice */
  133. unsigned int io_disp[2];
  134. unsigned long last_low_overflow_time[2];
  135. uint64_t last_bytes_disp[2];
  136. unsigned int last_io_disp[2];
  137. unsigned long last_check_time;
  138. unsigned long latency_target; /* us */
  139. unsigned long latency_target_conf; /* us */
  140. /* When did we start a new slice */
  141. unsigned long slice_start[2];
  142. unsigned long slice_end[2];
  143. unsigned long last_finish_time; /* ns / 1024 */
  144. unsigned long checked_last_finish_time; /* ns / 1024 */
  145. unsigned long avg_idletime; /* ns / 1024 */
  146. unsigned long idletime_threshold; /* us */
  147. unsigned long idletime_threshold_conf; /* us */
  148. unsigned int bio_cnt; /* total bios */
  149. unsigned int bad_bio_cnt; /* bios exceeding latency threshold */
  150. unsigned long bio_cnt_reset_time;
  151. };
  152. /* We measure latency for request size from <= 4k to >= 1M */
  153. #define LATENCY_BUCKET_SIZE 9
  154. struct latency_bucket {
  155. unsigned long total_latency; /* ns / 1024 */
  156. int samples;
  157. };
  158. struct avg_latency_bucket {
  159. unsigned long latency; /* ns / 1024 */
  160. bool valid;
  161. };
  162. struct throtl_data
  163. {
  164. /* service tree for active throtl groups */
  165. struct throtl_service_queue service_queue;
  166. struct request_queue *queue;
  167. /* Total Number of queued bios on READ and WRITE lists */
  168. unsigned int nr_queued[2];
  169. unsigned int throtl_slice;
  170. /* Work for dispatching throttled bios */
  171. struct work_struct dispatch_work;
  172. unsigned int limit_index;
  173. bool limit_valid[LIMIT_CNT];
  174. unsigned long low_upgrade_time;
  175. unsigned long low_downgrade_time;
  176. unsigned int scale;
  177. struct latency_bucket tmp_buckets[LATENCY_BUCKET_SIZE];
  178. struct avg_latency_bucket avg_buckets[LATENCY_BUCKET_SIZE];
  179. struct latency_bucket __percpu *latency_buckets;
  180. unsigned long last_calculate_time;
  181. unsigned long filtered_latency;
  182. bool track_bio_latency;
  183. };
  184. static void throtl_pending_timer_fn(unsigned long arg);
  185. static inline struct throtl_grp *pd_to_tg(struct blkg_policy_data *pd)
  186. {
  187. return pd ? container_of(pd, struct throtl_grp, pd) : NULL;
  188. }
  189. static inline struct throtl_grp *blkg_to_tg(struct blkcg_gq *blkg)
  190. {
  191. return pd_to_tg(blkg_to_pd(blkg, &blkcg_policy_throtl));
  192. }
  193. static inline struct blkcg_gq *tg_to_blkg(struct throtl_grp *tg)
  194. {
  195. return pd_to_blkg(&tg->pd);
  196. }
  197. /**
  198. * sq_to_tg - return the throl_grp the specified service queue belongs to
  199. * @sq: the throtl_service_queue of interest
  200. *
  201. * Return the throtl_grp @sq belongs to. If @sq is the top-level one
  202. * embedded in throtl_data, %NULL is returned.
  203. */
  204. static struct throtl_grp *sq_to_tg(struct throtl_service_queue *sq)
  205. {
  206. if (sq && sq->parent_sq)
  207. return container_of(sq, struct throtl_grp, service_queue);
  208. else
  209. return NULL;
  210. }
  211. /**
  212. * sq_to_td - return throtl_data the specified service queue belongs to
  213. * @sq: the throtl_service_queue of interest
  214. *
  215. * A service_queue can be embedded in either a throtl_grp or throtl_data.
  216. * Determine the associated throtl_data accordingly and return it.
  217. */
  218. static struct throtl_data *sq_to_td(struct throtl_service_queue *sq)
  219. {
  220. struct throtl_grp *tg = sq_to_tg(sq);
  221. if (tg)
  222. return tg->td;
  223. else
  224. return container_of(sq, struct throtl_data, service_queue);
  225. }
  226. /*
  227. * cgroup's limit in LIMIT_MAX is scaled if low limit is set. This scale is to
  228. * make the IO dispatch more smooth.
  229. * Scale up: linearly scale up according to lapsed time since upgrade. For
  230. * every throtl_slice, the limit scales up 1/2 .low limit till the
  231. * limit hits .max limit
  232. * Scale down: exponentially scale down if a cgroup doesn't hit its .low limit
  233. */
  234. static uint64_t throtl_adjusted_limit(uint64_t low, struct throtl_data *td)
  235. {
  236. /* arbitrary value to avoid too big scale */
  237. if (td->scale < 4096 && time_after_eq(jiffies,
  238. td->low_upgrade_time + td->scale * td->throtl_slice))
  239. td->scale = (jiffies - td->low_upgrade_time) / td->throtl_slice;
  240. return low + (low >> 1) * td->scale;
  241. }
  242. static uint64_t tg_bps_limit(struct throtl_grp *tg, int rw)
  243. {
  244. struct blkcg_gq *blkg = tg_to_blkg(tg);
  245. struct throtl_data *td;
  246. uint64_t ret;
  247. if (cgroup_subsys_on_dfl(io_cgrp_subsys) && !blkg->parent)
  248. return U64_MAX;
  249. td = tg->td;
  250. ret = tg->bps[rw][td->limit_index];
  251. if (ret == 0 && td->limit_index == LIMIT_LOW) {
  252. /* intermediate node or iops isn't 0 */
  253. if (!list_empty(&blkg->blkcg->css.children) ||
  254. tg->iops[rw][td->limit_index])
  255. return U64_MAX;
  256. else
  257. return MIN_THROTL_BPS;
  258. }
  259. if (td->limit_index == LIMIT_MAX && tg->bps[rw][LIMIT_LOW] &&
  260. tg->bps[rw][LIMIT_LOW] != tg->bps[rw][LIMIT_MAX]) {
  261. uint64_t adjusted;
  262. adjusted = throtl_adjusted_limit(tg->bps[rw][LIMIT_LOW], td);
  263. ret = min(tg->bps[rw][LIMIT_MAX], adjusted);
  264. }
  265. return ret;
  266. }
  267. static unsigned int tg_iops_limit(struct throtl_grp *tg, int rw)
  268. {
  269. struct blkcg_gq *blkg = tg_to_blkg(tg);
  270. struct throtl_data *td;
  271. unsigned int ret;
  272. if (cgroup_subsys_on_dfl(io_cgrp_subsys) && !blkg->parent)
  273. return UINT_MAX;
  274. td = tg->td;
  275. ret = tg->iops[rw][td->limit_index];
  276. if (ret == 0 && tg->td->limit_index == LIMIT_LOW) {
  277. /* intermediate node or bps isn't 0 */
  278. if (!list_empty(&blkg->blkcg->css.children) ||
  279. tg->bps[rw][td->limit_index])
  280. return UINT_MAX;
  281. else
  282. return MIN_THROTL_IOPS;
  283. }
  284. if (td->limit_index == LIMIT_MAX && tg->iops[rw][LIMIT_LOW] &&
  285. tg->iops[rw][LIMIT_LOW] != tg->iops[rw][LIMIT_MAX]) {
  286. uint64_t adjusted;
  287. adjusted = throtl_adjusted_limit(tg->iops[rw][LIMIT_LOW], td);
  288. if (adjusted > UINT_MAX)
  289. adjusted = UINT_MAX;
  290. ret = min_t(unsigned int, tg->iops[rw][LIMIT_MAX], adjusted);
  291. }
  292. return ret;
  293. }
  294. #define request_bucket_index(sectors) \
  295. clamp_t(int, order_base_2(sectors) - 3, 0, LATENCY_BUCKET_SIZE - 1)
  296. /**
  297. * throtl_log - log debug message via blktrace
  298. * @sq: the service_queue being reported
  299. * @fmt: printf format string
  300. * @args: printf args
  301. *
  302. * The messages are prefixed with "throtl BLKG_NAME" if @sq belongs to a
  303. * throtl_grp; otherwise, just "throtl".
  304. */
  305. #define throtl_log(sq, fmt, args...) do { \
  306. struct throtl_grp *__tg = sq_to_tg((sq)); \
  307. struct throtl_data *__td = sq_to_td((sq)); \
  308. \
  309. (void)__td; \
  310. if (likely(!blk_trace_note_message_enabled(__td->queue))) \
  311. break; \
  312. if ((__tg)) { \
  313. blk_add_cgroup_trace_msg(__td->queue, \
  314. tg_to_blkg(__tg)->blkcg, "throtl " fmt, ##args);\
  315. } else { \
  316. blk_add_trace_msg(__td->queue, "throtl " fmt, ##args); \
  317. } \
  318. } while (0)
  319. static inline unsigned int throtl_bio_data_size(struct bio *bio)
  320. {
  321. /* assume it's one sector */
  322. if (unlikely(bio_op(bio) == REQ_OP_DISCARD))
  323. return 512;
  324. return bio->bi_iter.bi_size;
  325. }
  326. static void throtl_qnode_init(struct throtl_qnode *qn, struct throtl_grp *tg)
  327. {
  328. INIT_LIST_HEAD(&qn->node);
  329. bio_list_init(&qn->bios);
  330. qn->tg = tg;
  331. }
  332. /**
  333. * throtl_qnode_add_bio - add a bio to a throtl_qnode and activate it
  334. * @bio: bio being added
  335. * @qn: qnode to add bio to
  336. * @queued: the service_queue->queued[] list @qn belongs to
  337. *
  338. * Add @bio to @qn and put @qn on @queued if it's not already on.
  339. * @qn->tg's reference count is bumped when @qn is activated. See the
  340. * comment on top of throtl_qnode definition for details.
  341. */
  342. static void throtl_qnode_add_bio(struct bio *bio, struct throtl_qnode *qn,
  343. struct list_head *queued)
  344. {
  345. bio_list_add(&qn->bios, bio);
  346. if (list_empty(&qn->node)) {
  347. list_add_tail(&qn->node, queued);
  348. blkg_get(tg_to_blkg(qn->tg));
  349. }
  350. }
  351. /**
  352. * throtl_peek_queued - peek the first bio on a qnode list
  353. * @queued: the qnode list to peek
  354. */
  355. static struct bio *throtl_peek_queued(struct list_head *queued)
  356. {
  357. struct throtl_qnode *qn = list_first_entry(queued, struct throtl_qnode, node);
  358. struct bio *bio;
  359. if (list_empty(queued))
  360. return NULL;
  361. bio = bio_list_peek(&qn->bios);
  362. WARN_ON_ONCE(!bio);
  363. return bio;
  364. }
  365. /**
  366. * throtl_pop_queued - pop the first bio form a qnode list
  367. * @queued: the qnode list to pop a bio from
  368. * @tg_to_put: optional out argument for throtl_grp to put
  369. *
  370. * Pop the first bio from the qnode list @queued. After popping, the first
  371. * qnode is removed from @queued if empty or moved to the end of @queued so
  372. * that the popping order is round-robin.
  373. *
  374. * When the first qnode is removed, its associated throtl_grp should be put
  375. * too. If @tg_to_put is NULL, this function automatically puts it;
  376. * otherwise, *@tg_to_put is set to the throtl_grp to put and the caller is
  377. * responsible for putting it.
  378. */
  379. static struct bio *throtl_pop_queued(struct list_head *queued,
  380. struct throtl_grp **tg_to_put)
  381. {
  382. struct throtl_qnode *qn = list_first_entry(queued, struct throtl_qnode, node);
  383. struct bio *bio;
  384. if (list_empty(queued))
  385. return NULL;
  386. bio = bio_list_pop(&qn->bios);
  387. WARN_ON_ONCE(!bio);
  388. if (bio_list_empty(&qn->bios)) {
  389. list_del_init(&qn->node);
  390. if (tg_to_put)
  391. *tg_to_put = qn->tg;
  392. else
  393. blkg_put(tg_to_blkg(qn->tg));
  394. } else {
  395. list_move_tail(&qn->node, queued);
  396. }
  397. return bio;
  398. }
  399. /* init a service_queue, assumes the caller zeroed it */
  400. static void throtl_service_queue_init(struct throtl_service_queue *sq)
  401. {
  402. INIT_LIST_HEAD(&sq->queued[0]);
  403. INIT_LIST_HEAD(&sq->queued[1]);
  404. sq->pending_tree = RB_ROOT;
  405. setup_timer(&sq->pending_timer, throtl_pending_timer_fn,
  406. (unsigned long)sq);
  407. }
  408. static struct blkg_policy_data *throtl_pd_alloc(gfp_t gfp, int node)
  409. {
  410. struct throtl_grp *tg;
  411. int rw;
  412. tg = kzalloc_node(sizeof(*tg), gfp, node);
  413. if (!tg)
  414. return NULL;
  415. throtl_service_queue_init(&tg->service_queue);
  416. for (rw = READ; rw <= WRITE; rw++) {
  417. throtl_qnode_init(&tg->qnode_on_self[rw], tg);
  418. throtl_qnode_init(&tg->qnode_on_parent[rw], tg);
  419. }
  420. RB_CLEAR_NODE(&tg->rb_node);
  421. tg->bps[READ][LIMIT_MAX] = U64_MAX;
  422. tg->bps[WRITE][LIMIT_MAX] = U64_MAX;
  423. tg->iops[READ][LIMIT_MAX] = UINT_MAX;
  424. tg->iops[WRITE][LIMIT_MAX] = UINT_MAX;
  425. tg->bps_conf[READ][LIMIT_MAX] = U64_MAX;
  426. tg->bps_conf[WRITE][LIMIT_MAX] = U64_MAX;
  427. tg->iops_conf[READ][LIMIT_MAX] = UINT_MAX;
  428. tg->iops_conf[WRITE][LIMIT_MAX] = UINT_MAX;
  429. /* LIMIT_LOW will have default value 0 */
  430. tg->latency_target = DFL_LATENCY_TARGET;
  431. tg->latency_target_conf = DFL_LATENCY_TARGET;
  432. tg->idletime_threshold = DFL_IDLE_THRESHOLD;
  433. tg->idletime_threshold_conf = DFL_IDLE_THRESHOLD;
  434. return &tg->pd;
  435. }
  436. static void throtl_pd_init(struct blkg_policy_data *pd)
  437. {
  438. struct throtl_grp *tg = pd_to_tg(pd);
  439. struct blkcg_gq *blkg = tg_to_blkg(tg);
  440. struct throtl_data *td = blkg->q->td;
  441. struct throtl_service_queue *sq = &tg->service_queue;
  442. /*
  443. * If on the default hierarchy, we switch to properly hierarchical
  444. * behavior where limits on a given throtl_grp are applied to the
  445. * whole subtree rather than just the group itself. e.g. If 16M
  446. * read_bps limit is set on the root group, the whole system can't
  447. * exceed 16M for the device.
  448. *
  449. * If not on the default hierarchy, the broken flat hierarchy
  450. * behavior is retained where all throtl_grps are treated as if
  451. * they're all separate root groups right below throtl_data.
  452. * Limits of a group don't interact with limits of other groups
  453. * regardless of the position of the group in the hierarchy.
  454. */
  455. sq->parent_sq = &td->service_queue;
  456. if (cgroup_subsys_on_dfl(io_cgrp_subsys) && blkg->parent)
  457. sq->parent_sq = &blkg_to_tg(blkg->parent)->service_queue;
  458. tg->td = td;
  459. }
  460. /*
  461. * Set has_rules[] if @tg or any of its parents have limits configured.
  462. * This doesn't require walking up to the top of the hierarchy as the
  463. * parent's has_rules[] is guaranteed to be correct.
  464. */
  465. static void tg_update_has_rules(struct throtl_grp *tg)
  466. {
  467. struct throtl_grp *parent_tg = sq_to_tg(tg->service_queue.parent_sq);
  468. struct throtl_data *td = tg->td;
  469. int rw;
  470. for (rw = READ; rw <= WRITE; rw++)
  471. tg->has_rules[rw] = (parent_tg && parent_tg->has_rules[rw]) ||
  472. (td->limit_valid[td->limit_index] &&
  473. (tg_bps_limit(tg, rw) != U64_MAX ||
  474. tg_iops_limit(tg, rw) != UINT_MAX));
  475. }
  476. static void throtl_pd_online(struct blkg_policy_data *pd)
  477. {
  478. struct throtl_grp *tg = pd_to_tg(pd);
  479. /*
  480. * We don't want new groups to escape the limits of its ancestors.
  481. * Update has_rules[] after a new group is brought online.
  482. */
  483. tg_update_has_rules(tg);
  484. }
  485. static void blk_throtl_update_limit_valid(struct throtl_data *td)
  486. {
  487. struct cgroup_subsys_state *pos_css;
  488. struct blkcg_gq *blkg;
  489. bool low_valid = false;
  490. rcu_read_lock();
  491. blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg) {
  492. struct throtl_grp *tg = blkg_to_tg(blkg);
  493. if (tg->bps[READ][LIMIT_LOW] || tg->bps[WRITE][LIMIT_LOW] ||
  494. tg->iops[READ][LIMIT_LOW] || tg->iops[WRITE][LIMIT_LOW])
  495. low_valid = true;
  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 1;
  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 = jiffy_elapsed_rnd = jiffies - tg->slice_start[rw];
  751. /* Slice has just started. Consider one slice interval */
  752. if (!jiffy_elapsed)
  753. jiffy_elapsed_rnd = tg->td->throtl_slice;
  754. jiffy_elapsed_rnd = roundup(jiffy_elapsed_rnd, tg->td->throtl_slice);
  755. /*
  756. * jiffy_elapsed_rnd should not be a big value as minimum iops can be
  757. * 1 then at max jiffy elapsed should be equivalent of 1 second as we
  758. * will allow dispatch after 1 second and after that slice should
  759. * have been trimmed.
  760. */
  761. tmp = (u64)tg_iops_limit(tg, rw) * jiffy_elapsed_rnd;
  762. do_div(tmp, HZ);
  763. if (tmp > UINT_MAX)
  764. io_allowed = UINT_MAX;
  765. else
  766. io_allowed = tmp;
  767. if (tg->io_disp[rw] + 1 <= io_allowed) {
  768. if (wait)
  769. *wait = 0;
  770. return true;
  771. }
  772. /* Calc approx time to dispatch */
  773. jiffy_wait = ((tg->io_disp[rw] + 1) * HZ) / tg_iops_limit(tg, rw) + 1;
  774. if (jiffy_wait > jiffy_elapsed)
  775. jiffy_wait = jiffy_wait - jiffy_elapsed;
  776. else
  777. jiffy_wait = 1;
  778. if (wait)
  779. *wait = jiffy_wait;
  780. return 0;
  781. }
  782. static bool tg_with_in_bps_limit(struct throtl_grp *tg, struct bio *bio,
  783. unsigned long *wait)
  784. {
  785. bool rw = bio_data_dir(bio);
  786. u64 bytes_allowed, extra_bytes, tmp;
  787. unsigned long jiffy_elapsed, jiffy_wait, jiffy_elapsed_rnd;
  788. unsigned int bio_size = throtl_bio_data_size(bio);
  789. jiffy_elapsed = jiffy_elapsed_rnd = jiffies - tg->slice_start[rw];
  790. /* Slice has just started. Consider one slice interval */
  791. if (!jiffy_elapsed)
  792. jiffy_elapsed_rnd = tg->td->throtl_slice;
  793. jiffy_elapsed_rnd = roundup(jiffy_elapsed_rnd, tg->td->throtl_slice);
  794. tmp = tg_bps_limit(tg, rw) * jiffy_elapsed_rnd;
  795. do_div(tmp, HZ);
  796. bytes_allowed = tmp;
  797. if (tg->bytes_disp[rw] + bio_size <= bytes_allowed) {
  798. if (wait)
  799. *wait = 0;
  800. return true;
  801. }
  802. /* Calc approx time to dispatch */
  803. extra_bytes = tg->bytes_disp[rw] + bio_size - bytes_allowed;
  804. jiffy_wait = div64_u64(extra_bytes * HZ, tg_bps_limit(tg, rw));
  805. if (!jiffy_wait)
  806. jiffy_wait = 1;
  807. /*
  808. * This wait time is without taking into consideration the rounding
  809. * up we did. Add that time also.
  810. */
  811. jiffy_wait = jiffy_wait + (jiffy_elapsed_rnd - jiffy_elapsed);
  812. if (wait)
  813. *wait = jiffy_wait;
  814. return 0;
  815. }
  816. /*
  817. * Returns whether one can dispatch a bio or not. Also returns approx number
  818. * of jiffies to wait before this bio is with-in IO rate and can be dispatched
  819. */
  820. static bool tg_may_dispatch(struct throtl_grp *tg, struct bio *bio,
  821. unsigned long *wait)
  822. {
  823. bool rw = bio_data_dir(bio);
  824. unsigned long bps_wait = 0, iops_wait = 0, max_wait = 0;
  825. /*
  826. * Currently whole state machine of group depends on first bio
  827. * queued in the group bio list. So one should not be calling
  828. * this function with a different bio if there are other bios
  829. * queued.
  830. */
  831. BUG_ON(tg->service_queue.nr_queued[rw] &&
  832. bio != throtl_peek_queued(&tg->service_queue.queued[rw]));
  833. /* If tg->bps = -1, then BW is unlimited */
  834. if (tg_bps_limit(tg, rw) == U64_MAX &&
  835. tg_iops_limit(tg, rw) == UINT_MAX) {
  836. if (wait)
  837. *wait = 0;
  838. return true;
  839. }
  840. /*
  841. * If previous slice expired, start a new one otherwise renew/extend
  842. * existing slice to make sure it is at least throtl_slice interval
  843. * long since now. New slice is started only for empty throttle group.
  844. * If there is queued bio, that means there should be an active
  845. * slice and it should be extended instead.
  846. */
  847. if (throtl_slice_used(tg, rw) && !(tg->service_queue.nr_queued[rw]))
  848. throtl_start_new_slice(tg, rw);
  849. else {
  850. if (time_before(tg->slice_end[rw],
  851. jiffies + tg->td->throtl_slice))
  852. throtl_extend_slice(tg, rw,
  853. jiffies + tg->td->throtl_slice);
  854. }
  855. if (tg_with_in_bps_limit(tg, bio, &bps_wait) &&
  856. tg_with_in_iops_limit(tg, bio, &iops_wait)) {
  857. if (wait)
  858. *wait = 0;
  859. return 1;
  860. }
  861. max_wait = max(bps_wait, iops_wait);
  862. if (wait)
  863. *wait = max_wait;
  864. if (time_before(tg->slice_end[rw], jiffies + max_wait))
  865. throtl_extend_slice(tg, rw, jiffies + max_wait);
  866. return 0;
  867. }
  868. static void throtl_charge_bio(struct throtl_grp *tg, struct bio *bio)
  869. {
  870. bool rw = bio_data_dir(bio);
  871. unsigned int bio_size = throtl_bio_data_size(bio);
  872. /* Charge the bio to the group */
  873. tg->bytes_disp[rw] += bio_size;
  874. tg->io_disp[rw]++;
  875. tg->last_bytes_disp[rw] += bio_size;
  876. tg->last_io_disp[rw]++;
  877. /*
  878. * BIO_THROTTLED is used to prevent the same bio to be throttled
  879. * more than once as a throttled bio will go through blk-throtl the
  880. * second time when it eventually gets issued. Set it when a bio
  881. * is being charged to a tg.
  882. */
  883. if (!bio_flagged(bio, BIO_THROTTLED))
  884. bio_set_flag(bio, BIO_THROTTLED);
  885. }
  886. /**
  887. * throtl_add_bio_tg - add a bio to the specified throtl_grp
  888. * @bio: bio to add
  889. * @qn: qnode to use
  890. * @tg: the target throtl_grp
  891. *
  892. * Add @bio to @tg's service_queue using @qn. If @qn is not specified,
  893. * tg->qnode_on_self[] is used.
  894. */
  895. static void throtl_add_bio_tg(struct bio *bio, struct throtl_qnode *qn,
  896. struct throtl_grp *tg)
  897. {
  898. struct throtl_service_queue *sq = &tg->service_queue;
  899. bool rw = bio_data_dir(bio);
  900. if (!qn)
  901. qn = &tg->qnode_on_self[rw];
  902. /*
  903. * If @tg doesn't currently have any bios queued in the same
  904. * direction, queueing @bio can change when @tg should be
  905. * dispatched. Mark that @tg was empty. This is automatically
  906. * cleaered on the next tg_update_disptime().
  907. */
  908. if (!sq->nr_queued[rw])
  909. tg->flags |= THROTL_TG_WAS_EMPTY;
  910. throtl_qnode_add_bio(bio, qn, &sq->queued[rw]);
  911. sq->nr_queued[rw]++;
  912. throtl_enqueue_tg(tg);
  913. }
  914. static void tg_update_disptime(struct throtl_grp *tg)
  915. {
  916. struct throtl_service_queue *sq = &tg->service_queue;
  917. unsigned long read_wait = -1, write_wait = -1, min_wait = -1, disptime;
  918. struct bio *bio;
  919. bio = throtl_peek_queued(&sq->queued[READ]);
  920. if (bio)
  921. tg_may_dispatch(tg, bio, &read_wait);
  922. bio = throtl_peek_queued(&sq->queued[WRITE]);
  923. if (bio)
  924. tg_may_dispatch(tg, bio, &write_wait);
  925. min_wait = min(read_wait, write_wait);
  926. disptime = jiffies + min_wait;
  927. /* Update dispatch time */
  928. throtl_dequeue_tg(tg);
  929. tg->disptime = disptime;
  930. throtl_enqueue_tg(tg);
  931. /* see throtl_add_bio_tg() */
  932. tg->flags &= ~THROTL_TG_WAS_EMPTY;
  933. }
  934. static void start_parent_slice_with_credit(struct throtl_grp *child_tg,
  935. struct throtl_grp *parent_tg, bool rw)
  936. {
  937. if (throtl_slice_used(parent_tg, rw)) {
  938. throtl_start_new_slice_with_credit(parent_tg, rw,
  939. child_tg->slice_start[rw]);
  940. }
  941. }
  942. static void tg_dispatch_one_bio(struct throtl_grp *tg, bool rw)
  943. {
  944. struct throtl_service_queue *sq = &tg->service_queue;
  945. struct throtl_service_queue *parent_sq = sq->parent_sq;
  946. struct throtl_grp *parent_tg = sq_to_tg(parent_sq);
  947. struct throtl_grp *tg_to_put = NULL;
  948. struct bio *bio;
  949. /*
  950. * @bio is being transferred from @tg to @parent_sq. Popping a bio
  951. * from @tg may put its reference and @parent_sq might end up
  952. * getting released prematurely. Remember the tg to put and put it
  953. * after @bio is transferred to @parent_sq.
  954. */
  955. bio = throtl_pop_queued(&sq->queued[rw], &tg_to_put);
  956. sq->nr_queued[rw]--;
  957. throtl_charge_bio(tg, bio);
  958. /*
  959. * If our parent is another tg, we just need to transfer @bio to
  960. * the parent using throtl_add_bio_tg(). If our parent is
  961. * @td->service_queue, @bio is ready to be issued. Put it on its
  962. * bio_lists[] and decrease total number queued. The caller is
  963. * responsible for issuing these bios.
  964. */
  965. if (parent_tg) {
  966. throtl_add_bio_tg(bio, &tg->qnode_on_parent[rw], parent_tg);
  967. start_parent_slice_with_credit(tg, parent_tg, rw);
  968. } else {
  969. throtl_qnode_add_bio(bio, &tg->qnode_on_parent[rw],
  970. &parent_sq->queued[rw]);
  971. BUG_ON(tg->td->nr_queued[rw] <= 0);
  972. tg->td->nr_queued[rw]--;
  973. }
  974. throtl_trim_slice(tg, rw);
  975. if (tg_to_put)
  976. blkg_put(tg_to_blkg(tg_to_put));
  977. }
  978. static int throtl_dispatch_tg(struct throtl_grp *tg)
  979. {
  980. struct throtl_service_queue *sq = &tg->service_queue;
  981. unsigned int nr_reads = 0, nr_writes = 0;
  982. unsigned int max_nr_reads = throtl_grp_quantum*3/4;
  983. unsigned int max_nr_writes = throtl_grp_quantum - max_nr_reads;
  984. struct bio *bio;
  985. /* Try to dispatch 75% READS and 25% WRITES */
  986. while ((bio = throtl_peek_queued(&sq->queued[READ])) &&
  987. tg_may_dispatch(tg, bio, NULL)) {
  988. tg_dispatch_one_bio(tg, bio_data_dir(bio));
  989. nr_reads++;
  990. if (nr_reads >= max_nr_reads)
  991. break;
  992. }
  993. while ((bio = throtl_peek_queued(&sq->queued[WRITE])) &&
  994. tg_may_dispatch(tg, bio, NULL)) {
  995. tg_dispatch_one_bio(tg, bio_data_dir(bio));
  996. nr_writes++;
  997. if (nr_writes >= max_nr_writes)
  998. break;
  999. }
  1000. return nr_reads + nr_writes;
  1001. }
  1002. static int throtl_select_dispatch(struct throtl_service_queue *parent_sq)
  1003. {
  1004. unsigned int nr_disp = 0;
  1005. while (1) {
  1006. struct throtl_grp *tg = throtl_rb_first(parent_sq);
  1007. struct throtl_service_queue *sq = &tg->service_queue;
  1008. if (!tg)
  1009. break;
  1010. if (time_before(jiffies, tg->disptime))
  1011. break;
  1012. throtl_dequeue_tg(tg);
  1013. nr_disp += throtl_dispatch_tg(tg);
  1014. if (sq->nr_queued[0] || sq->nr_queued[1])
  1015. tg_update_disptime(tg);
  1016. if (nr_disp >= throtl_quantum)
  1017. break;
  1018. }
  1019. return nr_disp;
  1020. }
  1021. static bool throtl_can_upgrade(struct throtl_data *td,
  1022. struct throtl_grp *this_tg);
  1023. /**
  1024. * throtl_pending_timer_fn - timer function for service_queue->pending_timer
  1025. * @arg: the throtl_service_queue being serviced
  1026. *
  1027. * This timer is armed when a child throtl_grp with active bio's become
  1028. * pending and queued on the service_queue's pending_tree and expires when
  1029. * the first child throtl_grp should be dispatched. This function
  1030. * dispatches bio's from the children throtl_grps to the parent
  1031. * service_queue.
  1032. *
  1033. * If the parent's parent is another throtl_grp, dispatching is propagated
  1034. * by either arming its pending_timer or repeating dispatch directly. If
  1035. * the top-level service_tree is reached, throtl_data->dispatch_work is
  1036. * kicked so that the ready bio's are issued.
  1037. */
  1038. static void throtl_pending_timer_fn(unsigned long arg)
  1039. {
  1040. struct throtl_service_queue *sq = (void *)arg;
  1041. struct throtl_grp *tg = sq_to_tg(sq);
  1042. struct throtl_data *td = sq_to_td(sq);
  1043. struct request_queue *q = td->queue;
  1044. struct throtl_service_queue *parent_sq;
  1045. bool dispatched;
  1046. int ret;
  1047. spin_lock_irq(q->queue_lock);
  1048. if (throtl_can_upgrade(td, NULL))
  1049. throtl_upgrade_state(td);
  1050. again:
  1051. parent_sq = sq->parent_sq;
  1052. dispatched = false;
  1053. while (true) {
  1054. throtl_log(sq, "dispatch nr_queued=%u read=%u write=%u",
  1055. sq->nr_queued[READ] + sq->nr_queued[WRITE],
  1056. sq->nr_queued[READ], sq->nr_queued[WRITE]);
  1057. ret = throtl_select_dispatch(sq);
  1058. if (ret) {
  1059. throtl_log(sq, "bios disp=%u", ret);
  1060. dispatched = true;
  1061. }
  1062. if (throtl_schedule_next_dispatch(sq, false))
  1063. break;
  1064. /* this dispatch windows is still open, relax and repeat */
  1065. spin_unlock_irq(q->queue_lock);
  1066. cpu_relax();
  1067. spin_lock_irq(q->queue_lock);
  1068. }
  1069. if (!dispatched)
  1070. goto out_unlock;
  1071. if (parent_sq) {
  1072. /* @parent_sq is another throl_grp, propagate dispatch */
  1073. if (tg->flags & THROTL_TG_WAS_EMPTY) {
  1074. tg_update_disptime(tg);
  1075. if (!throtl_schedule_next_dispatch(parent_sq, false)) {
  1076. /* window is already open, repeat dispatching */
  1077. sq = parent_sq;
  1078. tg = sq_to_tg(sq);
  1079. goto again;
  1080. }
  1081. }
  1082. } else {
  1083. /* reached the top-level, queue issueing */
  1084. queue_work(kthrotld_workqueue, &td->dispatch_work);
  1085. }
  1086. out_unlock:
  1087. spin_unlock_irq(q->queue_lock);
  1088. }
  1089. /**
  1090. * blk_throtl_dispatch_work_fn - work function for throtl_data->dispatch_work
  1091. * @work: work item being executed
  1092. *
  1093. * This function is queued for execution when bio's reach the bio_lists[]
  1094. * of throtl_data->service_queue. Those bio's are ready and issued by this
  1095. * function.
  1096. */
  1097. static void blk_throtl_dispatch_work_fn(struct work_struct *work)
  1098. {
  1099. struct throtl_data *td = container_of(work, struct throtl_data,
  1100. dispatch_work);
  1101. struct throtl_service_queue *td_sq = &td->service_queue;
  1102. struct request_queue *q = td->queue;
  1103. struct bio_list bio_list_on_stack;
  1104. struct bio *bio;
  1105. struct blk_plug plug;
  1106. int rw;
  1107. bio_list_init(&bio_list_on_stack);
  1108. spin_lock_irq(q->queue_lock);
  1109. for (rw = READ; rw <= WRITE; rw++)
  1110. while ((bio = throtl_pop_queued(&td_sq->queued[rw], NULL)))
  1111. bio_list_add(&bio_list_on_stack, bio);
  1112. spin_unlock_irq(q->queue_lock);
  1113. if (!bio_list_empty(&bio_list_on_stack)) {
  1114. blk_start_plug(&plug);
  1115. while((bio = bio_list_pop(&bio_list_on_stack)))
  1116. generic_make_request(bio);
  1117. blk_finish_plug(&plug);
  1118. }
  1119. }
  1120. static u64 tg_prfill_conf_u64(struct seq_file *sf, struct blkg_policy_data *pd,
  1121. int off)
  1122. {
  1123. struct throtl_grp *tg = pd_to_tg(pd);
  1124. u64 v = *(u64 *)((void *)tg + off);
  1125. if (v == U64_MAX)
  1126. return 0;
  1127. return __blkg_prfill_u64(sf, pd, v);
  1128. }
  1129. static u64 tg_prfill_conf_uint(struct seq_file *sf, struct blkg_policy_data *pd,
  1130. int off)
  1131. {
  1132. struct throtl_grp *tg = pd_to_tg(pd);
  1133. unsigned int v = *(unsigned int *)((void *)tg + off);
  1134. if (v == UINT_MAX)
  1135. return 0;
  1136. return __blkg_prfill_u64(sf, pd, v);
  1137. }
  1138. static int tg_print_conf_u64(struct seq_file *sf, void *v)
  1139. {
  1140. blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_conf_u64,
  1141. &blkcg_policy_throtl, seq_cft(sf)->private, false);
  1142. return 0;
  1143. }
  1144. static int tg_print_conf_uint(struct seq_file *sf, void *v)
  1145. {
  1146. blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_conf_uint,
  1147. &blkcg_policy_throtl, seq_cft(sf)->private, false);
  1148. return 0;
  1149. }
  1150. static void tg_conf_updated(struct throtl_grp *tg, bool global)
  1151. {
  1152. struct throtl_service_queue *sq = &tg->service_queue;
  1153. struct cgroup_subsys_state *pos_css;
  1154. struct blkcg_gq *blkg;
  1155. throtl_log(&tg->service_queue,
  1156. "limit change rbps=%llu wbps=%llu riops=%u wiops=%u",
  1157. tg_bps_limit(tg, READ), tg_bps_limit(tg, WRITE),
  1158. tg_iops_limit(tg, READ), tg_iops_limit(tg, WRITE));
  1159. /*
  1160. * Update has_rules[] flags for the updated tg's subtree. A tg is
  1161. * considered to have rules if either the tg itself or any of its
  1162. * ancestors has rules. This identifies groups without any
  1163. * restrictions in the whole hierarchy and allows them to bypass
  1164. * blk-throttle.
  1165. */
  1166. blkg_for_each_descendant_pre(blkg, pos_css,
  1167. global ? tg->td->queue->root_blkg : tg_to_blkg(tg)) {
  1168. struct throtl_grp *this_tg = blkg_to_tg(blkg);
  1169. struct throtl_grp *parent_tg;
  1170. tg_update_has_rules(this_tg);
  1171. /* ignore root/second level */
  1172. if (!cgroup_subsys_on_dfl(io_cgrp_subsys) || !blkg->parent ||
  1173. !blkg->parent->parent)
  1174. continue;
  1175. parent_tg = blkg_to_tg(blkg->parent);
  1176. /*
  1177. * make sure all children has lower idle time threshold and
  1178. * higher latency target
  1179. */
  1180. this_tg->idletime_threshold = min(this_tg->idletime_threshold,
  1181. parent_tg->idletime_threshold);
  1182. this_tg->latency_target = max(this_tg->latency_target,
  1183. parent_tg->latency_target);
  1184. }
  1185. /*
  1186. * We're already holding queue_lock and know @tg is valid. Let's
  1187. * apply the new config directly.
  1188. *
  1189. * Restart the slices for both READ and WRITES. It might happen
  1190. * that a group's limit are dropped suddenly and we don't want to
  1191. * account recently dispatched IO with new low rate.
  1192. */
  1193. throtl_start_new_slice(tg, 0);
  1194. throtl_start_new_slice(tg, 1);
  1195. if (tg->flags & THROTL_TG_PENDING) {
  1196. tg_update_disptime(tg);
  1197. throtl_schedule_next_dispatch(sq->parent_sq, true);
  1198. }
  1199. }
  1200. static ssize_t tg_set_conf(struct kernfs_open_file *of,
  1201. char *buf, size_t nbytes, loff_t off, bool is_u64)
  1202. {
  1203. struct blkcg *blkcg = css_to_blkcg(of_css(of));
  1204. struct blkg_conf_ctx ctx;
  1205. struct throtl_grp *tg;
  1206. int ret;
  1207. u64 v;
  1208. ret = blkg_conf_prep(blkcg, &blkcg_policy_throtl, buf, &ctx);
  1209. if (ret)
  1210. return ret;
  1211. ret = -EINVAL;
  1212. if (sscanf(ctx.body, "%llu", &v) != 1)
  1213. goto out_finish;
  1214. if (!v)
  1215. v = U64_MAX;
  1216. tg = blkg_to_tg(ctx.blkg);
  1217. if (is_u64)
  1218. *(u64 *)((void *)tg + of_cft(of)->private) = v;
  1219. else
  1220. *(unsigned int *)((void *)tg + of_cft(of)->private) = v;
  1221. tg_conf_updated(tg, false);
  1222. ret = 0;
  1223. out_finish:
  1224. blkg_conf_finish(&ctx);
  1225. return ret ?: nbytes;
  1226. }
  1227. static ssize_t tg_set_conf_u64(struct kernfs_open_file *of,
  1228. char *buf, size_t nbytes, loff_t off)
  1229. {
  1230. return tg_set_conf(of, buf, nbytes, off, true);
  1231. }
  1232. static ssize_t tg_set_conf_uint(struct kernfs_open_file *of,
  1233. char *buf, size_t nbytes, loff_t off)
  1234. {
  1235. return tg_set_conf(of, buf, nbytes, off, false);
  1236. }
  1237. static struct cftype throtl_legacy_files[] = {
  1238. {
  1239. .name = "throttle.read_bps_device",
  1240. .private = offsetof(struct throtl_grp, bps[READ][LIMIT_MAX]),
  1241. .seq_show = tg_print_conf_u64,
  1242. .write = tg_set_conf_u64,
  1243. },
  1244. {
  1245. .name = "throttle.write_bps_device",
  1246. .private = offsetof(struct throtl_grp, bps[WRITE][LIMIT_MAX]),
  1247. .seq_show = tg_print_conf_u64,
  1248. .write = tg_set_conf_u64,
  1249. },
  1250. {
  1251. .name = "throttle.read_iops_device",
  1252. .private = offsetof(struct throtl_grp, iops[READ][LIMIT_MAX]),
  1253. .seq_show = tg_print_conf_uint,
  1254. .write = tg_set_conf_uint,
  1255. },
  1256. {
  1257. .name = "throttle.write_iops_device",
  1258. .private = offsetof(struct throtl_grp, iops[WRITE][LIMIT_MAX]),
  1259. .seq_show = tg_print_conf_uint,
  1260. .write = tg_set_conf_uint,
  1261. },
  1262. {
  1263. .name = "throttle.io_service_bytes",
  1264. .private = (unsigned long)&blkcg_policy_throtl,
  1265. .seq_show = blkg_print_stat_bytes,
  1266. },
  1267. {
  1268. .name = "throttle.io_serviced",
  1269. .private = (unsigned long)&blkcg_policy_throtl,
  1270. .seq_show = blkg_print_stat_ios,
  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[LATENCY_BUCKET_SIZE];
  1727. int i, cpu;
  1728. unsigned long last_latency = 0;
  1729. unsigned long latency;
  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 (i = 0; i < LATENCY_BUCKET_SIZE; i++) {
  1737. struct latency_bucket *tmp = &td->tmp_buckets[i];
  1738. for_each_possible_cpu(cpu) {
  1739. struct latency_bucket *bucket;
  1740. /* this isn't race free, but ok in practice */
  1741. bucket = per_cpu_ptr(td->latency_buckets, cpu);
  1742. tmp->total_latency += bucket[i].total_latency;
  1743. tmp->samples += bucket[i].samples;
  1744. bucket[i].total_latency = 0;
  1745. bucket[i].samples = 0;
  1746. }
  1747. if (tmp->samples >= 32) {
  1748. int samples = tmp->samples;
  1749. latency = tmp->total_latency;
  1750. tmp->total_latency = 0;
  1751. tmp->samples = 0;
  1752. latency /= samples;
  1753. if (latency == 0)
  1754. continue;
  1755. avg_latency[i].latency = latency;
  1756. }
  1757. }
  1758. for (i = 0; i < LATENCY_BUCKET_SIZE; i++) {
  1759. if (!avg_latency[i].latency) {
  1760. if (td->avg_buckets[i].latency < last_latency)
  1761. td->avg_buckets[i].latency = last_latency;
  1762. continue;
  1763. }
  1764. if (!td->avg_buckets[i].valid)
  1765. latency = avg_latency[i].latency;
  1766. else
  1767. latency = (td->avg_buckets[i].latency * 7 +
  1768. avg_latency[i].latency) >> 3;
  1769. td->avg_buckets[i].latency = max(latency, last_latency);
  1770. td->avg_buckets[i].valid = true;
  1771. last_latency = td->avg_buckets[i].latency;
  1772. }
  1773. for (i = 0; i < LATENCY_BUCKET_SIZE; i++)
  1774. throtl_log(&td->service_queue,
  1775. "Latency bucket %d: latency=%ld, valid=%d", i,
  1776. td->avg_buckets[i].latency, td->avg_buckets[i].valid);
  1777. }
  1778. #else
  1779. static inline void throtl_update_latency_buckets(struct throtl_data *td)
  1780. {
  1781. }
  1782. #endif
  1783. static void blk_throtl_assoc_bio(struct throtl_grp *tg, struct bio *bio)
  1784. {
  1785. #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
  1786. if (bio->bi_css)
  1787. bio->bi_cg_private = tg;
  1788. blk_stat_set_issue(&bio->bi_issue_stat, bio_sectors(bio));
  1789. #endif
  1790. }
  1791. bool blk_throtl_bio(struct request_queue *q, struct blkcg_gq *blkg,
  1792. struct bio *bio)
  1793. {
  1794. struct throtl_qnode *qn = NULL;
  1795. struct throtl_grp *tg = blkg_to_tg(blkg ?: q->root_blkg);
  1796. struct throtl_service_queue *sq;
  1797. bool rw = bio_data_dir(bio);
  1798. bool throttled = false;
  1799. struct throtl_data *td = tg->td;
  1800. WARN_ON_ONCE(!rcu_read_lock_held());
  1801. /* see throtl_charge_bio() */
  1802. if (bio_flagged(bio, BIO_THROTTLED) || !tg->has_rules[rw])
  1803. goto out;
  1804. spin_lock_irq(q->queue_lock);
  1805. throtl_update_latency_buckets(td);
  1806. if (unlikely(blk_queue_bypass(q)))
  1807. goto out_unlock;
  1808. blk_throtl_assoc_bio(tg, bio);
  1809. blk_throtl_update_idletime(tg);
  1810. sq = &tg->service_queue;
  1811. again:
  1812. while (true) {
  1813. if (tg->last_low_overflow_time[rw] == 0)
  1814. tg->last_low_overflow_time[rw] = jiffies;
  1815. throtl_downgrade_check(tg);
  1816. throtl_upgrade_check(tg);
  1817. /* throtl is FIFO - if bios are already queued, should queue */
  1818. if (sq->nr_queued[rw])
  1819. break;
  1820. /* if above limits, break to queue */
  1821. if (!tg_may_dispatch(tg, bio, NULL)) {
  1822. tg->last_low_overflow_time[rw] = jiffies;
  1823. if (throtl_can_upgrade(td, tg)) {
  1824. throtl_upgrade_state(td);
  1825. goto again;
  1826. }
  1827. break;
  1828. }
  1829. /* within limits, let's charge and dispatch directly */
  1830. throtl_charge_bio(tg, bio);
  1831. /*
  1832. * We need to trim slice even when bios are not being queued
  1833. * otherwise it might happen that a bio is not queued for
  1834. * a long time and slice keeps on extending and trim is not
  1835. * called for a long time. Now if limits are reduced suddenly
  1836. * we take into account all the IO dispatched so far at new
  1837. * low rate and * newly queued IO gets a really long dispatch
  1838. * time.
  1839. *
  1840. * So keep on trimming slice even if bio is not queued.
  1841. */
  1842. throtl_trim_slice(tg, rw);
  1843. /*
  1844. * @bio passed through this layer without being throttled.
  1845. * Climb up the ladder. If we''re already at the top, it
  1846. * can be executed directly.
  1847. */
  1848. qn = &tg->qnode_on_parent[rw];
  1849. sq = sq->parent_sq;
  1850. tg = sq_to_tg(sq);
  1851. if (!tg)
  1852. goto out_unlock;
  1853. }
  1854. /* out-of-limit, queue to @tg */
  1855. throtl_log(sq, "[%c] bio. bdisp=%llu sz=%u bps=%llu iodisp=%u iops=%u queued=%d/%d",
  1856. rw == READ ? 'R' : 'W',
  1857. tg->bytes_disp[rw], bio->bi_iter.bi_size,
  1858. tg_bps_limit(tg, rw),
  1859. tg->io_disp[rw], tg_iops_limit(tg, rw),
  1860. sq->nr_queued[READ], sq->nr_queued[WRITE]);
  1861. tg->last_low_overflow_time[rw] = jiffies;
  1862. td->nr_queued[rw]++;
  1863. throtl_add_bio_tg(bio, qn, tg);
  1864. throttled = true;
  1865. /*
  1866. * Update @tg's dispatch time and force schedule dispatch if @tg
  1867. * was empty before @bio. The forced scheduling isn't likely to
  1868. * cause undue delay as @bio is likely to be dispatched directly if
  1869. * its @tg's disptime is not in the future.
  1870. */
  1871. if (tg->flags & THROTL_TG_WAS_EMPTY) {
  1872. tg_update_disptime(tg);
  1873. throtl_schedule_next_dispatch(tg->service_queue.parent_sq, true);
  1874. }
  1875. out_unlock:
  1876. spin_unlock_irq(q->queue_lock);
  1877. out:
  1878. bio_set_flag(bio, BIO_THROTTLED);
  1879. #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
  1880. if (throttled || !td->track_bio_latency)
  1881. bio->bi_issue_stat.stat |= SKIP_LATENCY;
  1882. #endif
  1883. return throttled;
  1884. }
  1885. #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
  1886. static void throtl_track_latency(struct throtl_data *td, sector_t size,
  1887. int op, unsigned long time)
  1888. {
  1889. struct latency_bucket *latency;
  1890. int index;
  1891. if (!td || td->limit_index != LIMIT_LOW || op != REQ_OP_READ ||
  1892. !blk_queue_nonrot(td->queue))
  1893. return;
  1894. index = request_bucket_index(size);
  1895. latency = get_cpu_ptr(td->latency_buckets);
  1896. latency[index].total_latency += time;
  1897. latency[index].samples++;
  1898. put_cpu_ptr(td->latency_buckets);
  1899. }
  1900. void blk_throtl_stat_add(struct request *rq, u64 time_ns)
  1901. {
  1902. struct request_queue *q = rq->q;
  1903. struct throtl_data *td = q->td;
  1904. throtl_track_latency(td, blk_stat_size(&rq->issue_stat),
  1905. req_op(rq), time_ns >> 10);
  1906. }
  1907. void blk_throtl_bio_endio(struct bio *bio)
  1908. {
  1909. struct throtl_grp *tg;
  1910. u64 finish_time_ns;
  1911. unsigned long finish_time;
  1912. unsigned long start_time;
  1913. unsigned long lat;
  1914. tg = bio->bi_cg_private;
  1915. if (!tg)
  1916. return;
  1917. bio->bi_cg_private = NULL;
  1918. finish_time_ns = ktime_get_ns();
  1919. tg->last_finish_time = finish_time_ns >> 10;
  1920. start_time = blk_stat_time(&bio->bi_issue_stat) >> 10;
  1921. finish_time = __blk_stat_time(finish_time_ns) >> 10;
  1922. if (!start_time || finish_time <= start_time)
  1923. return;
  1924. lat = finish_time - start_time;
  1925. /* this is only for bio based driver */
  1926. if (!(bio->bi_issue_stat.stat & SKIP_LATENCY))
  1927. throtl_track_latency(tg->td, blk_stat_size(&bio->bi_issue_stat),
  1928. bio_op(bio), lat);
  1929. if (tg->latency_target && lat >= tg->td->filtered_latency) {
  1930. int bucket;
  1931. unsigned int threshold;
  1932. bucket = request_bucket_index(
  1933. blk_stat_size(&bio->bi_issue_stat));
  1934. threshold = tg->td->avg_buckets[bucket].latency +
  1935. tg->latency_target;
  1936. if (lat > threshold)
  1937. tg->bad_bio_cnt++;
  1938. /*
  1939. * Not race free, could get wrong count, which means cgroups
  1940. * will be throttled
  1941. */
  1942. tg->bio_cnt++;
  1943. }
  1944. if (time_after(jiffies, tg->bio_cnt_reset_time) || tg->bio_cnt > 1024) {
  1945. tg->bio_cnt_reset_time = tg->td->throtl_slice + jiffies;
  1946. tg->bio_cnt /= 2;
  1947. tg->bad_bio_cnt /= 2;
  1948. }
  1949. }
  1950. #endif
  1951. /*
  1952. * Dispatch all bios from all children tg's queued on @parent_sq. On
  1953. * return, @parent_sq is guaranteed to not have any active children tg's
  1954. * and all bios from previously active tg's are on @parent_sq->bio_lists[].
  1955. */
  1956. static void tg_drain_bios(struct throtl_service_queue *parent_sq)
  1957. {
  1958. struct throtl_grp *tg;
  1959. while ((tg = throtl_rb_first(parent_sq))) {
  1960. struct throtl_service_queue *sq = &tg->service_queue;
  1961. struct bio *bio;
  1962. throtl_dequeue_tg(tg);
  1963. while ((bio = throtl_peek_queued(&sq->queued[READ])))
  1964. tg_dispatch_one_bio(tg, bio_data_dir(bio));
  1965. while ((bio = throtl_peek_queued(&sq->queued[WRITE])))
  1966. tg_dispatch_one_bio(tg, bio_data_dir(bio));
  1967. }
  1968. }
  1969. /**
  1970. * blk_throtl_drain - drain throttled bios
  1971. * @q: request_queue to drain throttled bios for
  1972. *
  1973. * Dispatch all currently throttled bios on @q through ->make_request_fn().
  1974. */
  1975. void blk_throtl_drain(struct request_queue *q)
  1976. __releases(q->queue_lock) __acquires(q->queue_lock)
  1977. {
  1978. struct throtl_data *td = q->td;
  1979. struct blkcg_gq *blkg;
  1980. struct cgroup_subsys_state *pos_css;
  1981. struct bio *bio;
  1982. int rw;
  1983. queue_lockdep_assert_held(q);
  1984. rcu_read_lock();
  1985. /*
  1986. * Drain each tg while doing post-order walk on the blkg tree, so
  1987. * that all bios are propagated to td->service_queue. It'd be
  1988. * better to walk service_queue tree directly but blkg walk is
  1989. * easier.
  1990. */
  1991. blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg)
  1992. tg_drain_bios(&blkg_to_tg(blkg)->service_queue);
  1993. /* finally, transfer bios from top-level tg's into the td */
  1994. tg_drain_bios(&td->service_queue);
  1995. rcu_read_unlock();
  1996. spin_unlock_irq(q->queue_lock);
  1997. /* all bios now should be in td->service_queue, issue them */
  1998. for (rw = READ; rw <= WRITE; rw++)
  1999. while ((bio = throtl_pop_queued(&td->service_queue.queued[rw],
  2000. NULL)))
  2001. generic_make_request(bio);
  2002. spin_lock_irq(q->queue_lock);
  2003. }
  2004. int blk_throtl_init(struct request_queue *q)
  2005. {
  2006. struct throtl_data *td;
  2007. int ret;
  2008. td = kzalloc_node(sizeof(*td), GFP_KERNEL, q->node);
  2009. if (!td)
  2010. return -ENOMEM;
  2011. td->latency_buckets = __alloc_percpu(sizeof(struct latency_bucket) *
  2012. LATENCY_BUCKET_SIZE, __alignof__(u64));
  2013. if (!td->latency_buckets) {
  2014. kfree(td);
  2015. return -ENOMEM;
  2016. }
  2017. INIT_WORK(&td->dispatch_work, blk_throtl_dispatch_work_fn);
  2018. throtl_service_queue_init(&td->service_queue);
  2019. q->td = td;
  2020. td->queue = q;
  2021. td->limit_valid[LIMIT_MAX] = true;
  2022. td->limit_index = LIMIT_MAX;
  2023. td->low_upgrade_time = jiffies;
  2024. td->low_downgrade_time = jiffies;
  2025. /* activate policy */
  2026. ret = blkcg_activate_policy(q, &blkcg_policy_throtl);
  2027. if (ret) {
  2028. free_percpu(td->latency_buckets);
  2029. kfree(td);
  2030. }
  2031. return ret;
  2032. }
  2033. void blk_throtl_exit(struct request_queue *q)
  2034. {
  2035. BUG_ON(!q->td);
  2036. throtl_shutdown_wq(q);
  2037. blkcg_deactivate_policy(q, &blkcg_policy_throtl);
  2038. free_percpu(q->td->latency_buckets);
  2039. kfree(q->td);
  2040. }
  2041. void blk_throtl_register_queue(struct request_queue *q)
  2042. {
  2043. struct throtl_data *td;
  2044. int i;
  2045. td = q->td;
  2046. BUG_ON(!td);
  2047. if (blk_queue_nonrot(q)) {
  2048. td->throtl_slice = DFL_THROTL_SLICE_SSD;
  2049. td->filtered_latency = LATENCY_FILTERED_SSD;
  2050. } else {
  2051. td->throtl_slice = DFL_THROTL_SLICE_HD;
  2052. td->filtered_latency = LATENCY_FILTERED_HD;
  2053. for (i = 0; i < LATENCY_BUCKET_SIZE; i++)
  2054. td->avg_buckets[i].latency = DFL_HD_BASELINE_LATENCY;
  2055. }
  2056. #ifndef CONFIG_BLK_DEV_THROTTLING_LOW
  2057. /* if no low limit, use previous default */
  2058. td->throtl_slice = DFL_THROTL_SLICE_HD;
  2059. #endif
  2060. td->track_bio_latency = !q->mq_ops && !q->request_fn;
  2061. if (!td->track_bio_latency)
  2062. blk_stat_enable_accounting(q);
  2063. }
  2064. #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
  2065. ssize_t blk_throtl_sample_time_show(struct request_queue *q, char *page)
  2066. {
  2067. if (!q->td)
  2068. return -EINVAL;
  2069. return sprintf(page, "%u\n", jiffies_to_msecs(q->td->throtl_slice));
  2070. }
  2071. ssize_t blk_throtl_sample_time_store(struct request_queue *q,
  2072. const char *page, size_t count)
  2073. {
  2074. unsigned long v;
  2075. unsigned long t;
  2076. if (!q->td)
  2077. return -EINVAL;
  2078. if (kstrtoul(page, 10, &v))
  2079. return -EINVAL;
  2080. t = msecs_to_jiffies(v);
  2081. if (t == 0 || t > MAX_THROTL_SLICE)
  2082. return -EINVAL;
  2083. q->td->throtl_slice = t;
  2084. return count;
  2085. }
  2086. #endif
  2087. static int __init throtl_init(void)
  2088. {
  2089. kthrotld_workqueue = alloc_workqueue("kthrotld", WQ_MEM_RECLAIM, 0);
  2090. if (!kthrotld_workqueue)
  2091. panic("Failed to create kthrotld\n");
  2092. return blkcg_policy_register(&blkcg_policy_throtl);
  2093. }
  2094. module_init(throtl_init);