blk-throttle.c 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709
  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 "blk.h"
  13. #include "blk-cgroup-rwstat.h"
  14. #include "blk-stat.h"
  15. #include "blk-throttle.h"
  16. /* Max dispatch from a group in 1 round */
  17. #define THROTL_GRP_QUANTUM 8
  18. /* Total max dispatch from all groups in one round */
  19. #define THROTL_QUANTUM 32
  20. /* Throttling is performed over a slice and after that slice is renewed */
  21. #define DFL_THROTL_SLICE_HD (HZ / 10)
  22. #define DFL_THROTL_SLICE_SSD (HZ / 50)
  23. #define MAX_THROTL_SLICE (HZ)
  24. /* A workqueue to queue throttle related work */
  25. static struct workqueue_struct *kthrotld_workqueue;
  26. #define rb_entry_tg(node) rb_entry((node), struct throtl_grp, rb_node)
  27. struct throtl_data
  28. {
  29. /* service tree for active throtl groups */
  30. struct throtl_service_queue service_queue;
  31. struct request_queue *queue;
  32. /* Total Number of queued bios on READ and WRITE lists */
  33. unsigned int nr_queued[2];
  34. unsigned int throtl_slice;
  35. /* Work for dispatching throttled bios */
  36. struct work_struct dispatch_work;
  37. bool track_bio_latency;
  38. };
  39. static void throtl_pending_timer_fn(struct timer_list *t);
  40. static inline struct blkcg_gq *tg_to_blkg(struct throtl_grp *tg)
  41. {
  42. return pd_to_blkg(&tg->pd);
  43. }
  44. /**
  45. * sq_to_tg - return the throl_grp the specified service queue belongs to
  46. * @sq: the throtl_service_queue of interest
  47. *
  48. * Return the throtl_grp @sq belongs to. If @sq is the top-level one
  49. * embedded in throtl_data, %NULL is returned.
  50. */
  51. static struct throtl_grp *sq_to_tg(struct throtl_service_queue *sq)
  52. {
  53. if (sq && sq->parent_sq)
  54. return container_of(sq, struct throtl_grp, service_queue);
  55. else
  56. return NULL;
  57. }
  58. /**
  59. * sq_to_td - return throtl_data the specified service queue belongs to
  60. * @sq: the throtl_service_queue of interest
  61. *
  62. * A service_queue can be embedded in either a throtl_grp or throtl_data.
  63. * Determine the associated throtl_data accordingly and return it.
  64. */
  65. static struct throtl_data *sq_to_td(struct throtl_service_queue *sq)
  66. {
  67. struct throtl_grp *tg = sq_to_tg(sq);
  68. if (tg)
  69. return tg->td;
  70. else
  71. return container_of(sq, struct throtl_data, service_queue);
  72. }
  73. static uint64_t tg_bps_limit(struct throtl_grp *tg, int rw)
  74. {
  75. struct blkcg_gq *blkg = tg_to_blkg(tg);
  76. if (cgroup_subsys_on_dfl(io_cgrp_subsys) && !blkg->parent)
  77. return U64_MAX;
  78. return tg->bps[rw];
  79. }
  80. static unsigned int tg_iops_limit(struct throtl_grp *tg, int rw)
  81. {
  82. struct blkcg_gq *blkg = tg_to_blkg(tg);
  83. if (cgroup_subsys_on_dfl(io_cgrp_subsys) && !blkg->parent)
  84. return UINT_MAX;
  85. return tg->iops[rw];
  86. }
  87. /**
  88. * throtl_log - log debug message via blktrace
  89. * @sq: the service_queue being reported
  90. * @fmt: printf format string
  91. * @args: printf args
  92. *
  93. * The messages are prefixed with "throtl BLKG_NAME" if @sq belongs to a
  94. * throtl_grp; otherwise, just "throtl".
  95. */
  96. #define throtl_log(sq, fmt, args...) do { \
  97. struct throtl_grp *__tg = sq_to_tg((sq)); \
  98. struct throtl_data *__td = sq_to_td((sq)); \
  99. \
  100. (void)__td; \
  101. if (likely(!blk_trace_note_message_enabled(__td->queue))) \
  102. break; \
  103. if ((__tg)) { \
  104. blk_add_cgroup_trace_msg(__td->queue, \
  105. &tg_to_blkg(__tg)->blkcg->css, "throtl " fmt, ##args);\
  106. } else { \
  107. blk_add_trace_msg(__td->queue, "throtl " fmt, ##args); \
  108. } \
  109. } while (0)
  110. static inline unsigned int throtl_bio_data_size(struct bio *bio)
  111. {
  112. /* assume it's one sector */
  113. if (unlikely(bio_op(bio) == REQ_OP_DISCARD))
  114. return 512;
  115. return bio->bi_iter.bi_size;
  116. }
  117. static void throtl_qnode_init(struct throtl_qnode *qn, struct throtl_grp *tg)
  118. {
  119. INIT_LIST_HEAD(&qn->node);
  120. bio_list_init(&qn->bios);
  121. qn->tg = tg;
  122. }
  123. /**
  124. * throtl_qnode_add_bio - add a bio to a throtl_qnode and activate it
  125. * @bio: bio being added
  126. * @qn: qnode to add bio to
  127. * @queued: the service_queue->queued[] list @qn belongs to
  128. *
  129. * Add @bio to @qn and put @qn on @queued if it's not already on.
  130. * @qn->tg's reference count is bumped when @qn is activated. See the
  131. * comment on top of throtl_qnode definition for details.
  132. */
  133. static void throtl_qnode_add_bio(struct bio *bio, struct throtl_qnode *qn,
  134. struct list_head *queued)
  135. {
  136. bio_list_add(&qn->bios, bio);
  137. if (list_empty(&qn->node)) {
  138. list_add_tail(&qn->node, queued);
  139. blkg_get(tg_to_blkg(qn->tg));
  140. }
  141. }
  142. /**
  143. * throtl_peek_queued - peek the first bio on a qnode list
  144. * @queued: the qnode list to peek
  145. */
  146. static struct bio *throtl_peek_queued(struct list_head *queued)
  147. {
  148. struct throtl_qnode *qn;
  149. struct bio *bio;
  150. if (list_empty(queued))
  151. return NULL;
  152. qn = list_first_entry(queued, struct throtl_qnode, node);
  153. bio = bio_list_peek(&qn->bios);
  154. WARN_ON_ONCE(!bio);
  155. return bio;
  156. }
  157. /**
  158. * throtl_pop_queued - pop the first bio form a qnode list
  159. * @queued: the qnode list to pop a bio from
  160. * @tg_to_put: optional out argument for throtl_grp to put
  161. *
  162. * Pop the first bio from the qnode list @queued. After popping, the first
  163. * qnode is removed from @queued if empty or moved to the end of @queued so
  164. * that the popping order is round-robin.
  165. *
  166. * When the first qnode is removed, its associated throtl_grp should be put
  167. * too. If @tg_to_put is NULL, this function automatically puts it;
  168. * otherwise, *@tg_to_put is set to the throtl_grp to put and the caller is
  169. * responsible for putting it.
  170. */
  171. static struct bio *throtl_pop_queued(struct list_head *queued,
  172. struct throtl_grp **tg_to_put)
  173. {
  174. struct throtl_qnode *qn;
  175. struct bio *bio;
  176. if (list_empty(queued))
  177. return NULL;
  178. qn = list_first_entry(queued, struct throtl_qnode, node);
  179. bio = bio_list_pop(&qn->bios);
  180. WARN_ON_ONCE(!bio);
  181. if (bio_list_empty(&qn->bios)) {
  182. list_del_init(&qn->node);
  183. if (tg_to_put)
  184. *tg_to_put = qn->tg;
  185. else
  186. blkg_put(tg_to_blkg(qn->tg));
  187. } else {
  188. list_move_tail(&qn->node, queued);
  189. }
  190. return bio;
  191. }
  192. /* init a service_queue, assumes the caller zeroed it */
  193. static void throtl_service_queue_init(struct throtl_service_queue *sq)
  194. {
  195. INIT_LIST_HEAD(&sq->queued[READ]);
  196. INIT_LIST_HEAD(&sq->queued[WRITE]);
  197. sq->pending_tree = RB_ROOT_CACHED;
  198. timer_setup(&sq->pending_timer, throtl_pending_timer_fn, 0);
  199. }
  200. static struct blkg_policy_data *throtl_pd_alloc(struct gendisk *disk,
  201. struct blkcg *blkcg, gfp_t gfp)
  202. {
  203. struct throtl_grp *tg;
  204. int rw;
  205. tg = kzalloc_node(sizeof(*tg), gfp, disk->node_id);
  206. if (!tg)
  207. return NULL;
  208. if (blkg_rwstat_init(&tg->stat_bytes, gfp))
  209. goto err_free_tg;
  210. if (blkg_rwstat_init(&tg->stat_ios, gfp))
  211. goto err_exit_stat_bytes;
  212. throtl_service_queue_init(&tg->service_queue);
  213. for (rw = READ; rw <= WRITE; rw++) {
  214. throtl_qnode_init(&tg->qnode_on_self[rw], tg);
  215. throtl_qnode_init(&tg->qnode_on_parent[rw], tg);
  216. }
  217. RB_CLEAR_NODE(&tg->rb_node);
  218. tg->bps[READ] = U64_MAX;
  219. tg->bps[WRITE] = U64_MAX;
  220. tg->iops[READ] = UINT_MAX;
  221. tg->iops[WRITE] = UINT_MAX;
  222. return &tg->pd;
  223. err_exit_stat_bytes:
  224. blkg_rwstat_exit(&tg->stat_bytes);
  225. err_free_tg:
  226. kfree(tg);
  227. return NULL;
  228. }
  229. static void throtl_pd_init(struct blkg_policy_data *pd)
  230. {
  231. struct throtl_grp *tg = pd_to_tg(pd);
  232. struct blkcg_gq *blkg = tg_to_blkg(tg);
  233. struct throtl_data *td = blkg->q->td;
  234. struct throtl_service_queue *sq = &tg->service_queue;
  235. /*
  236. * If on the default hierarchy, we switch to properly hierarchical
  237. * behavior where limits on a given throtl_grp are applied to the
  238. * whole subtree rather than just the group itself. e.g. If 16M
  239. * read_bps limit is set on a parent group, summary bps of
  240. * parent group and its subtree groups can't exceed 16M for the
  241. * device.
  242. *
  243. * If not on the default hierarchy, the broken flat hierarchy
  244. * behavior is retained where all throtl_grps are treated as if
  245. * they're all separate root groups right below throtl_data.
  246. * Limits of a group don't interact with limits of other groups
  247. * regardless of the position of the group in the hierarchy.
  248. */
  249. sq->parent_sq = &td->service_queue;
  250. if (cgroup_subsys_on_dfl(io_cgrp_subsys) && blkg->parent)
  251. sq->parent_sq = &blkg_to_tg(blkg->parent)->service_queue;
  252. tg->td = td;
  253. }
  254. /*
  255. * Set has_rules[] if @tg or any of its parents have limits configured.
  256. * This doesn't require walking up to the top of the hierarchy as the
  257. * parent's has_rules[] is guaranteed to be correct.
  258. */
  259. static void tg_update_has_rules(struct throtl_grp *tg)
  260. {
  261. struct throtl_grp *parent_tg = sq_to_tg(tg->service_queue.parent_sq);
  262. int rw;
  263. for (rw = READ; rw <= WRITE; rw++) {
  264. tg->has_rules_iops[rw] =
  265. (parent_tg && parent_tg->has_rules_iops[rw]) ||
  266. tg_iops_limit(tg, rw) != UINT_MAX;
  267. tg->has_rules_bps[rw] =
  268. (parent_tg && parent_tg->has_rules_bps[rw]) ||
  269. tg_bps_limit(tg, rw) != U64_MAX;
  270. }
  271. }
  272. static void throtl_pd_online(struct blkg_policy_data *pd)
  273. {
  274. struct throtl_grp *tg = pd_to_tg(pd);
  275. /*
  276. * We don't want new groups to escape the limits of its ancestors.
  277. * Update has_rules[] after a new group is brought online.
  278. */
  279. tg_update_has_rules(tg);
  280. }
  281. static void throtl_pd_free(struct blkg_policy_data *pd)
  282. {
  283. struct throtl_grp *tg = pd_to_tg(pd);
  284. del_timer_sync(&tg->service_queue.pending_timer);
  285. blkg_rwstat_exit(&tg->stat_bytes);
  286. blkg_rwstat_exit(&tg->stat_ios);
  287. kfree(tg);
  288. }
  289. static struct throtl_grp *
  290. throtl_rb_first(struct throtl_service_queue *parent_sq)
  291. {
  292. struct rb_node *n;
  293. n = rb_first_cached(&parent_sq->pending_tree);
  294. WARN_ON_ONCE(!n);
  295. if (!n)
  296. return NULL;
  297. return rb_entry_tg(n);
  298. }
  299. static void throtl_rb_erase(struct rb_node *n,
  300. struct throtl_service_queue *parent_sq)
  301. {
  302. rb_erase_cached(n, &parent_sq->pending_tree);
  303. RB_CLEAR_NODE(n);
  304. }
  305. static void update_min_dispatch_time(struct throtl_service_queue *parent_sq)
  306. {
  307. struct throtl_grp *tg;
  308. tg = throtl_rb_first(parent_sq);
  309. if (!tg)
  310. return;
  311. parent_sq->first_pending_disptime = tg->disptime;
  312. }
  313. static void tg_service_queue_add(struct throtl_grp *tg)
  314. {
  315. struct throtl_service_queue *parent_sq = tg->service_queue.parent_sq;
  316. struct rb_node **node = &parent_sq->pending_tree.rb_root.rb_node;
  317. struct rb_node *parent = NULL;
  318. struct throtl_grp *__tg;
  319. unsigned long key = tg->disptime;
  320. bool leftmost = true;
  321. while (*node != NULL) {
  322. parent = *node;
  323. __tg = rb_entry_tg(parent);
  324. if (time_before(key, __tg->disptime))
  325. node = &parent->rb_left;
  326. else {
  327. node = &parent->rb_right;
  328. leftmost = false;
  329. }
  330. }
  331. rb_link_node(&tg->rb_node, parent, node);
  332. rb_insert_color_cached(&tg->rb_node, &parent_sq->pending_tree,
  333. leftmost);
  334. }
  335. static void throtl_enqueue_tg(struct throtl_grp *tg)
  336. {
  337. if (!(tg->flags & THROTL_TG_PENDING)) {
  338. tg_service_queue_add(tg);
  339. tg->flags |= THROTL_TG_PENDING;
  340. tg->service_queue.parent_sq->nr_pending++;
  341. }
  342. }
  343. static void throtl_dequeue_tg(struct throtl_grp *tg)
  344. {
  345. if (tg->flags & THROTL_TG_PENDING) {
  346. struct throtl_service_queue *parent_sq =
  347. tg->service_queue.parent_sq;
  348. throtl_rb_erase(&tg->rb_node, parent_sq);
  349. --parent_sq->nr_pending;
  350. tg->flags &= ~THROTL_TG_PENDING;
  351. }
  352. }
  353. /* Call with queue lock held */
  354. static void throtl_schedule_pending_timer(struct throtl_service_queue *sq,
  355. unsigned long expires)
  356. {
  357. unsigned long max_expire = jiffies + 8 * sq_to_td(sq)->throtl_slice;
  358. /*
  359. * Since we are adjusting the throttle limit dynamically, the sleep
  360. * time calculated according to previous limit might be invalid. It's
  361. * possible the cgroup sleep time is very long and no other cgroups
  362. * have IO running so notify the limit changes. Make sure the cgroup
  363. * doesn't sleep too long to avoid the missed notification.
  364. */
  365. if (time_after(expires, max_expire))
  366. expires = max_expire;
  367. mod_timer(&sq->pending_timer, expires);
  368. throtl_log(sq, "schedule timer. delay=%lu jiffies=%lu",
  369. expires - jiffies, jiffies);
  370. }
  371. /**
  372. * throtl_schedule_next_dispatch - schedule the next dispatch cycle
  373. * @sq: the service_queue to schedule dispatch for
  374. * @force: force scheduling
  375. *
  376. * Arm @sq->pending_timer so that the next dispatch cycle starts on the
  377. * dispatch time of the first pending child. Returns %true if either timer
  378. * is armed or there's no pending child left. %false if the current
  379. * dispatch window is still open and the caller should continue
  380. * dispatching.
  381. *
  382. * If @force is %true, the dispatch timer is always scheduled and this
  383. * function is guaranteed to return %true. This is to be used when the
  384. * caller can't dispatch itself and needs to invoke pending_timer
  385. * unconditionally. Note that forced scheduling is likely to induce short
  386. * delay before dispatch starts even if @sq->first_pending_disptime is not
  387. * in the future and thus shouldn't be used in hot paths.
  388. */
  389. static bool throtl_schedule_next_dispatch(struct throtl_service_queue *sq,
  390. bool force)
  391. {
  392. /* any pending children left? */
  393. if (!sq->nr_pending)
  394. return true;
  395. update_min_dispatch_time(sq);
  396. /* is the next dispatch time in the future? */
  397. if (force || time_after(sq->first_pending_disptime, jiffies)) {
  398. throtl_schedule_pending_timer(sq, sq->first_pending_disptime);
  399. return true;
  400. }
  401. /* tell the caller to continue dispatching */
  402. return false;
  403. }
  404. static inline void throtl_start_new_slice_with_credit(struct throtl_grp *tg,
  405. bool rw, unsigned long start)
  406. {
  407. tg->bytes_disp[rw] = 0;
  408. tg->io_disp[rw] = 0;
  409. tg->carryover_bytes[rw] = 0;
  410. tg->carryover_ios[rw] = 0;
  411. /*
  412. * Previous slice has expired. We must have trimmed it after last
  413. * bio dispatch. That means since start of last slice, we never used
  414. * that bandwidth. Do try to make use of that bandwidth while giving
  415. * credit.
  416. */
  417. if (time_after(start, tg->slice_start[rw]))
  418. tg->slice_start[rw] = start;
  419. tg->slice_end[rw] = jiffies + tg->td->throtl_slice;
  420. throtl_log(&tg->service_queue,
  421. "[%c] new slice with credit start=%lu end=%lu jiffies=%lu",
  422. rw == READ ? 'R' : 'W', tg->slice_start[rw],
  423. tg->slice_end[rw], jiffies);
  424. }
  425. static inline void throtl_start_new_slice(struct throtl_grp *tg, bool rw,
  426. bool clear_carryover)
  427. {
  428. tg->bytes_disp[rw] = 0;
  429. tg->io_disp[rw] = 0;
  430. tg->slice_start[rw] = jiffies;
  431. tg->slice_end[rw] = jiffies + tg->td->throtl_slice;
  432. if (clear_carryover) {
  433. tg->carryover_bytes[rw] = 0;
  434. tg->carryover_ios[rw] = 0;
  435. }
  436. throtl_log(&tg->service_queue,
  437. "[%c] new slice start=%lu end=%lu jiffies=%lu",
  438. rw == READ ? 'R' : 'W', tg->slice_start[rw],
  439. tg->slice_end[rw], jiffies);
  440. }
  441. static inline void throtl_set_slice_end(struct throtl_grp *tg, bool rw,
  442. unsigned long jiffy_end)
  443. {
  444. tg->slice_end[rw] = roundup(jiffy_end, tg->td->throtl_slice);
  445. }
  446. static inline void throtl_extend_slice(struct throtl_grp *tg, bool rw,
  447. unsigned long jiffy_end)
  448. {
  449. throtl_set_slice_end(tg, rw, jiffy_end);
  450. throtl_log(&tg->service_queue,
  451. "[%c] extend slice start=%lu end=%lu jiffies=%lu",
  452. rw == READ ? 'R' : 'W', tg->slice_start[rw],
  453. tg->slice_end[rw], jiffies);
  454. }
  455. /* Determine if previously allocated or extended slice is complete or not */
  456. static bool throtl_slice_used(struct throtl_grp *tg, bool rw)
  457. {
  458. if (time_in_range(jiffies, tg->slice_start[rw], tg->slice_end[rw]))
  459. return false;
  460. return true;
  461. }
  462. static unsigned int calculate_io_allowed(u32 iops_limit,
  463. unsigned long jiffy_elapsed)
  464. {
  465. unsigned int io_allowed;
  466. u64 tmp;
  467. /*
  468. * jiffy_elapsed should not be a big value as minimum iops can be
  469. * 1 then at max jiffy elapsed should be equivalent of 1 second as we
  470. * will allow dispatch after 1 second and after that slice should
  471. * have been trimmed.
  472. */
  473. tmp = (u64)iops_limit * jiffy_elapsed;
  474. do_div(tmp, HZ);
  475. if (tmp > UINT_MAX)
  476. io_allowed = UINT_MAX;
  477. else
  478. io_allowed = tmp;
  479. return io_allowed;
  480. }
  481. static u64 calculate_bytes_allowed(u64 bps_limit, unsigned long jiffy_elapsed)
  482. {
  483. /*
  484. * Can result be wider than 64 bits?
  485. * We check against 62, not 64, due to ilog2 truncation.
  486. */
  487. if (ilog2(bps_limit) + ilog2(jiffy_elapsed) - ilog2(HZ) > 62)
  488. return U64_MAX;
  489. return mul_u64_u64_div_u64(bps_limit, (u64)jiffy_elapsed, (u64)HZ);
  490. }
  491. /* Trim the used slices and adjust slice start accordingly */
  492. static inline void throtl_trim_slice(struct throtl_grp *tg, bool rw)
  493. {
  494. unsigned long time_elapsed;
  495. long long bytes_trim;
  496. int io_trim;
  497. BUG_ON(time_before(tg->slice_end[rw], tg->slice_start[rw]));
  498. /*
  499. * If bps are unlimited (-1), then time slice don't get
  500. * renewed. Don't try to trim the slice if slice is used. A new
  501. * slice will start when appropriate.
  502. */
  503. if (throtl_slice_used(tg, rw))
  504. return;
  505. /*
  506. * A bio has been dispatched. Also adjust slice_end. It might happen
  507. * that initially cgroup limit was very low resulting in high
  508. * slice_end, but later limit was bumped up and bio was dispatched
  509. * sooner, then we need to reduce slice_end. A high bogus slice_end
  510. * is bad because it does not allow new slice to start.
  511. */
  512. throtl_set_slice_end(tg, rw, jiffies + tg->td->throtl_slice);
  513. time_elapsed = rounddown(jiffies - tg->slice_start[rw],
  514. tg->td->throtl_slice);
  515. if (!time_elapsed)
  516. return;
  517. bytes_trim = calculate_bytes_allowed(tg_bps_limit(tg, rw),
  518. time_elapsed) +
  519. tg->carryover_bytes[rw];
  520. io_trim = calculate_io_allowed(tg_iops_limit(tg, rw), time_elapsed) +
  521. tg->carryover_ios[rw];
  522. if (bytes_trim <= 0 && io_trim <= 0)
  523. return;
  524. tg->carryover_bytes[rw] = 0;
  525. if ((long long)tg->bytes_disp[rw] >= bytes_trim)
  526. tg->bytes_disp[rw] -= bytes_trim;
  527. else
  528. tg->bytes_disp[rw] = 0;
  529. tg->carryover_ios[rw] = 0;
  530. if ((int)tg->io_disp[rw] >= io_trim)
  531. tg->io_disp[rw] -= io_trim;
  532. else
  533. tg->io_disp[rw] = 0;
  534. tg->slice_start[rw] += time_elapsed;
  535. throtl_log(&tg->service_queue,
  536. "[%c] trim slice nr=%lu bytes=%lld io=%d start=%lu end=%lu jiffies=%lu",
  537. rw == READ ? 'R' : 'W', time_elapsed / tg->td->throtl_slice,
  538. bytes_trim, io_trim, tg->slice_start[rw], tg->slice_end[rw],
  539. jiffies);
  540. }
  541. static void __tg_update_carryover(struct throtl_grp *tg, bool rw)
  542. {
  543. unsigned long jiffy_elapsed = jiffies - tg->slice_start[rw];
  544. u64 bps_limit = tg_bps_limit(tg, rw);
  545. u32 iops_limit = tg_iops_limit(tg, rw);
  546. /*
  547. * If config is updated while bios are still throttled, calculate and
  548. * accumulate how many bytes/ios are waited across changes. And
  549. * carryover_bytes/ios will be used to calculate new wait time under new
  550. * configuration.
  551. */
  552. if (bps_limit != U64_MAX)
  553. tg->carryover_bytes[rw] +=
  554. calculate_bytes_allowed(bps_limit, jiffy_elapsed) -
  555. tg->bytes_disp[rw];
  556. if (iops_limit != UINT_MAX)
  557. tg->carryover_ios[rw] +=
  558. calculate_io_allowed(iops_limit, jiffy_elapsed) -
  559. tg->io_disp[rw];
  560. }
  561. static void tg_update_carryover(struct throtl_grp *tg)
  562. {
  563. if (tg->service_queue.nr_queued[READ])
  564. __tg_update_carryover(tg, READ);
  565. if (tg->service_queue.nr_queued[WRITE])
  566. __tg_update_carryover(tg, WRITE);
  567. /* see comments in struct throtl_grp for meaning of these fields. */
  568. throtl_log(&tg->service_queue, "%s: %lld %lld %d %d\n", __func__,
  569. tg->carryover_bytes[READ], tg->carryover_bytes[WRITE],
  570. tg->carryover_ios[READ], tg->carryover_ios[WRITE]);
  571. }
  572. static unsigned long tg_within_iops_limit(struct throtl_grp *tg, struct bio *bio,
  573. u32 iops_limit)
  574. {
  575. bool rw = bio_data_dir(bio);
  576. int io_allowed;
  577. unsigned long jiffy_elapsed, jiffy_wait, jiffy_elapsed_rnd;
  578. if (iops_limit == UINT_MAX) {
  579. return 0;
  580. }
  581. jiffy_elapsed = jiffies - tg->slice_start[rw];
  582. /* Round up to the next throttle slice, wait time must be nonzero */
  583. jiffy_elapsed_rnd = roundup(jiffy_elapsed + 1, tg->td->throtl_slice);
  584. io_allowed = calculate_io_allowed(iops_limit, jiffy_elapsed_rnd) +
  585. tg->carryover_ios[rw];
  586. if (io_allowed > 0 && tg->io_disp[rw] + 1 <= io_allowed)
  587. return 0;
  588. /* Calc approx time to dispatch */
  589. jiffy_wait = jiffy_elapsed_rnd - jiffy_elapsed;
  590. /* make sure at least one io can be dispatched after waiting */
  591. jiffy_wait = max(jiffy_wait, HZ / iops_limit + 1);
  592. return jiffy_wait;
  593. }
  594. static unsigned long tg_within_bps_limit(struct throtl_grp *tg, struct bio *bio,
  595. u64 bps_limit)
  596. {
  597. bool rw = bio_data_dir(bio);
  598. long long bytes_allowed;
  599. u64 extra_bytes;
  600. unsigned long jiffy_elapsed, jiffy_wait, jiffy_elapsed_rnd;
  601. unsigned int bio_size = throtl_bio_data_size(bio);
  602. /* no need to throttle if this bio's bytes have been accounted */
  603. if (bps_limit == U64_MAX || bio_flagged(bio, BIO_BPS_THROTTLED)) {
  604. return 0;
  605. }
  606. jiffy_elapsed = jiffy_elapsed_rnd = jiffies - tg->slice_start[rw];
  607. /* Slice has just started. Consider one slice interval */
  608. if (!jiffy_elapsed)
  609. jiffy_elapsed_rnd = tg->td->throtl_slice;
  610. jiffy_elapsed_rnd = roundup(jiffy_elapsed_rnd, tg->td->throtl_slice);
  611. bytes_allowed = calculate_bytes_allowed(bps_limit, jiffy_elapsed_rnd) +
  612. tg->carryover_bytes[rw];
  613. if (bytes_allowed > 0 && tg->bytes_disp[rw] + bio_size <= bytes_allowed)
  614. return 0;
  615. /* Calc approx time to dispatch */
  616. extra_bytes = tg->bytes_disp[rw] + bio_size - bytes_allowed;
  617. jiffy_wait = div64_u64(extra_bytes * HZ, bps_limit);
  618. if (!jiffy_wait)
  619. jiffy_wait = 1;
  620. /*
  621. * This wait time is without taking into consideration the rounding
  622. * up we did. Add that time also.
  623. */
  624. jiffy_wait = jiffy_wait + (jiffy_elapsed_rnd - jiffy_elapsed);
  625. return jiffy_wait;
  626. }
  627. /*
  628. * Returns whether one can dispatch a bio or not. Also returns approx number
  629. * of jiffies to wait before this bio is with-in IO rate and can be dispatched
  630. */
  631. static bool tg_may_dispatch(struct throtl_grp *tg, struct bio *bio,
  632. unsigned long *wait)
  633. {
  634. bool rw = bio_data_dir(bio);
  635. unsigned long bps_wait = 0, iops_wait = 0, max_wait = 0;
  636. u64 bps_limit = tg_bps_limit(tg, rw);
  637. u32 iops_limit = tg_iops_limit(tg, rw);
  638. /*
  639. * Currently whole state machine of group depends on first bio
  640. * queued in the group bio list. So one should not be calling
  641. * this function with a different bio if there are other bios
  642. * queued.
  643. */
  644. BUG_ON(tg->service_queue.nr_queued[rw] &&
  645. bio != throtl_peek_queued(&tg->service_queue.queued[rw]));
  646. /* If tg->bps = -1, then BW is unlimited */
  647. if ((bps_limit == U64_MAX && iops_limit == UINT_MAX) ||
  648. tg->flags & THROTL_TG_CANCELING) {
  649. if (wait)
  650. *wait = 0;
  651. return true;
  652. }
  653. /*
  654. * If previous slice expired, start a new one otherwise renew/extend
  655. * existing slice to make sure it is at least throtl_slice interval
  656. * long since now. New slice is started only for empty throttle group.
  657. * If there is queued bio, that means there should be an active
  658. * slice and it should be extended instead.
  659. */
  660. if (throtl_slice_used(tg, rw) && !(tg->service_queue.nr_queued[rw]))
  661. throtl_start_new_slice(tg, rw, true);
  662. else {
  663. if (time_before(tg->slice_end[rw],
  664. jiffies + tg->td->throtl_slice))
  665. throtl_extend_slice(tg, rw,
  666. jiffies + tg->td->throtl_slice);
  667. }
  668. bps_wait = tg_within_bps_limit(tg, bio, bps_limit);
  669. iops_wait = tg_within_iops_limit(tg, bio, iops_limit);
  670. if (bps_wait + iops_wait == 0) {
  671. if (wait)
  672. *wait = 0;
  673. return true;
  674. }
  675. max_wait = max(bps_wait, iops_wait);
  676. if (wait)
  677. *wait = max_wait;
  678. if (time_before(tg->slice_end[rw], jiffies + max_wait))
  679. throtl_extend_slice(tg, rw, jiffies + max_wait);
  680. return false;
  681. }
  682. static void throtl_charge_bio(struct throtl_grp *tg, struct bio *bio)
  683. {
  684. bool rw = bio_data_dir(bio);
  685. unsigned int bio_size = throtl_bio_data_size(bio);
  686. /* Charge the bio to the group */
  687. if (!bio_flagged(bio, BIO_BPS_THROTTLED)) {
  688. tg->bytes_disp[rw] += bio_size;
  689. tg->last_bytes_disp[rw] += bio_size;
  690. }
  691. tg->io_disp[rw]++;
  692. tg->last_io_disp[rw]++;
  693. }
  694. /**
  695. * throtl_add_bio_tg - add a bio to the specified throtl_grp
  696. * @bio: bio to add
  697. * @qn: qnode to use
  698. * @tg: the target throtl_grp
  699. *
  700. * Add @bio to @tg's service_queue using @qn. If @qn is not specified,
  701. * tg->qnode_on_self[] is used.
  702. */
  703. static void throtl_add_bio_tg(struct bio *bio, struct throtl_qnode *qn,
  704. struct throtl_grp *tg)
  705. {
  706. struct throtl_service_queue *sq = &tg->service_queue;
  707. bool rw = bio_data_dir(bio);
  708. if (!qn)
  709. qn = &tg->qnode_on_self[rw];
  710. /*
  711. * If @tg doesn't currently have any bios queued in the same
  712. * direction, queueing @bio can change when @tg should be
  713. * dispatched. Mark that @tg was empty. This is automatically
  714. * cleared on the next tg_update_disptime().
  715. */
  716. if (!sq->nr_queued[rw])
  717. tg->flags |= THROTL_TG_WAS_EMPTY;
  718. throtl_qnode_add_bio(bio, qn, &sq->queued[rw]);
  719. sq->nr_queued[rw]++;
  720. throtl_enqueue_tg(tg);
  721. }
  722. static void tg_update_disptime(struct throtl_grp *tg)
  723. {
  724. struct throtl_service_queue *sq = &tg->service_queue;
  725. unsigned long read_wait = -1, write_wait = -1, min_wait = -1, disptime;
  726. struct bio *bio;
  727. bio = throtl_peek_queued(&sq->queued[READ]);
  728. if (bio)
  729. tg_may_dispatch(tg, bio, &read_wait);
  730. bio = throtl_peek_queued(&sq->queued[WRITE]);
  731. if (bio)
  732. tg_may_dispatch(tg, bio, &write_wait);
  733. min_wait = min(read_wait, write_wait);
  734. disptime = jiffies + min_wait;
  735. /* Update dispatch time */
  736. throtl_rb_erase(&tg->rb_node, tg->service_queue.parent_sq);
  737. tg->disptime = disptime;
  738. tg_service_queue_add(tg);
  739. /* see throtl_add_bio_tg() */
  740. tg->flags &= ~THROTL_TG_WAS_EMPTY;
  741. }
  742. static void start_parent_slice_with_credit(struct throtl_grp *child_tg,
  743. struct throtl_grp *parent_tg, bool rw)
  744. {
  745. if (throtl_slice_used(parent_tg, rw)) {
  746. throtl_start_new_slice_with_credit(parent_tg, rw,
  747. child_tg->slice_start[rw]);
  748. }
  749. }
  750. static void tg_dispatch_one_bio(struct throtl_grp *tg, bool rw)
  751. {
  752. struct throtl_service_queue *sq = &tg->service_queue;
  753. struct throtl_service_queue *parent_sq = sq->parent_sq;
  754. struct throtl_grp *parent_tg = sq_to_tg(parent_sq);
  755. struct throtl_grp *tg_to_put = NULL;
  756. struct bio *bio;
  757. /*
  758. * @bio is being transferred from @tg to @parent_sq. Popping a bio
  759. * from @tg may put its reference and @parent_sq might end up
  760. * getting released prematurely. Remember the tg to put and put it
  761. * after @bio is transferred to @parent_sq.
  762. */
  763. bio = throtl_pop_queued(&sq->queued[rw], &tg_to_put);
  764. sq->nr_queued[rw]--;
  765. throtl_charge_bio(tg, bio);
  766. /*
  767. * If our parent is another tg, we just need to transfer @bio to
  768. * the parent using throtl_add_bio_tg(). If our parent is
  769. * @td->service_queue, @bio is ready to be issued. Put it on its
  770. * bio_lists[] and decrease total number queued. The caller is
  771. * responsible for issuing these bios.
  772. */
  773. if (parent_tg) {
  774. throtl_add_bio_tg(bio, &tg->qnode_on_parent[rw], parent_tg);
  775. start_parent_slice_with_credit(tg, parent_tg, rw);
  776. } else {
  777. bio_set_flag(bio, BIO_BPS_THROTTLED);
  778. throtl_qnode_add_bio(bio, &tg->qnode_on_parent[rw],
  779. &parent_sq->queued[rw]);
  780. BUG_ON(tg->td->nr_queued[rw] <= 0);
  781. tg->td->nr_queued[rw]--;
  782. }
  783. throtl_trim_slice(tg, rw);
  784. if (tg_to_put)
  785. blkg_put(tg_to_blkg(tg_to_put));
  786. }
  787. static int throtl_dispatch_tg(struct throtl_grp *tg)
  788. {
  789. struct throtl_service_queue *sq = &tg->service_queue;
  790. unsigned int nr_reads = 0, nr_writes = 0;
  791. unsigned int max_nr_reads = THROTL_GRP_QUANTUM * 3 / 4;
  792. unsigned int max_nr_writes = THROTL_GRP_QUANTUM - max_nr_reads;
  793. struct bio *bio;
  794. /* Try to dispatch 75% READS and 25% WRITES */
  795. while ((bio = throtl_peek_queued(&sq->queued[READ])) &&
  796. tg_may_dispatch(tg, bio, NULL)) {
  797. tg_dispatch_one_bio(tg, READ);
  798. nr_reads++;
  799. if (nr_reads >= max_nr_reads)
  800. break;
  801. }
  802. while ((bio = throtl_peek_queued(&sq->queued[WRITE])) &&
  803. tg_may_dispatch(tg, bio, NULL)) {
  804. tg_dispatch_one_bio(tg, WRITE);
  805. nr_writes++;
  806. if (nr_writes >= max_nr_writes)
  807. break;
  808. }
  809. return nr_reads + nr_writes;
  810. }
  811. static int throtl_select_dispatch(struct throtl_service_queue *parent_sq)
  812. {
  813. unsigned int nr_disp = 0;
  814. while (1) {
  815. struct throtl_grp *tg;
  816. struct throtl_service_queue *sq;
  817. if (!parent_sq->nr_pending)
  818. break;
  819. tg = throtl_rb_first(parent_sq);
  820. if (!tg)
  821. break;
  822. if (time_before(jiffies, tg->disptime))
  823. break;
  824. nr_disp += throtl_dispatch_tg(tg);
  825. sq = &tg->service_queue;
  826. if (sq->nr_queued[READ] || sq->nr_queued[WRITE])
  827. tg_update_disptime(tg);
  828. else
  829. throtl_dequeue_tg(tg);
  830. if (nr_disp >= THROTL_QUANTUM)
  831. break;
  832. }
  833. return nr_disp;
  834. }
  835. /**
  836. * throtl_pending_timer_fn - timer function for service_queue->pending_timer
  837. * @t: the pending_timer member of the throtl_service_queue being serviced
  838. *
  839. * This timer is armed when a child throtl_grp with active bio's become
  840. * pending and queued on the service_queue's pending_tree and expires when
  841. * the first child throtl_grp should be dispatched. This function
  842. * dispatches bio's from the children throtl_grps to the parent
  843. * service_queue.
  844. *
  845. * If the parent's parent is another throtl_grp, dispatching is propagated
  846. * by either arming its pending_timer or repeating dispatch directly. If
  847. * the top-level service_tree is reached, throtl_data->dispatch_work is
  848. * kicked so that the ready bio's are issued.
  849. */
  850. static void throtl_pending_timer_fn(struct timer_list *t)
  851. {
  852. struct throtl_service_queue *sq = from_timer(sq, t, pending_timer);
  853. struct throtl_grp *tg = sq_to_tg(sq);
  854. struct throtl_data *td = sq_to_td(sq);
  855. struct throtl_service_queue *parent_sq;
  856. struct request_queue *q;
  857. bool dispatched;
  858. int ret;
  859. /* throtl_data may be gone, so figure out request queue by blkg */
  860. if (tg)
  861. q = tg->pd.blkg->q;
  862. else
  863. q = td->queue;
  864. spin_lock_irq(&q->queue_lock);
  865. if (!q->root_blkg)
  866. goto out_unlock;
  867. again:
  868. parent_sq = sq->parent_sq;
  869. dispatched = false;
  870. while (true) {
  871. throtl_log(sq, "dispatch nr_queued=%u read=%u write=%u",
  872. sq->nr_queued[READ] + sq->nr_queued[WRITE],
  873. sq->nr_queued[READ], sq->nr_queued[WRITE]);
  874. ret = throtl_select_dispatch(sq);
  875. if (ret) {
  876. throtl_log(sq, "bios disp=%u", ret);
  877. dispatched = true;
  878. }
  879. if (throtl_schedule_next_dispatch(sq, false))
  880. break;
  881. /* this dispatch windows is still open, relax and repeat */
  882. spin_unlock_irq(&q->queue_lock);
  883. cpu_relax();
  884. spin_lock_irq(&q->queue_lock);
  885. }
  886. if (!dispatched)
  887. goto out_unlock;
  888. if (parent_sq) {
  889. /* @parent_sq is another throl_grp, propagate dispatch */
  890. if (tg->flags & THROTL_TG_WAS_EMPTY) {
  891. tg_update_disptime(tg);
  892. if (!throtl_schedule_next_dispatch(parent_sq, false)) {
  893. /* window is already open, repeat dispatching */
  894. sq = parent_sq;
  895. tg = sq_to_tg(sq);
  896. goto again;
  897. }
  898. }
  899. } else {
  900. /* reached the top-level, queue issuing */
  901. queue_work(kthrotld_workqueue, &td->dispatch_work);
  902. }
  903. out_unlock:
  904. spin_unlock_irq(&q->queue_lock);
  905. }
  906. /**
  907. * blk_throtl_dispatch_work_fn - work function for throtl_data->dispatch_work
  908. * @work: work item being executed
  909. *
  910. * This function is queued for execution when bios reach the bio_lists[]
  911. * of throtl_data->service_queue. Those bios are ready and issued by this
  912. * function.
  913. */
  914. static void blk_throtl_dispatch_work_fn(struct work_struct *work)
  915. {
  916. struct throtl_data *td = container_of(work, struct throtl_data,
  917. dispatch_work);
  918. struct throtl_service_queue *td_sq = &td->service_queue;
  919. struct request_queue *q = td->queue;
  920. struct bio_list bio_list_on_stack;
  921. struct bio *bio;
  922. struct blk_plug plug;
  923. int rw;
  924. bio_list_init(&bio_list_on_stack);
  925. spin_lock_irq(&q->queue_lock);
  926. for (rw = READ; rw <= WRITE; rw++)
  927. while ((bio = throtl_pop_queued(&td_sq->queued[rw], NULL)))
  928. bio_list_add(&bio_list_on_stack, bio);
  929. spin_unlock_irq(&q->queue_lock);
  930. if (!bio_list_empty(&bio_list_on_stack)) {
  931. blk_start_plug(&plug);
  932. while ((bio = bio_list_pop(&bio_list_on_stack)))
  933. submit_bio_noacct_nocheck(bio);
  934. blk_finish_plug(&plug);
  935. }
  936. }
  937. static u64 tg_prfill_conf_u64(struct seq_file *sf, struct blkg_policy_data *pd,
  938. int off)
  939. {
  940. struct throtl_grp *tg = pd_to_tg(pd);
  941. u64 v = *(u64 *)((void *)tg + off);
  942. if (v == U64_MAX)
  943. return 0;
  944. return __blkg_prfill_u64(sf, pd, v);
  945. }
  946. static u64 tg_prfill_conf_uint(struct seq_file *sf, struct blkg_policy_data *pd,
  947. int off)
  948. {
  949. struct throtl_grp *tg = pd_to_tg(pd);
  950. unsigned int v = *(unsigned int *)((void *)tg + off);
  951. if (v == UINT_MAX)
  952. return 0;
  953. return __blkg_prfill_u64(sf, pd, v);
  954. }
  955. static int tg_print_conf_u64(struct seq_file *sf, void *v)
  956. {
  957. blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_conf_u64,
  958. &blkcg_policy_throtl, seq_cft(sf)->private, false);
  959. return 0;
  960. }
  961. static int tg_print_conf_uint(struct seq_file *sf, void *v)
  962. {
  963. blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_conf_uint,
  964. &blkcg_policy_throtl, seq_cft(sf)->private, false);
  965. return 0;
  966. }
  967. static void tg_conf_updated(struct throtl_grp *tg, bool global)
  968. {
  969. struct throtl_service_queue *sq = &tg->service_queue;
  970. struct cgroup_subsys_state *pos_css;
  971. struct blkcg_gq *blkg;
  972. throtl_log(&tg->service_queue,
  973. "limit change rbps=%llu wbps=%llu riops=%u wiops=%u",
  974. tg_bps_limit(tg, READ), tg_bps_limit(tg, WRITE),
  975. tg_iops_limit(tg, READ), tg_iops_limit(tg, WRITE));
  976. rcu_read_lock();
  977. /*
  978. * Update has_rules[] flags for the updated tg's subtree. A tg is
  979. * considered to have rules if either the tg itself or any of its
  980. * ancestors has rules. This identifies groups without any
  981. * restrictions in the whole hierarchy and allows them to bypass
  982. * blk-throttle.
  983. */
  984. blkg_for_each_descendant_pre(blkg, pos_css,
  985. global ? tg->td->queue->root_blkg : tg_to_blkg(tg)) {
  986. struct throtl_grp *this_tg = blkg_to_tg(blkg);
  987. tg_update_has_rules(this_tg);
  988. /* ignore root/second level */
  989. if (!cgroup_subsys_on_dfl(io_cgrp_subsys) || !blkg->parent ||
  990. !blkg->parent->parent)
  991. continue;
  992. }
  993. rcu_read_unlock();
  994. /*
  995. * We're already holding queue_lock and know @tg is valid. Let's
  996. * apply the new config directly.
  997. *
  998. * Restart the slices for both READ and WRITES. It might happen
  999. * that a group's limit are dropped suddenly and we don't want to
  1000. * account recently dispatched IO with new low rate.
  1001. */
  1002. throtl_start_new_slice(tg, READ, false);
  1003. throtl_start_new_slice(tg, WRITE, false);
  1004. if (tg->flags & THROTL_TG_PENDING) {
  1005. tg_update_disptime(tg);
  1006. throtl_schedule_next_dispatch(sq->parent_sq, true);
  1007. }
  1008. }
  1009. static int blk_throtl_init(struct gendisk *disk)
  1010. {
  1011. struct request_queue *q = disk->queue;
  1012. struct throtl_data *td;
  1013. int ret;
  1014. td = kzalloc_node(sizeof(*td), GFP_KERNEL, q->node);
  1015. if (!td)
  1016. return -ENOMEM;
  1017. INIT_WORK(&td->dispatch_work, blk_throtl_dispatch_work_fn);
  1018. throtl_service_queue_init(&td->service_queue);
  1019. /*
  1020. * Freeze queue before activating policy, to synchronize with IO path,
  1021. * which is protected by 'q_usage_counter'.
  1022. */
  1023. blk_mq_freeze_queue(disk->queue);
  1024. blk_mq_quiesce_queue(disk->queue);
  1025. q->td = td;
  1026. td->queue = q;
  1027. /* activate policy */
  1028. ret = blkcg_activate_policy(disk, &blkcg_policy_throtl);
  1029. if (ret) {
  1030. q->td = NULL;
  1031. kfree(td);
  1032. goto out;
  1033. }
  1034. if (blk_queue_nonrot(q))
  1035. td->throtl_slice = DFL_THROTL_SLICE_SSD;
  1036. else
  1037. td->throtl_slice = DFL_THROTL_SLICE_HD;
  1038. td->track_bio_latency = !queue_is_mq(q);
  1039. if (!td->track_bio_latency)
  1040. blk_stat_enable_accounting(q);
  1041. out:
  1042. blk_mq_unquiesce_queue(disk->queue);
  1043. blk_mq_unfreeze_queue(disk->queue);
  1044. return ret;
  1045. }
  1046. static ssize_t tg_set_conf(struct kernfs_open_file *of,
  1047. char *buf, size_t nbytes, loff_t off, bool is_u64)
  1048. {
  1049. struct blkcg *blkcg = css_to_blkcg(of_css(of));
  1050. struct blkg_conf_ctx ctx;
  1051. struct throtl_grp *tg;
  1052. int ret;
  1053. u64 v;
  1054. blkg_conf_init(&ctx, buf);
  1055. ret = blkg_conf_open_bdev(&ctx);
  1056. if (ret)
  1057. goto out_finish;
  1058. if (!blk_throtl_activated(ctx.bdev->bd_queue)) {
  1059. ret = blk_throtl_init(ctx.bdev->bd_disk);
  1060. if (ret)
  1061. goto out_finish;
  1062. }
  1063. ret = blkg_conf_prep(blkcg, &blkcg_policy_throtl, &ctx);
  1064. if (ret)
  1065. goto out_finish;
  1066. ret = -EINVAL;
  1067. if (sscanf(ctx.body, "%llu", &v) != 1)
  1068. goto out_finish;
  1069. if (!v)
  1070. v = U64_MAX;
  1071. tg = blkg_to_tg(ctx.blkg);
  1072. tg_update_carryover(tg);
  1073. if (is_u64)
  1074. *(u64 *)((void *)tg + of_cft(of)->private) = v;
  1075. else
  1076. *(unsigned int *)((void *)tg + of_cft(of)->private) = v;
  1077. tg_conf_updated(tg, false);
  1078. ret = 0;
  1079. out_finish:
  1080. blkg_conf_exit(&ctx);
  1081. return ret ?: nbytes;
  1082. }
  1083. static ssize_t tg_set_conf_u64(struct kernfs_open_file *of,
  1084. char *buf, size_t nbytes, loff_t off)
  1085. {
  1086. return tg_set_conf(of, buf, nbytes, off, true);
  1087. }
  1088. static ssize_t tg_set_conf_uint(struct kernfs_open_file *of,
  1089. char *buf, size_t nbytes, loff_t off)
  1090. {
  1091. return tg_set_conf(of, buf, nbytes, off, false);
  1092. }
  1093. static int tg_print_rwstat(struct seq_file *sf, void *v)
  1094. {
  1095. blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
  1096. blkg_prfill_rwstat, &blkcg_policy_throtl,
  1097. seq_cft(sf)->private, true);
  1098. return 0;
  1099. }
  1100. static u64 tg_prfill_rwstat_recursive(struct seq_file *sf,
  1101. struct blkg_policy_data *pd, int off)
  1102. {
  1103. struct blkg_rwstat_sample sum;
  1104. blkg_rwstat_recursive_sum(pd_to_blkg(pd), &blkcg_policy_throtl, off,
  1105. &sum);
  1106. return __blkg_prfill_rwstat(sf, pd, &sum);
  1107. }
  1108. static int tg_print_rwstat_recursive(struct seq_file *sf, void *v)
  1109. {
  1110. blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
  1111. tg_prfill_rwstat_recursive, &blkcg_policy_throtl,
  1112. seq_cft(sf)->private, true);
  1113. return 0;
  1114. }
  1115. static struct cftype throtl_legacy_files[] = {
  1116. {
  1117. .name = "throttle.read_bps_device",
  1118. .private = offsetof(struct throtl_grp, bps[READ]),
  1119. .seq_show = tg_print_conf_u64,
  1120. .write = tg_set_conf_u64,
  1121. },
  1122. {
  1123. .name = "throttle.write_bps_device",
  1124. .private = offsetof(struct throtl_grp, bps[WRITE]),
  1125. .seq_show = tg_print_conf_u64,
  1126. .write = tg_set_conf_u64,
  1127. },
  1128. {
  1129. .name = "throttle.read_iops_device",
  1130. .private = offsetof(struct throtl_grp, iops[READ]),
  1131. .seq_show = tg_print_conf_uint,
  1132. .write = tg_set_conf_uint,
  1133. },
  1134. {
  1135. .name = "throttle.write_iops_device",
  1136. .private = offsetof(struct throtl_grp, iops[WRITE]),
  1137. .seq_show = tg_print_conf_uint,
  1138. .write = tg_set_conf_uint,
  1139. },
  1140. {
  1141. .name = "throttle.io_service_bytes",
  1142. .private = offsetof(struct throtl_grp, stat_bytes),
  1143. .seq_show = tg_print_rwstat,
  1144. },
  1145. {
  1146. .name = "throttle.io_service_bytes_recursive",
  1147. .private = offsetof(struct throtl_grp, stat_bytes),
  1148. .seq_show = tg_print_rwstat_recursive,
  1149. },
  1150. {
  1151. .name = "throttle.io_serviced",
  1152. .private = offsetof(struct throtl_grp, stat_ios),
  1153. .seq_show = tg_print_rwstat,
  1154. },
  1155. {
  1156. .name = "throttle.io_serviced_recursive",
  1157. .private = offsetof(struct throtl_grp, stat_ios),
  1158. .seq_show = tg_print_rwstat_recursive,
  1159. },
  1160. { } /* terminate */
  1161. };
  1162. static u64 tg_prfill_limit(struct seq_file *sf, struct blkg_policy_data *pd,
  1163. int off)
  1164. {
  1165. struct throtl_grp *tg = pd_to_tg(pd);
  1166. const char *dname = blkg_dev_name(pd->blkg);
  1167. u64 bps_dft;
  1168. unsigned int iops_dft;
  1169. if (!dname)
  1170. return 0;
  1171. bps_dft = U64_MAX;
  1172. iops_dft = UINT_MAX;
  1173. if (tg->bps[READ] == bps_dft &&
  1174. tg->bps[WRITE] == bps_dft &&
  1175. tg->iops[READ] == iops_dft &&
  1176. tg->iops[WRITE] == iops_dft)
  1177. return 0;
  1178. seq_printf(sf, "%s", dname);
  1179. if (tg->bps[READ] == U64_MAX)
  1180. seq_printf(sf, " rbps=max");
  1181. else
  1182. seq_printf(sf, " rbps=%llu", tg->bps[READ]);
  1183. if (tg->bps[WRITE] == U64_MAX)
  1184. seq_printf(sf, " wbps=max");
  1185. else
  1186. seq_printf(sf, " wbps=%llu", tg->bps[WRITE]);
  1187. if (tg->iops[READ] == UINT_MAX)
  1188. seq_printf(sf, " riops=max");
  1189. else
  1190. seq_printf(sf, " riops=%u", tg->iops[READ]);
  1191. if (tg->iops[WRITE] == UINT_MAX)
  1192. seq_printf(sf, " wiops=max");
  1193. else
  1194. seq_printf(sf, " wiops=%u", tg->iops[WRITE]);
  1195. seq_printf(sf, "\n");
  1196. return 0;
  1197. }
  1198. static int tg_print_limit(struct seq_file *sf, void *v)
  1199. {
  1200. blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_limit,
  1201. &blkcg_policy_throtl, seq_cft(sf)->private, false);
  1202. return 0;
  1203. }
  1204. static ssize_t tg_set_limit(struct kernfs_open_file *of,
  1205. char *buf, size_t nbytes, loff_t off)
  1206. {
  1207. struct blkcg *blkcg = css_to_blkcg(of_css(of));
  1208. struct blkg_conf_ctx ctx;
  1209. struct throtl_grp *tg;
  1210. u64 v[4];
  1211. int ret;
  1212. blkg_conf_init(&ctx, buf);
  1213. ret = blkg_conf_open_bdev(&ctx);
  1214. if (ret)
  1215. goto out_finish;
  1216. if (!blk_throtl_activated(ctx.bdev->bd_queue)) {
  1217. ret = blk_throtl_init(ctx.bdev->bd_disk);
  1218. if (ret)
  1219. goto out_finish;
  1220. }
  1221. ret = blkg_conf_prep(blkcg, &blkcg_policy_throtl, &ctx);
  1222. if (ret)
  1223. goto out_finish;
  1224. tg = blkg_to_tg(ctx.blkg);
  1225. tg_update_carryover(tg);
  1226. v[0] = tg->bps[READ];
  1227. v[1] = tg->bps[WRITE];
  1228. v[2] = tg->iops[READ];
  1229. v[3] = tg->iops[WRITE];
  1230. while (true) {
  1231. char tok[27]; /* wiops=18446744073709551616 */
  1232. char *p;
  1233. u64 val = U64_MAX;
  1234. int len;
  1235. if (sscanf(ctx.body, "%26s%n", tok, &len) != 1)
  1236. break;
  1237. if (tok[0] == '\0')
  1238. break;
  1239. ctx.body += len;
  1240. ret = -EINVAL;
  1241. p = tok;
  1242. strsep(&p, "=");
  1243. if (!p || (sscanf(p, "%llu", &val) != 1 && strcmp(p, "max")))
  1244. goto out_finish;
  1245. ret = -ERANGE;
  1246. if (!val)
  1247. goto out_finish;
  1248. ret = -EINVAL;
  1249. if (!strcmp(tok, "rbps") && val > 1)
  1250. v[0] = val;
  1251. else if (!strcmp(tok, "wbps") && val > 1)
  1252. v[1] = val;
  1253. else if (!strcmp(tok, "riops") && val > 1)
  1254. v[2] = min_t(u64, val, UINT_MAX);
  1255. else if (!strcmp(tok, "wiops") && val > 1)
  1256. v[3] = min_t(u64, val, UINT_MAX);
  1257. else
  1258. goto out_finish;
  1259. }
  1260. tg->bps[READ] = v[0];
  1261. tg->bps[WRITE] = v[1];
  1262. tg->iops[READ] = v[2];
  1263. tg->iops[WRITE] = v[3];
  1264. tg_conf_updated(tg, false);
  1265. ret = 0;
  1266. out_finish:
  1267. blkg_conf_exit(&ctx);
  1268. return ret ?: nbytes;
  1269. }
  1270. static struct cftype throtl_files[] = {
  1271. {
  1272. .name = "max",
  1273. .flags = CFTYPE_NOT_ON_ROOT,
  1274. .seq_show = tg_print_limit,
  1275. .write = tg_set_limit,
  1276. },
  1277. { } /* terminate */
  1278. };
  1279. static void throtl_shutdown_wq(struct request_queue *q)
  1280. {
  1281. struct throtl_data *td = q->td;
  1282. cancel_work_sync(&td->dispatch_work);
  1283. }
  1284. struct blkcg_policy blkcg_policy_throtl = {
  1285. .dfl_cftypes = throtl_files,
  1286. .legacy_cftypes = throtl_legacy_files,
  1287. .pd_alloc_fn = throtl_pd_alloc,
  1288. .pd_init_fn = throtl_pd_init,
  1289. .pd_online_fn = throtl_pd_online,
  1290. .pd_free_fn = throtl_pd_free,
  1291. };
  1292. void blk_throtl_cancel_bios(struct gendisk *disk)
  1293. {
  1294. struct request_queue *q = disk->queue;
  1295. struct cgroup_subsys_state *pos_css;
  1296. struct blkcg_gq *blkg;
  1297. if (!blk_throtl_activated(q))
  1298. return;
  1299. spin_lock_irq(&q->queue_lock);
  1300. /*
  1301. * queue_lock is held, rcu lock is not needed here technically.
  1302. * However, rcu lock is still held to emphasize that following
  1303. * path need RCU protection and to prevent warning from lockdep.
  1304. */
  1305. rcu_read_lock();
  1306. blkg_for_each_descendant_post(blkg, pos_css, q->root_blkg) {
  1307. struct throtl_grp *tg = blkg_to_tg(blkg);
  1308. struct throtl_service_queue *sq = &tg->service_queue;
  1309. /*
  1310. * Set the flag to make sure throtl_pending_timer_fn() won't
  1311. * stop until all throttled bios are dispatched.
  1312. */
  1313. tg->flags |= THROTL_TG_CANCELING;
  1314. /*
  1315. * Do not dispatch cgroup without THROTL_TG_PENDING or cgroup
  1316. * will be inserted to service queue without THROTL_TG_PENDING
  1317. * set in tg_update_disptime below. Then IO dispatched from
  1318. * child in tg_dispatch_one_bio will trigger double insertion
  1319. * and corrupt the tree.
  1320. */
  1321. if (!(tg->flags & THROTL_TG_PENDING))
  1322. continue;
  1323. /*
  1324. * Update disptime after setting the above flag to make sure
  1325. * throtl_select_dispatch() won't exit without dispatching.
  1326. */
  1327. tg_update_disptime(tg);
  1328. throtl_schedule_pending_timer(sq, jiffies + 1);
  1329. }
  1330. rcu_read_unlock();
  1331. spin_unlock_irq(&q->queue_lock);
  1332. }
  1333. static bool tg_within_limit(struct throtl_grp *tg, struct bio *bio, bool rw)
  1334. {
  1335. /* throtl is FIFO - if bios are already queued, should queue */
  1336. if (tg->service_queue.nr_queued[rw])
  1337. return false;
  1338. return tg_may_dispatch(tg, bio, NULL);
  1339. }
  1340. bool __blk_throtl_bio(struct bio *bio)
  1341. {
  1342. struct request_queue *q = bdev_get_queue(bio->bi_bdev);
  1343. struct blkcg_gq *blkg = bio->bi_blkg;
  1344. struct throtl_qnode *qn = NULL;
  1345. struct throtl_grp *tg = blkg_to_tg(blkg);
  1346. struct throtl_service_queue *sq;
  1347. bool rw = bio_data_dir(bio);
  1348. bool throttled = false;
  1349. struct throtl_data *td = tg->td;
  1350. rcu_read_lock();
  1351. spin_lock_irq(&q->queue_lock);
  1352. sq = &tg->service_queue;
  1353. while (true) {
  1354. if (tg_within_limit(tg, bio, rw)) {
  1355. /* within limits, let's charge and dispatch directly */
  1356. throtl_charge_bio(tg, bio);
  1357. /*
  1358. * We need to trim slice even when bios are not being
  1359. * queued otherwise it might happen that a bio is not
  1360. * queued for a long time and slice keeps on extending
  1361. * and trim is not called for a long time. Now if limits
  1362. * are reduced suddenly we take into account all the IO
  1363. * dispatched so far at new low rate and * newly queued
  1364. * IO gets a really long dispatch time.
  1365. *
  1366. * So keep on trimming slice even if bio is not queued.
  1367. */
  1368. throtl_trim_slice(tg, rw);
  1369. } else if (bio_issue_as_root_blkg(bio)) {
  1370. /*
  1371. * IOs which may cause priority inversions are
  1372. * dispatched directly, even if they're over limit.
  1373. *
  1374. * Charge and dispatch directly, and our throttle
  1375. * control algorithm is adaptive, and extra IO bytes
  1376. * will be throttled for paying the debt
  1377. */
  1378. throtl_charge_bio(tg, bio);
  1379. } else {
  1380. /* if above limits, break to queue */
  1381. break;
  1382. }
  1383. /*
  1384. * @bio passed through this layer without being throttled.
  1385. * Climb up the ladder. If we're already at the top, it
  1386. * can be executed directly.
  1387. */
  1388. qn = &tg->qnode_on_parent[rw];
  1389. sq = sq->parent_sq;
  1390. tg = sq_to_tg(sq);
  1391. if (!tg) {
  1392. bio_set_flag(bio, BIO_BPS_THROTTLED);
  1393. goto out_unlock;
  1394. }
  1395. }
  1396. /* out-of-limit, queue to @tg */
  1397. throtl_log(sq, "[%c] bio. bdisp=%llu sz=%u bps=%llu iodisp=%u iops=%u queued=%d/%d",
  1398. rw == READ ? 'R' : 'W',
  1399. tg->bytes_disp[rw], bio->bi_iter.bi_size,
  1400. tg_bps_limit(tg, rw),
  1401. tg->io_disp[rw], tg_iops_limit(tg, rw),
  1402. sq->nr_queued[READ], sq->nr_queued[WRITE]);
  1403. td->nr_queued[rw]++;
  1404. throtl_add_bio_tg(bio, qn, tg);
  1405. throttled = true;
  1406. /*
  1407. * Update @tg's dispatch time and force schedule dispatch if @tg
  1408. * was empty before @bio. The forced scheduling isn't likely to
  1409. * cause undue delay as @bio is likely to be dispatched directly if
  1410. * its @tg's disptime is not in the future.
  1411. */
  1412. if (tg->flags & THROTL_TG_WAS_EMPTY) {
  1413. tg_update_disptime(tg);
  1414. throtl_schedule_next_dispatch(tg->service_queue.parent_sq, true);
  1415. }
  1416. out_unlock:
  1417. spin_unlock_irq(&q->queue_lock);
  1418. rcu_read_unlock();
  1419. return throttled;
  1420. }
  1421. void blk_throtl_exit(struct gendisk *disk)
  1422. {
  1423. struct request_queue *q = disk->queue;
  1424. if (!blk_throtl_activated(q))
  1425. return;
  1426. del_timer_sync(&q->td->service_queue.pending_timer);
  1427. throtl_shutdown_wq(q);
  1428. blkcg_deactivate_policy(disk, &blkcg_policy_throtl);
  1429. kfree(q->td);
  1430. }
  1431. static int __init throtl_init(void)
  1432. {
  1433. kthrotld_workqueue = alloc_workqueue("kthrotld", WQ_MEM_RECLAIM, 0);
  1434. if (!kthrotld_workqueue)
  1435. panic("Failed to create kthrotld\n");
  1436. return blkcg_policy_register(&blkcg_policy_throtl);
  1437. }
  1438. module_init(throtl_init);