blk-throttle.c 46 KB

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