blk-iolatency.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  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. unsigned int max_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->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->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.disk->queue->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 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. We halve the queue depth
  329. * at a time so we can scale down queue depth quickly from default unlimited
  330. * to target.
  331. */
  332. static void scale_change(struct iolatency_grp *iolat, bool up)
  333. {
  334. unsigned long qd = iolat->blkiolat->rqos.disk->queue->nr_requests;
  335. unsigned long scale = scale_amount(qd, up);
  336. unsigned long old = iolat->max_depth;
  337. if (old > qd)
  338. old = qd;
  339. if (up) {
  340. if (old == 1 && blkcg_unuse_delay(lat_to_blkg(iolat)))
  341. return;
  342. if (old < qd) {
  343. old += scale;
  344. old = min(old, qd);
  345. iolat->max_depth = old;
  346. wake_up_all(&iolat->rq_wait.wait);
  347. }
  348. } else {
  349. old >>= 1;
  350. iolat->max_depth = max(old, 1UL);
  351. }
  352. }
  353. /* Check our parent and see if the scale cookie has changed. */
  354. static void check_scale_change(struct iolatency_grp *iolat)
  355. {
  356. struct iolatency_grp *parent;
  357. struct child_latency_info *lat_info;
  358. unsigned int cur_cookie;
  359. unsigned int our_cookie = atomic_read(&iolat->scale_cookie);
  360. u64 scale_lat;
  361. int direction = 0;
  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->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->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, u64 start,
  429. u64 now, bool issue_as_root)
  430. {
  431. u64 req_time;
  432. if (now <= start)
  433. return;
  434. req_time = now - start;
  435. /*
  436. * We don't want to count issue_as_root bio's in the cgroups latency
  437. * statistics as it could skew the numbers downwards.
  438. */
  439. if (unlikely(issue_as_root && iolat->max_depth != UINT_MAX)) {
  440. u64 sub = iolat->min_lat_nsec;
  441. if (req_time < sub)
  442. blkcg_add_delay(lat_to_blkg(iolat), now, sub - req_time);
  443. return;
  444. }
  445. latency_stat_record_time(iolat, req_time);
  446. }
  447. #define BLKIOLATENCY_MIN_ADJUST_TIME (500 * NSEC_PER_MSEC)
  448. #define BLKIOLATENCY_MIN_GOOD_SAMPLES 5
  449. static void iolatency_check_latencies(struct iolatency_grp *iolat, u64 now)
  450. {
  451. struct blkcg_gq *blkg = lat_to_blkg(iolat);
  452. struct iolatency_grp *parent;
  453. struct child_latency_info *lat_info;
  454. struct latency_stat stat;
  455. unsigned long flags;
  456. int cpu;
  457. latency_stat_init(iolat, &stat);
  458. preempt_disable();
  459. for_each_online_cpu(cpu) {
  460. struct latency_stat *s;
  461. s = per_cpu_ptr(iolat->stats, cpu);
  462. latency_stat_sum(iolat, &stat, s);
  463. latency_stat_init(iolat, s);
  464. }
  465. preempt_enable();
  466. parent = blkg_to_lat(blkg->parent);
  467. if (!parent)
  468. return;
  469. lat_info = &parent->child_lat;
  470. iolat_update_total_lat_avg(iolat, &stat);
  471. /* Everything is ok and we don't need to adjust the scale. */
  472. if (latency_sum_ok(iolat, &stat) &&
  473. atomic_read(&lat_info->scale_cookie) == DEFAULT_SCALE_COOKIE)
  474. return;
  475. /* Somebody beat us to the punch, just bail. */
  476. spin_lock_irqsave(&lat_info->lock, flags);
  477. latency_stat_sum(iolat, &iolat->cur_stat, &stat);
  478. lat_info->nr_samples -= iolat->nr_samples;
  479. lat_info->nr_samples += latency_stat_samples(iolat, &iolat->cur_stat);
  480. iolat->nr_samples = latency_stat_samples(iolat, &iolat->cur_stat);
  481. if ((lat_info->last_scale_event >= now ||
  482. now - lat_info->last_scale_event < BLKIOLATENCY_MIN_ADJUST_TIME))
  483. goto out;
  484. if (latency_sum_ok(iolat, &iolat->cur_stat) &&
  485. latency_sum_ok(iolat, &stat)) {
  486. if (latency_stat_samples(iolat, &iolat->cur_stat) <
  487. BLKIOLATENCY_MIN_GOOD_SAMPLES)
  488. goto out;
  489. if (lat_info->scale_grp == iolat) {
  490. lat_info->last_scale_event = now;
  491. scale_cookie_change(iolat->blkiolat, lat_info, true);
  492. }
  493. } else if (lat_info->scale_lat == 0 ||
  494. lat_info->scale_lat >= iolat->min_lat_nsec) {
  495. lat_info->last_scale_event = now;
  496. if (!lat_info->scale_grp ||
  497. lat_info->scale_lat > iolat->min_lat_nsec) {
  498. WRITE_ONCE(lat_info->scale_lat, iolat->min_lat_nsec);
  499. lat_info->scale_grp = iolat;
  500. }
  501. scale_cookie_change(iolat->blkiolat, lat_info, false);
  502. }
  503. latency_stat_init(iolat, &iolat->cur_stat);
  504. out:
  505. spin_unlock_irqrestore(&lat_info->lock, flags);
  506. }
  507. static void blkcg_iolatency_done_bio(struct rq_qos *rqos, struct bio *bio)
  508. {
  509. struct blkcg_gq *blkg;
  510. struct rq_wait *rqw;
  511. struct iolatency_grp *iolat;
  512. u64 window_start;
  513. u64 now;
  514. bool issue_as_root = bio_issue_as_root_blkg(bio);
  515. int inflight = 0;
  516. blkg = bio->bi_blkg;
  517. if (!blkg || !bio_flagged(bio, BIO_QOS_THROTTLED))
  518. return;
  519. iolat = blkg_to_lat(bio->bi_blkg);
  520. if (!iolat)
  521. return;
  522. if (!iolat->blkiolat->enabled)
  523. return;
  524. now = blk_time_get_ns();
  525. while (blkg && blkg->parent) {
  526. iolat = blkg_to_lat(blkg);
  527. if (!iolat) {
  528. blkg = blkg->parent;
  529. continue;
  530. }
  531. rqw = &iolat->rq_wait;
  532. inflight = atomic_dec_return(&rqw->inflight);
  533. WARN_ON_ONCE(inflight < 0);
  534. /*
  535. * If bi_status is BLK_STS_AGAIN, the bio wasn't actually
  536. * submitted, so do not account for it.
  537. */
  538. if (iolat->min_lat_nsec && bio->bi_status != BLK_STS_AGAIN) {
  539. iolatency_record_time(iolat, bio->issue_time_ns, now,
  540. issue_as_root);
  541. window_start = atomic64_read(&iolat->window_start);
  542. if (now > window_start &&
  543. (now - window_start) >= iolat->cur_win_nsec) {
  544. if (atomic64_try_cmpxchg(&iolat->window_start,
  545. &window_start, now))
  546. iolatency_check_latencies(iolat, now);
  547. }
  548. }
  549. wake_up(&rqw->wait);
  550. blkg = blkg->parent;
  551. }
  552. }
  553. static void blkcg_iolatency_exit(struct rq_qos *rqos)
  554. {
  555. struct blk_iolatency *blkiolat = BLKIOLATENCY(rqos);
  556. timer_shutdown_sync(&blkiolat->timer);
  557. flush_work(&blkiolat->enable_work);
  558. blkcg_deactivate_policy(rqos->disk, &blkcg_policy_iolatency);
  559. kfree(blkiolat);
  560. }
  561. static const struct rq_qos_ops blkcg_iolatency_ops = {
  562. .throttle = blkcg_iolatency_throttle,
  563. .done_bio = blkcg_iolatency_done_bio,
  564. .exit = blkcg_iolatency_exit,
  565. };
  566. static void blkiolatency_timer_fn(struct timer_list *t)
  567. {
  568. struct blk_iolatency *blkiolat = timer_container_of(blkiolat, t,
  569. timer);
  570. struct blkcg_gq *blkg;
  571. struct cgroup_subsys_state *pos_css;
  572. u64 now = blk_time_get_ns();
  573. rcu_read_lock();
  574. blkg_for_each_descendant_pre(blkg, pos_css,
  575. blkiolat->rqos.disk->queue->root_blkg) {
  576. struct iolatency_grp *iolat;
  577. struct child_latency_info *lat_info;
  578. unsigned long flags;
  579. u64 cookie;
  580. /*
  581. * We could be exiting, don't access the pd unless we have a
  582. * ref on the blkg.
  583. */
  584. if (!blkg_tryget(blkg))
  585. continue;
  586. iolat = blkg_to_lat(blkg);
  587. if (!iolat)
  588. goto next;
  589. lat_info = &iolat->child_lat;
  590. cookie = atomic_read(&lat_info->scale_cookie);
  591. if (cookie >= DEFAULT_SCALE_COOKIE)
  592. goto next;
  593. spin_lock_irqsave(&lat_info->lock, flags);
  594. if (lat_info->last_scale_event >= now)
  595. goto next_lock;
  596. /*
  597. * We scaled down but don't have a scale_grp, scale up and carry
  598. * on.
  599. */
  600. if (lat_info->scale_grp == NULL) {
  601. scale_cookie_change(iolat->blkiolat, lat_info, true);
  602. goto next_lock;
  603. }
  604. /*
  605. * It's been 5 seconds since our last scale event, clear the
  606. * scale grp in case the group that needed the scale down isn't
  607. * doing any IO currently.
  608. */
  609. if (now - lat_info->last_scale_event >=
  610. ((u64)NSEC_PER_SEC * 5))
  611. lat_info->scale_grp = NULL;
  612. next_lock:
  613. spin_unlock_irqrestore(&lat_info->lock, flags);
  614. next:
  615. blkg_put(blkg);
  616. }
  617. rcu_read_unlock();
  618. }
  619. /**
  620. * blkiolatency_enable_work_fn - Enable or disable iolatency on the device
  621. * @work: enable_work of the blk_iolatency of interest
  622. *
  623. * iolatency needs to keep track of the number of in-flight IOs per cgroup. This
  624. * is relatively expensive as it involves walking up the hierarchy twice for
  625. * every IO. Thus, if iolatency is not enabled in any cgroup for the device, we
  626. * want to disable the in-flight tracking.
  627. *
  628. * We have to make sure that the counting is balanced - we don't want to leak
  629. * the in-flight counts by disabling accounting in the completion path while IOs
  630. * are in flight. This is achieved by ensuring that no IO is in flight by
  631. * freezing the queue while flipping ->enabled. As this requires a sleepable
  632. * context, ->enabled flipping is punted to this work function.
  633. */
  634. static void blkiolatency_enable_work_fn(struct work_struct *work)
  635. {
  636. struct blk_iolatency *blkiolat = container_of(work, struct blk_iolatency,
  637. enable_work);
  638. bool enabled;
  639. /*
  640. * There can only be one instance of this function running for @blkiolat
  641. * and it's guaranteed to be executed at least once after the latest
  642. * ->enabled_cnt modification. Acting on the latest ->enable_cnt is
  643. * sufficient.
  644. *
  645. * Also, we know @blkiolat is safe to access as ->enable_work is flushed
  646. * in blkcg_iolatency_exit().
  647. */
  648. enabled = atomic_read(&blkiolat->enable_cnt);
  649. if (enabled != blkiolat->enabled) {
  650. struct request_queue *q = blkiolat->rqos.disk->queue;
  651. unsigned int memflags;
  652. memflags = blk_mq_freeze_queue(blkiolat->rqos.disk->queue);
  653. blkiolat->enabled = enabled;
  654. if (enabled)
  655. blk_queue_flag_set(QUEUE_FLAG_BIO_ISSUE_TIME, q);
  656. else
  657. blk_queue_flag_clear(QUEUE_FLAG_BIO_ISSUE_TIME, q);
  658. blk_mq_unfreeze_queue(blkiolat->rqos.disk->queue, memflags);
  659. }
  660. }
  661. static int blk_iolatency_init(struct gendisk *disk)
  662. {
  663. struct blk_iolatency *blkiolat;
  664. int ret;
  665. blkiolat = kzalloc_obj(*blkiolat);
  666. if (!blkiolat)
  667. return -ENOMEM;
  668. ret = rq_qos_add(&blkiolat->rqos, disk, RQ_QOS_LATENCY,
  669. &blkcg_iolatency_ops);
  670. if (ret)
  671. goto err_free;
  672. ret = blkcg_activate_policy(disk, &blkcg_policy_iolatency);
  673. if (ret)
  674. goto err_qos_del;
  675. timer_setup(&blkiolat->timer, blkiolatency_timer_fn, 0);
  676. INIT_WORK(&blkiolat->enable_work, blkiolatency_enable_work_fn);
  677. return 0;
  678. err_qos_del:
  679. rq_qos_del(&blkiolat->rqos);
  680. err_free:
  681. kfree(blkiolat);
  682. return ret;
  683. }
  684. static void iolatency_set_min_lat_nsec(struct blkcg_gq *blkg, u64 val)
  685. {
  686. struct iolatency_grp *iolat = blkg_to_lat(blkg);
  687. struct blk_iolatency *blkiolat = iolat->blkiolat;
  688. u64 oldval = iolat->min_lat_nsec;
  689. iolat->min_lat_nsec = val;
  690. iolat->cur_win_nsec = max_t(u64, val << 4, BLKIOLATENCY_MIN_WIN_SIZE);
  691. iolat->cur_win_nsec = min_t(u64, iolat->cur_win_nsec,
  692. BLKIOLATENCY_MAX_WIN_SIZE);
  693. if (!oldval && val) {
  694. if (atomic_inc_return(&blkiolat->enable_cnt) == 1)
  695. schedule_work(&blkiolat->enable_work);
  696. }
  697. if (oldval && !val) {
  698. blkcg_clear_delay(blkg);
  699. if (atomic_dec_return(&blkiolat->enable_cnt) == 0)
  700. schedule_work(&blkiolat->enable_work);
  701. }
  702. }
  703. static void iolatency_clear_scaling(struct blkcg_gq *blkg)
  704. {
  705. if (blkg->parent) {
  706. struct iolatency_grp *iolat = blkg_to_lat(blkg->parent);
  707. struct child_latency_info *lat_info;
  708. if (!iolat)
  709. return;
  710. lat_info = &iolat->child_lat;
  711. spin_lock(&lat_info->lock);
  712. atomic_set(&lat_info->scale_cookie, DEFAULT_SCALE_COOKIE);
  713. lat_info->last_scale_event = 0;
  714. lat_info->scale_grp = NULL;
  715. lat_info->scale_lat = 0;
  716. spin_unlock(&lat_info->lock);
  717. }
  718. }
  719. static ssize_t iolatency_set_limit(struct kernfs_open_file *of, char *buf,
  720. size_t nbytes, loff_t off)
  721. {
  722. struct blkcg *blkcg = css_to_blkcg(of_css(of));
  723. struct blkcg_gq *blkg;
  724. struct blkg_conf_ctx ctx;
  725. struct iolatency_grp *iolat;
  726. char *p, *tok;
  727. u64 lat_val = 0;
  728. u64 oldval;
  729. int ret;
  730. blkg_conf_init(&ctx, buf);
  731. ret = blkg_conf_open_bdev(&ctx);
  732. if (ret)
  733. goto out;
  734. /*
  735. * blk_iolatency_init() may fail after rq_qos_add() succeeds which can
  736. * confuse iolat_rq_qos() test. Make the test and init atomic.
  737. */
  738. lockdep_assert_held(&ctx.bdev->bd_queue->rq_qos_mutex);
  739. if (!iolat_rq_qos(ctx.bdev->bd_queue))
  740. ret = blk_iolatency_init(ctx.bdev->bd_disk);
  741. if (ret)
  742. goto out;
  743. ret = blkg_conf_prep(blkcg, &blkcg_policy_iolatency, &ctx);
  744. if (ret)
  745. goto out;
  746. iolat = blkg_to_lat(ctx.blkg);
  747. p = ctx.body;
  748. ret = -EINVAL;
  749. while ((tok = strsep(&p, " "))) {
  750. char key[16];
  751. char val[21]; /* 18446744073709551616 */
  752. if (sscanf(tok, "%15[^=]=%20s", key, val) != 2)
  753. goto out;
  754. if (!strcmp(key, "target")) {
  755. u64 v;
  756. if (!strcmp(val, "max"))
  757. lat_val = 0;
  758. else if (sscanf(val, "%llu", &v) == 1)
  759. lat_val = v * NSEC_PER_USEC;
  760. else
  761. goto out;
  762. } else {
  763. goto out;
  764. }
  765. }
  766. /* Walk up the tree to see if our new val is lower than it should be. */
  767. blkg = ctx.blkg;
  768. oldval = iolat->min_lat_nsec;
  769. iolatency_set_min_lat_nsec(blkg, lat_val);
  770. if (oldval != iolat->min_lat_nsec)
  771. iolatency_clear_scaling(blkg);
  772. ret = 0;
  773. out:
  774. blkg_conf_exit(&ctx);
  775. return ret ?: nbytes;
  776. }
  777. static u64 iolatency_prfill_limit(struct seq_file *sf,
  778. struct blkg_policy_data *pd, int off)
  779. {
  780. struct iolatency_grp *iolat = pd_to_lat(pd);
  781. const char *dname = blkg_dev_name(pd->blkg);
  782. if (!dname || !iolat->min_lat_nsec)
  783. return 0;
  784. seq_printf(sf, "%s target=%llu\n",
  785. dname, div_u64(iolat->min_lat_nsec, NSEC_PER_USEC));
  786. return 0;
  787. }
  788. static int iolatency_print_limit(struct seq_file *sf, void *v)
  789. {
  790. blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
  791. iolatency_prfill_limit,
  792. &blkcg_policy_iolatency, seq_cft(sf)->private, false);
  793. return 0;
  794. }
  795. static void iolatency_ssd_stat(struct iolatency_grp *iolat, struct seq_file *s)
  796. {
  797. struct latency_stat stat;
  798. int cpu;
  799. latency_stat_init(iolat, &stat);
  800. preempt_disable();
  801. for_each_online_cpu(cpu) {
  802. struct latency_stat *s;
  803. s = per_cpu_ptr(iolat->stats, cpu);
  804. latency_stat_sum(iolat, &stat, s);
  805. }
  806. preempt_enable();
  807. if (iolat->max_depth == UINT_MAX)
  808. seq_printf(s, " missed=%llu total=%llu depth=max",
  809. (unsigned long long)stat.ps.missed,
  810. (unsigned long long)stat.ps.total);
  811. else
  812. seq_printf(s, " missed=%llu total=%llu depth=%u",
  813. (unsigned long long)stat.ps.missed,
  814. (unsigned long long)stat.ps.total,
  815. iolat->max_depth);
  816. }
  817. static void iolatency_pd_stat(struct blkg_policy_data *pd, struct seq_file *s)
  818. {
  819. struct iolatency_grp *iolat = pd_to_lat(pd);
  820. unsigned long long avg_lat;
  821. unsigned long long cur_win;
  822. if (!blkcg_debug_stats)
  823. return;
  824. if (iolat->ssd)
  825. return iolatency_ssd_stat(iolat, s);
  826. avg_lat = div64_u64(iolat->lat_avg, NSEC_PER_USEC);
  827. cur_win = div64_u64(iolat->cur_win_nsec, NSEC_PER_MSEC);
  828. if (iolat->max_depth == UINT_MAX)
  829. seq_printf(s, " depth=max avg_lat=%llu win=%llu",
  830. avg_lat, cur_win);
  831. else
  832. seq_printf(s, " depth=%u avg_lat=%llu win=%llu",
  833. iolat->max_depth, avg_lat, cur_win);
  834. }
  835. static struct blkg_policy_data *iolatency_pd_alloc(struct gendisk *disk,
  836. struct blkcg *blkcg, gfp_t gfp)
  837. {
  838. struct iolatency_grp *iolat;
  839. iolat = kzalloc_node(sizeof(*iolat), gfp, disk->node_id);
  840. if (!iolat)
  841. return NULL;
  842. iolat->stats = __alloc_percpu_gfp(sizeof(struct latency_stat),
  843. __alignof__(struct latency_stat), gfp);
  844. if (!iolat->stats) {
  845. kfree(iolat);
  846. return NULL;
  847. }
  848. return &iolat->pd;
  849. }
  850. static void iolatency_pd_init(struct blkg_policy_data *pd)
  851. {
  852. struct iolatency_grp *iolat = pd_to_lat(pd);
  853. struct blkcg_gq *blkg = lat_to_blkg(iolat);
  854. struct rq_qos *rqos = iolat_rq_qos(blkg->q);
  855. struct blk_iolatency *blkiolat = BLKIOLATENCY(rqos);
  856. u64 now = blk_time_get_ns();
  857. int cpu;
  858. iolat->ssd = !blk_queue_rot(blkg->q);
  859. for_each_possible_cpu(cpu) {
  860. struct latency_stat *stat;
  861. stat = per_cpu_ptr(iolat->stats, cpu);
  862. latency_stat_init(iolat, stat);
  863. }
  864. latency_stat_init(iolat, &iolat->cur_stat);
  865. rq_wait_init(&iolat->rq_wait);
  866. spin_lock_init(&iolat->child_lat.lock);
  867. iolat->max_depth = UINT_MAX;
  868. iolat->blkiolat = blkiolat;
  869. iolat->cur_win_nsec = 100 * NSEC_PER_MSEC;
  870. atomic64_set(&iolat->window_start, now);
  871. /*
  872. * We init things in list order, so the pd for the parent may not be
  873. * init'ed yet for whatever reason.
  874. */
  875. if (blkg->parent && blkg_to_pd(blkg->parent, &blkcg_policy_iolatency)) {
  876. struct iolatency_grp *parent = blkg_to_lat(blkg->parent);
  877. atomic_set(&iolat->scale_cookie,
  878. atomic_read(&parent->child_lat.scale_cookie));
  879. } else {
  880. atomic_set(&iolat->scale_cookie, DEFAULT_SCALE_COOKIE);
  881. }
  882. atomic_set(&iolat->child_lat.scale_cookie, DEFAULT_SCALE_COOKIE);
  883. }
  884. static void iolatency_pd_offline(struct blkg_policy_data *pd)
  885. {
  886. struct iolatency_grp *iolat = pd_to_lat(pd);
  887. struct blkcg_gq *blkg = lat_to_blkg(iolat);
  888. iolatency_set_min_lat_nsec(blkg, 0);
  889. iolatency_clear_scaling(blkg);
  890. }
  891. static void iolatency_pd_free(struct blkg_policy_data *pd)
  892. {
  893. struct iolatency_grp *iolat = pd_to_lat(pd);
  894. free_percpu(iolat->stats);
  895. kfree(iolat);
  896. }
  897. static struct cftype iolatency_files[] = {
  898. {
  899. .name = "latency",
  900. .flags = CFTYPE_NOT_ON_ROOT,
  901. .seq_show = iolatency_print_limit,
  902. .write = iolatency_set_limit,
  903. },
  904. {}
  905. };
  906. static struct blkcg_policy blkcg_policy_iolatency = {
  907. .dfl_cftypes = iolatency_files,
  908. .pd_alloc_fn = iolatency_pd_alloc,
  909. .pd_init_fn = iolatency_pd_init,
  910. .pd_offline_fn = iolatency_pd_offline,
  911. .pd_free_fn = iolatency_pd_free,
  912. .pd_stat_fn = iolatency_pd_stat,
  913. };
  914. static int __init iolatency_init(void)
  915. {
  916. return blkcg_policy_register(&blkcg_policy_iolatency);
  917. }
  918. static void __exit iolatency_exit(void)
  919. {
  920. blkcg_policy_unregister(&blkcg_policy_iolatency);
  921. }
  922. module_init(iolatency_init);
  923. module_exit(iolatency_exit);