blk-iolatency.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Block rq-qos base io controller
  4. *
  5. * This works similar to wbt with a few exceptions
  6. *
  7. * - It's bio based, so the latency covers the whole block layer in addition to
  8. * the actual io.
  9. * - We will throttle all IO that comes in here if we need to.
  10. * - We use the mean latency over the 100ms window. This is because writes can
  11. * be particularly fast, which could give us a false sense of the impact of
  12. * other workloads on our protected workload.
  13. * - By default there's no throttling, we set the queue_depth to UINT_MAX so
  14. * that we can have as many outstanding bio's as we're allowed to. Only at
  15. * throttle time do we pay attention to the actual queue depth.
  16. *
  17. * The hierarchy works like the cpu controller does, we track the latency at
  18. * every configured node, and each configured node has it's own independent
  19. * queue depth. This means that we only care about our latency targets at the
  20. * peer level. Some group at the bottom of the hierarchy isn't going to affect
  21. * a group at the end of some other path if we're only configred at leaf level.
  22. *
  23. * Consider the following
  24. *
  25. * root blkg
  26. * / \
  27. * fast (target=5ms) slow (target=10ms)
  28. * / \ / \
  29. * a b normal(15ms) unloved
  30. *
  31. * "a" and "b" have no target, but their combined io under "fast" cannot exceed
  32. * an average latency of 5ms. If it does then we will throttle the "slow"
  33. * group. In the case of "normal", if it exceeds its 15ms target, we will
  34. * throttle "unloved", but nobody else.
  35. *
  36. * In this example "fast", "slow", and "normal" will be the only groups actually
  37. * accounting their io latencies. We have to walk up the heirarchy to the root
  38. * on every submit and complete so we can do the appropriate stat recording and
  39. * adjust the queue depth of ourselves if needed.
  40. *
  41. * There are 2 ways we throttle IO.
  42. *
  43. * 1) Queue depth throttling. As we throttle down we will adjust the maximum
  44. * number of IO's we're allowed to have in flight. This starts at (u64)-1 down
  45. * to 1. If the group is only ever submitting IO for itself then this is the
  46. * only way we throttle.
  47. *
  48. * 2) Induced delay throttling. This is for the case that a group is generating
  49. * IO that has to be issued by the root cg to avoid priority inversion. So think
  50. * REQ_META or REQ_SWAP. If we are already at qd == 1 and we're getting a lot
  51. * of work done for us on behalf of the root cg and are being asked to scale
  52. * down more then we induce a latency at userspace return. We accumulate the
  53. * total amount of time we need to be punished by doing
  54. *
  55. * total_time += min_lat_nsec - actual_io_completion
  56. *
  57. * and then at throttle time will do
  58. *
  59. * throttle_time = min(total_time, NSEC_PER_SEC)
  60. *
  61. * This induced delay will throttle back the activity that is generating the
  62. * root cg issued io's, wethere that's some metadata intensive operation or the
  63. * group is using so much memory that it is pushing us into swap.
  64. *
  65. * Copyright (C) 2018 Josef Bacik
  66. */
  67. #include <linux/kernel.h>
  68. #include <linux/blk_types.h>
  69. #include <linux/backing-dev.h>
  70. #include <linux/module.h>
  71. #include <linux/timer.h>
  72. #include <linux/memcontrol.h>
  73. #include <linux/sched/loadavg.h>
  74. #include <linux/sched/signal.h>
  75. #include <trace/events/block.h>
  76. #include <linux/blk-mq.h>
  77. #include "blk-rq-qos.h"
  78. #include "blk-stat.h"
  79. #include "blk-cgroup.h"
  80. #include "blk.h"
  81. #define DEFAULT_SCALE_COOKIE 1000000U
  82. static struct blkcg_policy blkcg_policy_iolatency;
  83. struct iolatency_grp;
  84. struct blk_iolatency {
  85. struct rq_qos rqos;
  86. struct timer_list timer;
  87. /*
  88. * ->enabled is the master enable switch gating the throttling logic and
  89. * inflight tracking. The number of cgroups which have iolat enabled is
  90. * tracked in ->enable_cnt, and ->enable is flipped on/off accordingly
  91. * from ->enable_work with the request_queue frozen. For details, See
  92. * blkiolatency_enable_work_fn().
  93. */
  94. bool enabled;
  95. atomic_t enable_cnt;
  96. struct work_struct enable_work;
  97. };
  98. static inline struct blk_iolatency *BLKIOLATENCY(struct rq_qos *rqos)
  99. {
  100. return container_of(rqos, struct blk_iolatency, rqos);
  101. }
  102. struct child_latency_info {
  103. spinlock_t lock;
  104. /* Last time we adjusted the scale of everybody. */
  105. u64 last_scale_event;
  106. /* The latency that we missed. */
  107. u64 scale_lat;
  108. /* Total io's from all of our children for the last summation. */
  109. u64 nr_samples;
  110. /* The guy who actually changed the latency numbers. */
  111. struct iolatency_grp *scale_grp;
  112. /* Cookie to tell if we need to scale up or down. */
  113. atomic_t scale_cookie;
  114. };
  115. struct percentile_stats {
  116. u64 total;
  117. u64 missed;
  118. };
  119. struct latency_stat {
  120. union {
  121. struct percentile_stats ps;
  122. struct blk_rq_stat rqs;
  123. };
  124. };
  125. struct iolatency_grp {
  126. struct blkg_policy_data pd;
  127. struct latency_stat __percpu *stats;
  128. struct latency_stat cur_stat;
  129. struct blk_iolatency *blkiolat;
  130. struct rq_depth rq_depth;
  131. struct rq_wait rq_wait;
  132. atomic64_t window_start;
  133. atomic_t scale_cookie;
  134. u64 min_lat_nsec;
  135. u64 cur_win_nsec;
  136. /* total running average of our io latency. */
  137. u64 lat_avg;
  138. /* Our current number of IO's for the last summation. */
  139. u64 nr_samples;
  140. bool ssd;
  141. struct child_latency_info child_lat;
  142. };
  143. #define BLKIOLATENCY_MIN_WIN_SIZE (100 * NSEC_PER_MSEC)
  144. #define BLKIOLATENCY_MAX_WIN_SIZE NSEC_PER_SEC
  145. /*
  146. * These are the constants used to fake the fixed-point moving average
  147. * calculation just like load average. The call to calc_load() folds
  148. * (FIXED_1 (2048) - exp_factor) * new_sample into lat_avg. The sampling
  149. * window size is bucketed to try to approximately calculate average
  150. * latency such that 1/exp (decay rate) is [1 min, 2.5 min) when windows
  151. * elapse immediately. Note, windows only elapse with IO activity. Idle
  152. * periods extend the most recent window.
  153. */
  154. #define BLKIOLATENCY_NR_EXP_FACTORS 5
  155. #define BLKIOLATENCY_EXP_BUCKET_SIZE (BLKIOLATENCY_MAX_WIN_SIZE / \
  156. (BLKIOLATENCY_NR_EXP_FACTORS - 1))
  157. static const u64 iolatency_exp_factors[BLKIOLATENCY_NR_EXP_FACTORS] = {
  158. 2045, // exp(1/600) - 600 samples
  159. 2039, // exp(1/240) - 240 samples
  160. 2031, // exp(1/120) - 120 samples
  161. 2023, // exp(1/80) - 80 samples
  162. 2014, // exp(1/60) - 60 samples
  163. };
  164. static inline struct iolatency_grp *pd_to_lat(struct blkg_policy_data *pd)
  165. {
  166. return pd ? container_of(pd, struct iolatency_grp, pd) : NULL;
  167. }
  168. static inline struct iolatency_grp *blkg_to_lat(struct blkcg_gq *blkg)
  169. {
  170. return pd_to_lat(blkg_to_pd(blkg, &blkcg_policy_iolatency));
  171. }
  172. static inline struct blkcg_gq *lat_to_blkg(struct iolatency_grp *iolat)
  173. {
  174. return pd_to_blkg(&iolat->pd);
  175. }
  176. static inline void latency_stat_init(struct iolatency_grp *iolat,
  177. struct latency_stat *stat)
  178. {
  179. if (iolat->ssd) {
  180. stat->ps.total = 0;
  181. stat->ps.missed = 0;
  182. } else
  183. blk_rq_stat_init(&stat->rqs);
  184. }
  185. static inline void latency_stat_sum(struct iolatency_grp *iolat,
  186. struct latency_stat *sum,
  187. struct latency_stat *stat)
  188. {
  189. if (iolat->ssd) {
  190. sum->ps.total += stat->ps.total;
  191. sum->ps.missed += stat->ps.missed;
  192. } else
  193. blk_rq_stat_sum(&sum->rqs, &stat->rqs);
  194. }
  195. static inline void latency_stat_record_time(struct iolatency_grp *iolat,
  196. u64 req_time)
  197. {
  198. struct latency_stat *stat = get_cpu_ptr(iolat->stats);
  199. if (iolat->ssd) {
  200. if (req_time >= iolat->min_lat_nsec)
  201. stat->ps.missed++;
  202. stat->ps.total++;
  203. } else
  204. blk_rq_stat_add(&stat->rqs, req_time);
  205. put_cpu_ptr(stat);
  206. }
  207. static inline bool latency_sum_ok(struct iolatency_grp *iolat,
  208. struct latency_stat *stat)
  209. {
  210. if (iolat->ssd) {
  211. u64 thresh = div64_u64(stat->ps.total, 10);
  212. thresh = max(thresh, 1ULL);
  213. return stat->ps.missed < thresh;
  214. }
  215. return stat->rqs.mean <= iolat->min_lat_nsec;
  216. }
  217. static inline u64 latency_stat_samples(struct iolatency_grp *iolat,
  218. struct latency_stat *stat)
  219. {
  220. if (iolat->ssd)
  221. return stat->ps.total;
  222. return stat->rqs.nr_samples;
  223. }
  224. static inline void iolat_update_total_lat_avg(struct iolatency_grp *iolat,
  225. struct latency_stat *stat)
  226. {
  227. int exp_idx;
  228. if (iolat->ssd)
  229. return;
  230. /*
  231. * calc_load() takes in a number stored in fixed point representation.
  232. * Because we are using this for IO time in ns, the values stored
  233. * are significantly larger than the FIXED_1 denominator (2048).
  234. * Therefore, rounding errors in the calculation are negligible and
  235. * can be ignored.
  236. */
  237. exp_idx = min_t(int, BLKIOLATENCY_NR_EXP_FACTORS - 1,
  238. div64_u64(iolat->cur_win_nsec,
  239. BLKIOLATENCY_EXP_BUCKET_SIZE));
  240. iolat->lat_avg = calc_load(iolat->lat_avg,
  241. iolatency_exp_factors[exp_idx],
  242. stat->rqs.mean);
  243. }
  244. static void iolat_cleanup_cb(struct rq_wait *rqw, void *private_data)
  245. {
  246. atomic_dec(&rqw->inflight);
  247. wake_up(&rqw->wait);
  248. }
  249. static bool iolat_acquire_inflight(struct rq_wait *rqw, void *private_data)
  250. {
  251. struct iolatency_grp *iolat = private_data;
  252. return rq_wait_inc_below(rqw, iolat->rq_depth.max_depth);
  253. }
  254. static void __blkcg_iolatency_throttle(struct rq_qos *rqos,
  255. struct iolatency_grp *iolat,
  256. bool issue_as_root,
  257. bool use_memdelay)
  258. {
  259. struct rq_wait *rqw = &iolat->rq_wait;
  260. unsigned use_delay = atomic_read(&lat_to_blkg(iolat)->use_delay);
  261. if (use_delay)
  262. blkcg_schedule_throttle(rqos->q->disk, use_memdelay);
  263. /*
  264. * To avoid priority inversions we want to just take a slot if we are
  265. * issuing as root. If we're being killed off there's no point in
  266. * delaying things, we may have been killed by OOM so throttling may
  267. * make recovery take even longer, so just let the IO's through so the
  268. * task can go away.
  269. */
  270. if (issue_as_root || fatal_signal_pending(current)) {
  271. atomic_inc(&rqw->inflight);
  272. return;
  273. }
  274. rq_qos_wait(rqw, iolat, iolat_acquire_inflight, iolat_cleanup_cb);
  275. }
  276. #define SCALE_DOWN_FACTOR 2
  277. #define SCALE_UP_FACTOR 4
  278. static inline unsigned long scale_amount(unsigned long qd, bool up)
  279. {
  280. return max(up ? qd >> SCALE_UP_FACTOR : qd >> SCALE_DOWN_FACTOR, 1UL);
  281. }
  282. /*
  283. * We scale the qd down faster than we scale up, so we need to use this helper
  284. * to adjust the scale_cookie accordingly so we don't prematurely get
  285. * scale_cookie at DEFAULT_SCALE_COOKIE and unthrottle too much.
  286. *
  287. * Each group has their own local copy of the last scale cookie they saw, so if
  288. * the global scale cookie goes up or down they know which way they need to go
  289. * based on their last knowledge of it.
  290. */
  291. static void scale_cookie_change(struct blk_iolatency *blkiolat,
  292. struct child_latency_info *lat_info,
  293. bool up)
  294. {
  295. unsigned long qd = blkiolat->rqos.q->nr_requests;
  296. unsigned long scale = scale_amount(qd, up);
  297. unsigned long old = atomic_read(&lat_info->scale_cookie);
  298. unsigned long max_scale = qd << 1;
  299. unsigned long diff = 0;
  300. if (old < DEFAULT_SCALE_COOKIE)
  301. diff = DEFAULT_SCALE_COOKIE - old;
  302. if (up) {
  303. if (scale + old > DEFAULT_SCALE_COOKIE)
  304. atomic_set(&lat_info->scale_cookie,
  305. DEFAULT_SCALE_COOKIE);
  306. else if (diff > qd)
  307. atomic_inc(&lat_info->scale_cookie);
  308. else
  309. atomic_add(scale, &lat_info->scale_cookie);
  310. } else {
  311. /*
  312. * We don't want to dig a hole so deep that it takes us hours to
  313. * dig out of it. Just enough that we don't throttle/unthrottle
  314. * with jagged workloads but can still unthrottle once pressure
  315. * has sufficiently dissipated.
  316. */
  317. if (diff > qd) {
  318. if (diff < max_scale)
  319. atomic_dec(&lat_info->scale_cookie);
  320. } else {
  321. atomic_sub(scale, &lat_info->scale_cookie);
  322. }
  323. }
  324. }
  325. /*
  326. * Change the queue depth of the iolatency_grp. We add/subtract 1/16th of the
  327. * queue depth at a time so we don't get wild swings and hopefully dial in to
  328. * fairer distribution of the overall queue depth.
  329. */
  330. static void scale_change(struct iolatency_grp *iolat, bool up)
  331. {
  332. unsigned long qd = iolat->blkiolat->rqos.q->nr_requests;
  333. unsigned long scale = scale_amount(qd, up);
  334. unsigned long old = iolat->rq_depth.max_depth;
  335. if (old > qd)
  336. old = qd;
  337. if (up) {
  338. if (old == 1 && blkcg_unuse_delay(lat_to_blkg(iolat)))
  339. return;
  340. if (old < qd) {
  341. old += scale;
  342. old = min(old, qd);
  343. iolat->rq_depth.max_depth = old;
  344. wake_up_all(&iolat->rq_wait.wait);
  345. }
  346. } else {
  347. old >>= 1;
  348. iolat->rq_depth.max_depth = max(old, 1UL);
  349. }
  350. }
  351. /* Check our parent and see if the scale cookie has changed. */
  352. static void check_scale_change(struct iolatency_grp *iolat)
  353. {
  354. struct iolatency_grp *parent;
  355. struct child_latency_info *lat_info;
  356. unsigned int cur_cookie;
  357. unsigned int our_cookie = atomic_read(&iolat->scale_cookie);
  358. u64 scale_lat;
  359. int direction = 0;
  360. if (lat_to_blkg(iolat)->parent == NULL)
  361. return;
  362. parent = blkg_to_lat(lat_to_blkg(iolat)->parent);
  363. if (!parent)
  364. return;
  365. lat_info = &parent->child_lat;
  366. cur_cookie = atomic_read(&lat_info->scale_cookie);
  367. scale_lat = READ_ONCE(lat_info->scale_lat);
  368. if (cur_cookie < our_cookie)
  369. direction = -1;
  370. else if (cur_cookie > our_cookie)
  371. direction = 1;
  372. else
  373. return;
  374. if (!atomic_try_cmpxchg(&iolat->scale_cookie, &our_cookie, cur_cookie)) {
  375. /* Somebody beat us to the punch, just bail. */
  376. return;
  377. }
  378. if (direction < 0 && iolat->min_lat_nsec) {
  379. u64 samples_thresh;
  380. if (!scale_lat || iolat->min_lat_nsec <= scale_lat)
  381. return;
  382. /*
  383. * Sometimes high priority groups are their own worst enemy, so
  384. * instead of taking it out on some poor other group that did 5%
  385. * or less of the IO's for the last summation just skip this
  386. * scale down event.
  387. */
  388. samples_thresh = lat_info->nr_samples * 5;
  389. samples_thresh = max(1ULL, div64_u64(samples_thresh, 100));
  390. if (iolat->nr_samples <= samples_thresh)
  391. return;
  392. }
  393. /* We're as low as we can go. */
  394. if (iolat->rq_depth.max_depth == 1 && direction < 0) {
  395. blkcg_use_delay(lat_to_blkg(iolat));
  396. return;
  397. }
  398. /* We're back to the default cookie, unthrottle all the things. */
  399. if (cur_cookie == DEFAULT_SCALE_COOKIE) {
  400. blkcg_clear_delay(lat_to_blkg(iolat));
  401. iolat->rq_depth.max_depth = UINT_MAX;
  402. wake_up_all(&iolat->rq_wait.wait);
  403. return;
  404. }
  405. scale_change(iolat, direction > 0);
  406. }
  407. static void blkcg_iolatency_throttle(struct rq_qos *rqos, struct bio *bio)
  408. {
  409. struct blk_iolatency *blkiolat = BLKIOLATENCY(rqos);
  410. struct blkcg_gq *blkg = bio->bi_blkg;
  411. bool issue_as_root = bio_issue_as_root_blkg(bio);
  412. if (!blkiolat->enabled)
  413. return;
  414. while (blkg && blkg->parent) {
  415. struct iolatency_grp *iolat = blkg_to_lat(blkg);
  416. if (!iolat) {
  417. blkg = blkg->parent;
  418. continue;
  419. }
  420. check_scale_change(iolat);
  421. __blkcg_iolatency_throttle(rqos, iolat, issue_as_root,
  422. (bio->bi_opf & REQ_SWAP) == REQ_SWAP);
  423. blkg = blkg->parent;
  424. }
  425. if (!timer_pending(&blkiolat->timer))
  426. mod_timer(&blkiolat->timer, jiffies + HZ);
  427. }
  428. static void iolatency_record_time(struct iolatency_grp *iolat,
  429. struct bio_issue *issue, u64 now,
  430. bool issue_as_root)
  431. {
  432. u64 start = bio_issue_time(issue);
  433. u64 req_time;
  434. /*
  435. * Have to do this so we are truncated to the correct time that our
  436. * issue is truncated to.
  437. */
  438. now = __bio_issue_time(now);
  439. if (now <= start)
  440. return;
  441. req_time = now - start;
  442. /*
  443. * We don't want to count issue_as_root bio's in the cgroups latency
  444. * statistics as it could skew the numbers downwards.
  445. */
  446. if (unlikely(issue_as_root && iolat->rq_depth.max_depth != UINT_MAX)) {
  447. u64 sub = iolat->min_lat_nsec;
  448. if (req_time < sub)
  449. blkcg_add_delay(lat_to_blkg(iolat), now, sub - req_time);
  450. return;
  451. }
  452. latency_stat_record_time(iolat, req_time);
  453. }
  454. #define BLKIOLATENCY_MIN_ADJUST_TIME (500 * NSEC_PER_MSEC)
  455. #define BLKIOLATENCY_MIN_GOOD_SAMPLES 5
  456. static void iolatency_check_latencies(struct iolatency_grp *iolat, u64 now)
  457. {
  458. struct blkcg_gq *blkg = lat_to_blkg(iolat);
  459. struct iolatency_grp *parent;
  460. struct child_latency_info *lat_info;
  461. struct latency_stat stat;
  462. unsigned long flags;
  463. int cpu;
  464. latency_stat_init(iolat, &stat);
  465. preempt_disable();
  466. for_each_online_cpu(cpu) {
  467. struct latency_stat *s;
  468. s = per_cpu_ptr(iolat->stats, cpu);
  469. latency_stat_sum(iolat, &stat, s);
  470. latency_stat_init(iolat, s);
  471. }
  472. preempt_enable();
  473. parent = blkg_to_lat(blkg->parent);
  474. if (!parent)
  475. return;
  476. lat_info = &parent->child_lat;
  477. iolat_update_total_lat_avg(iolat, &stat);
  478. /* Everything is ok and we don't need to adjust the scale. */
  479. if (latency_sum_ok(iolat, &stat) &&
  480. atomic_read(&lat_info->scale_cookie) == DEFAULT_SCALE_COOKIE)
  481. return;
  482. /* Somebody beat us to the punch, just bail. */
  483. spin_lock_irqsave(&lat_info->lock, flags);
  484. latency_stat_sum(iolat, &iolat->cur_stat, &stat);
  485. lat_info->nr_samples -= iolat->nr_samples;
  486. lat_info->nr_samples += latency_stat_samples(iolat, &iolat->cur_stat);
  487. iolat->nr_samples = latency_stat_samples(iolat, &iolat->cur_stat);
  488. if ((lat_info->last_scale_event >= now ||
  489. now - lat_info->last_scale_event < BLKIOLATENCY_MIN_ADJUST_TIME))
  490. goto out;
  491. if (latency_sum_ok(iolat, &iolat->cur_stat) &&
  492. latency_sum_ok(iolat, &stat)) {
  493. if (latency_stat_samples(iolat, &iolat->cur_stat) <
  494. BLKIOLATENCY_MIN_GOOD_SAMPLES)
  495. goto out;
  496. if (lat_info->scale_grp == iolat) {
  497. lat_info->last_scale_event = now;
  498. scale_cookie_change(iolat->blkiolat, lat_info, true);
  499. }
  500. } else if (lat_info->scale_lat == 0 ||
  501. lat_info->scale_lat >= iolat->min_lat_nsec) {
  502. lat_info->last_scale_event = now;
  503. if (!lat_info->scale_grp ||
  504. lat_info->scale_lat > iolat->min_lat_nsec) {
  505. WRITE_ONCE(lat_info->scale_lat, iolat->min_lat_nsec);
  506. lat_info->scale_grp = iolat;
  507. }
  508. scale_cookie_change(iolat->blkiolat, lat_info, false);
  509. }
  510. latency_stat_init(iolat, &iolat->cur_stat);
  511. out:
  512. spin_unlock_irqrestore(&lat_info->lock, flags);
  513. }
  514. static void blkcg_iolatency_done_bio(struct rq_qos *rqos, struct bio *bio)
  515. {
  516. struct blkcg_gq *blkg;
  517. struct rq_wait *rqw;
  518. struct iolatency_grp *iolat;
  519. u64 window_start;
  520. u64 now;
  521. bool issue_as_root = bio_issue_as_root_blkg(bio);
  522. int inflight = 0;
  523. blkg = bio->bi_blkg;
  524. if (!blkg || !bio_flagged(bio, BIO_QOS_THROTTLED))
  525. return;
  526. iolat = blkg_to_lat(bio->bi_blkg);
  527. if (!iolat)
  528. return;
  529. if (!iolat->blkiolat->enabled)
  530. return;
  531. now = ktime_to_ns(ktime_get());
  532. while (blkg && blkg->parent) {
  533. iolat = blkg_to_lat(blkg);
  534. if (!iolat) {
  535. blkg = blkg->parent;
  536. continue;
  537. }
  538. rqw = &iolat->rq_wait;
  539. inflight = atomic_dec_return(&rqw->inflight);
  540. WARN_ON_ONCE(inflight < 0);
  541. /*
  542. * If bi_status is BLK_STS_AGAIN, the bio wasn't actually
  543. * submitted, so do not account for it.
  544. */
  545. if (iolat->min_lat_nsec && bio->bi_status != BLK_STS_AGAIN) {
  546. iolatency_record_time(iolat, &bio->bi_issue, now,
  547. issue_as_root);
  548. window_start = atomic64_read(&iolat->window_start);
  549. if (now > window_start &&
  550. (now - window_start) >= iolat->cur_win_nsec) {
  551. if (atomic64_try_cmpxchg(&iolat->window_start,
  552. &window_start, now))
  553. iolatency_check_latencies(iolat, now);
  554. }
  555. }
  556. wake_up(&rqw->wait);
  557. blkg = blkg->parent;
  558. }
  559. }
  560. static void blkcg_iolatency_exit(struct rq_qos *rqos)
  561. {
  562. struct blk_iolatency *blkiolat = BLKIOLATENCY(rqos);
  563. del_timer_sync(&blkiolat->timer);
  564. flush_work(&blkiolat->enable_work);
  565. blkcg_deactivate_policy(rqos->q, &blkcg_policy_iolatency);
  566. kfree(blkiolat);
  567. }
  568. static struct rq_qos_ops blkcg_iolatency_ops = {
  569. .throttle = blkcg_iolatency_throttle,
  570. .done_bio = blkcg_iolatency_done_bio,
  571. .exit = blkcg_iolatency_exit,
  572. };
  573. static void blkiolatency_timer_fn(struct timer_list *t)
  574. {
  575. struct blk_iolatency *blkiolat = from_timer(blkiolat, t, timer);
  576. struct blkcg_gq *blkg;
  577. struct cgroup_subsys_state *pos_css;
  578. u64 now = ktime_to_ns(ktime_get());
  579. rcu_read_lock();
  580. blkg_for_each_descendant_pre(blkg, pos_css,
  581. blkiolat->rqos.q->root_blkg) {
  582. struct iolatency_grp *iolat;
  583. struct child_latency_info *lat_info;
  584. unsigned long flags;
  585. u64 cookie;
  586. /*
  587. * We could be exiting, don't access the pd unless we have a
  588. * ref on the blkg.
  589. */
  590. if (!blkg_tryget(blkg))
  591. continue;
  592. iolat = blkg_to_lat(blkg);
  593. if (!iolat)
  594. goto next;
  595. lat_info = &iolat->child_lat;
  596. cookie = atomic_read(&lat_info->scale_cookie);
  597. if (cookie >= DEFAULT_SCALE_COOKIE)
  598. goto next;
  599. spin_lock_irqsave(&lat_info->lock, flags);
  600. if (lat_info->last_scale_event >= now)
  601. goto next_lock;
  602. /*
  603. * We scaled down but don't have a scale_grp, scale up and carry
  604. * on.
  605. */
  606. if (lat_info->scale_grp == NULL) {
  607. scale_cookie_change(iolat->blkiolat, lat_info, true);
  608. goto next_lock;
  609. }
  610. /*
  611. * It's been 5 seconds since our last scale event, clear the
  612. * scale grp in case the group that needed the scale down isn't
  613. * doing any IO currently.
  614. */
  615. if (now - lat_info->last_scale_event >=
  616. ((u64)NSEC_PER_SEC * 5))
  617. lat_info->scale_grp = NULL;
  618. next_lock:
  619. spin_unlock_irqrestore(&lat_info->lock, flags);
  620. next:
  621. blkg_put(blkg);
  622. }
  623. rcu_read_unlock();
  624. }
  625. /**
  626. * blkiolatency_enable_work_fn - Enable or disable iolatency on the device
  627. * @work: enable_work of the blk_iolatency of interest
  628. *
  629. * iolatency needs to keep track of the number of in-flight IOs per cgroup. This
  630. * is relatively expensive as it involves walking up the hierarchy twice for
  631. * every IO. Thus, if iolatency is not enabled in any cgroup for the device, we
  632. * want to disable the in-flight tracking.
  633. *
  634. * We have to make sure that the counting is balanced - we don't want to leak
  635. * the in-flight counts by disabling accounting in the completion path while IOs
  636. * are in flight. This is achieved by ensuring that no IO is in flight by
  637. * freezing the queue while flipping ->enabled. As this requires a sleepable
  638. * context, ->enabled flipping is punted to this work function.
  639. */
  640. static void blkiolatency_enable_work_fn(struct work_struct *work)
  641. {
  642. struct blk_iolatency *blkiolat = container_of(work, struct blk_iolatency,
  643. enable_work);
  644. bool enabled;
  645. /*
  646. * There can only be one instance of this function running for @blkiolat
  647. * and it's guaranteed to be executed at least once after the latest
  648. * ->enabled_cnt modification. Acting on the latest ->enable_cnt is
  649. * sufficient.
  650. *
  651. * Also, we know @blkiolat is safe to access as ->enable_work is flushed
  652. * in blkcg_iolatency_exit().
  653. */
  654. enabled = atomic_read(&blkiolat->enable_cnt);
  655. if (enabled != blkiolat->enabled) {
  656. blk_mq_freeze_queue(blkiolat->rqos.q);
  657. blkiolat->enabled = enabled;
  658. blk_mq_unfreeze_queue(blkiolat->rqos.q);
  659. }
  660. }
  661. int blk_iolatency_init(struct gendisk *disk)
  662. {
  663. struct request_queue *q = disk->queue;
  664. struct blk_iolatency *blkiolat;
  665. struct rq_qos *rqos;
  666. int ret;
  667. blkiolat = kzalloc(sizeof(*blkiolat), GFP_KERNEL);
  668. if (!blkiolat)
  669. return -ENOMEM;
  670. rqos = &blkiolat->rqos;
  671. rqos->id = RQ_QOS_LATENCY;
  672. rqos->ops = &blkcg_iolatency_ops;
  673. rqos->q = q;
  674. ret = rq_qos_add(q, rqos);
  675. if (ret)
  676. goto err_free;
  677. ret = blkcg_activate_policy(q, &blkcg_policy_iolatency);
  678. if (ret)
  679. goto err_qos_del;
  680. timer_setup(&blkiolat->timer, blkiolatency_timer_fn, 0);
  681. INIT_WORK(&blkiolat->enable_work, blkiolatency_enable_work_fn);
  682. return 0;
  683. err_qos_del:
  684. rq_qos_del(q, rqos);
  685. err_free:
  686. kfree(blkiolat);
  687. return ret;
  688. }
  689. static void iolatency_set_min_lat_nsec(struct blkcg_gq *blkg, u64 val)
  690. {
  691. struct iolatency_grp *iolat = blkg_to_lat(blkg);
  692. struct blk_iolatency *blkiolat = iolat->blkiolat;
  693. u64 oldval = iolat->min_lat_nsec;
  694. iolat->min_lat_nsec = val;
  695. iolat->cur_win_nsec = max_t(u64, val << 4, BLKIOLATENCY_MIN_WIN_SIZE);
  696. iolat->cur_win_nsec = min_t(u64, iolat->cur_win_nsec,
  697. BLKIOLATENCY_MAX_WIN_SIZE);
  698. if (!oldval && val) {
  699. if (atomic_inc_return(&blkiolat->enable_cnt) == 1)
  700. schedule_work(&blkiolat->enable_work);
  701. }
  702. if (oldval && !val) {
  703. blkcg_clear_delay(blkg);
  704. if (atomic_dec_return(&blkiolat->enable_cnt) == 0)
  705. schedule_work(&blkiolat->enable_work);
  706. }
  707. }
  708. static void iolatency_clear_scaling(struct blkcg_gq *blkg)
  709. {
  710. if (blkg->parent) {
  711. struct iolatency_grp *iolat = blkg_to_lat(blkg->parent);
  712. struct child_latency_info *lat_info;
  713. if (!iolat)
  714. return;
  715. lat_info = &iolat->child_lat;
  716. spin_lock(&lat_info->lock);
  717. atomic_set(&lat_info->scale_cookie, DEFAULT_SCALE_COOKIE);
  718. lat_info->last_scale_event = 0;
  719. lat_info->scale_grp = NULL;
  720. lat_info->scale_lat = 0;
  721. spin_unlock(&lat_info->lock);
  722. }
  723. }
  724. static ssize_t iolatency_set_limit(struct kernfs_open_file *of, char *buf,
  725. size_t nbytes, loff_t off)
  726. {
  727. struct blkcg *blkcg = css_to_blkcg(of_css(of));
  728. struct blkcg_gq *blkg;
  729. struct blkg_conf_ctx ctx;
  730. struct iolatency_grp *iolat;
  731. char *p, *tok;
  732. u64 lat_val = 0;
  733. u64 oldval;
  734. int ret;
  735. ret = blkg_conf_prep(blkcg, &blkcg_policy_iolatency, buf, &ctx);
  736. if (ret)
  737. return ret;
  738. iolat = blkg_to_lat(ctx.blkg);
  739. p = ctx.body;
  740. ret = -EINVAL;
  741. while ((tok = strsep(&p, " "))) {
  742. char key[16];
  743. char val[21]; /* 18446744073709551616 */
  744. if (sscanf(tok, "%15[^=]=%20s", key, val) != 2)
  745. goto out;
  746. if (!strcmp(key, "target")) {
  747. u64 v;
  748. if (!strcmp(val, "max"))
  749. lat_val = 0;
  750. else if (sscanf(val, "%llu", &v) == 1)
  751. lat_val = v * NSEC_PER_USEC;
  752. else
  753. goto out;
  754. } else {
  755. goto out;
  756. }
  757. }
  758. /* Walk up the tree to see if our new val is lower than it should be. */
  759. blkg = ctx.blkg;
  760. oldval = iolat->min_lat_nsec;
  761. iolatency_set_min_lat_nsec(blkg, lat_val);
  762. if (oldval != iolat->min_lat_nsec)
  763. iolatency_clear_scaling(blkg);
  764. ret = 0;
  765. out:
  766. blkg_conf_finish(&ctx);
  767. return ret ?: nbytes;
  768. }
  769. static u64 iolatency_prfill_limit(struct seq_file *sf,
  770. struct blkg_policy_data *pd, int off)
  771. {
  772. struct iolatency_grp *iolat = pd_to_lat(pd);
  773. const char *dname = blkg_dev_name(pd->blkg);
  774. if (!dname || !iolat->min_lat_nsec)
  775. return 0;
  776. seq_printf(sf, "%s target=%llu\n",
  777. dname, div_u64(iolat->min_lat_nsec, NSEC_PER_USEC));
  778. return 0;
  779. }
  780. static int iolatency_print_limit(struct seq_file *sf, void *v)
  781. {
  782. blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
  783. iolatency_prfill_limit,
  784. &blkcg_policy_iolatency, seq_cft(sf)->private, false);
  785. return 0;
  786. }
  787. static void iolatency_ssd_stat(struct iolatency_grp *iolat, struct seq_file *s)
  788. {
  789. struct latency_stat stat;
  790. int cpu;
  791. latency_stat_init(iolat, &stat);
  792. preempt_disable();
  793. for_each_online_cpu(cpu) {
  794. struct latency_stat *s;
  795. s = per_cpu_ptr(iolat->stats, cpu);
  796. latency_stat_sum(iolat, &stat, s);
  797. }
  798. preempt_enable();
  799. if (iolat->rq_depth.max_depth == UINT_MAX)
  800. seq_printf(s, " missed=%llu total=%llu depth=max",
  801. (unsigned long long)stat.ps.missed,
  802. (unsigned long long)stat.ps.total);
  803. else
  804. seq_printf(s, " missed=%llu total=%llu depth=%u",
  805. (unsigned long long)stat.ps.missed,
  806. (unsigned long long)stat.ps.total,
  807. iolat->rq_depth.max_depth);
  808. }
  809. static void iolatency_pd_stat(struct blkg_policy_data *pd, struct seq_file *s)
  810. {
  811. struct iolatency_grp *iolat = pd_to_lat(pd);
  812. unsigned long long avg_lat;
  813. unsigned long long cur_win;
  814. if (!blkcg_debug_stats)
  815. return;
  816. if (iolat->ssd)
  817. return iolatency_ssd_stat(iolat, s);
  818. avg_lat = div64_u64(iolat->lat_avg, NSEC_PER_USEC);
  819. cur_win = div64_u64(iolat->cur_win_nsec, NSEC_PER_MSEC);
  820. if (iolat->rq_depth.max_depth == UINT_MAX)
  821. seq_printf(s, " depth=max avg_lat=%llu win=%llu",
  822. avg_lat, cur_win);
  823. else
  824. seq_printf(s, " depth=%u avg_lat=%llu win=%llu",
  825. iolat->rq_depth.max_depth, avg_lat, cur_win);
  826. }
  827. static struct blkg_policy_data *iolatency_pd_alloc(gfp_t gfp,
  828. struct request_queue *q,
  829. struct blkcg *blkcg)
  830. {
  831. struct iolatency_grp *iolat;
  832. iolat = kzalloc_node(sizeof(*iolat), gfp, q->node);
  833. if (!iolat)
  834. return NULL;
  835. iolat->stats = __alloc_percpu_gfp(sizeof(struct latency_stat),
  836. __alignof__(struct latency_stat), gfp);
  837. if (!iolat->stats) {
  838. kfree(iolat);
  839. return NULL;
  840. }
  841. return &iolat->pd;
  842. }
  843. static void iolatency_pd_init(struct blkg_policy_data *pd)
  844. {
  845. struct iolatency_grp *iolat = pd_to_lat(pd);
  846. struct blkcg_gq *blkg = lat_to_blkg(iolat);
  847. struct rq_qos *rqos = blkcg_rq_qos(blkg->q);
  848. struct blk_iolatency *blkiolat = BLKIOLATENCY(rqos);
  849. u64 now = ktime_to_ns(ktime_get());
  850. int cpu;
  851. if (blk_queue_nonrot(blkg->q))
  852. iolat->ssd = true;
  853. else
  854. iolat->ssd = false;
  855. for_each_possible_cpu(cpu) {
  856. struct latency_stat *stat;
  857. stat = per_cpu_ptr(iolat->stats, cpu);
  858. latency_stat_init(iolat, stat);
  859. }
  860. latency_stat_init(iolat, &iolat->cur_stat);
  861. rq_wait_init(&iolat->rq_wait);
  862. spin_lock_init(&iolat->child_lat.lock);
  863. iolat->rq_depth.queue_depth = blkg->q->nr_requests;
  864. iolat->rq_depth.max_depth = UINT_MAX;
  865. iolat->rq_depth.default_depth = iolat->rq_depth.queue_depth;
  866. iolat->blkiolat = blkiolat;
  867. iolat->cur_win_nsec = 100 * NSEC_PER_MSEC;
  868. atomic64_set(&iolat->window_start, now);
  869. /*
  870. * We init things in list order, so the pd for the parent may not be
  871. * init'ed yet for whatever reason.
  872. */
  873. if (blkg->parent && blkg_to_pd(blkg->parent, &blkcg_policy_iolatency)) {
  874. struct iolatency_grp *parent = blkg_to_lat(blkg->parent);
  875. atomic_set(&iolat->scale_cookie,
  876. atomic_read(&parent->child_lat.scale_cookie));
  877. } else {
  878. atomic_set(&iolat->scale_cookie, DEFAULT_SCALE_COOKIE);
  879. }
  880. atomic_set(&iolat->child_lat.scale_cookie, DEFAULT_SCALE_COOKIE);
  881. }
  882. static void iolatency_pd_offline(struct blkg_policy_data *pd)
  883. {
  884. struct iolatency_grp *iolat = pd_to_lat(pd);
  885. struct blkcg_gq *blkg = lat_to_blkg(iolat);
  886. iolatency_set_min_lat_nsec(blkg, 0);
  887. iolatency_clear_scaling(blkg);
  888. }
  889. static void iolatency_pd_free(struct blkg_policy_data *pd)
  890. {
  891. struct iolatency_grp *iolat = pd_to_lat(pd);
  892. free_percpu(iolat->stats);
  893. kfree(iolat);
  894. }
  895. static struct cftype iolatency_files[] = {
  896. {
  897. .name = "latency",
  898. .flags = CFTYPE_NOT_ON_ROOT,
  899. .seq_show = iolatency_print_limit,
  900. .write = iolatency_set_limit,
  901. },
  902. {}
  903. };
  904. static struct blkcg_policy blkcg_policy_iolatency = {
  905. .dfl_cftypes = iolatency_files,
  906. .pd_alloc_fn = iolatency_pd_alloc,
  907. .pd_init_fn = iolatency_pd_init,
  908. .pd_offline_fn = iolatency_pd_offline,
  909. .pd_free_fn = iolatency_pd_free,
  910. .pd_stat_fn = iolatency_pd_stat,
  911. };
  912. static int __init iolatency_init(void)
  913. {
  914. return blkcg_policy_register(&blkcg_policy_iolatency);
  915. }
  916. static void __exit iolatency_exit(void)
  917. {
  918. blkcg_policy_unregister(&blkcg_policy_iolatency);
  919. }
  920. module_init(iolatency_init);
  921. module_exit(iolatency_exit);