blob: d2b69d87f3e78ff8d588d64184332e1342ff4130 [file] [log] [blame]
Tejun Heo7caa4712019-08-28 15:05:58 -07001/* SPDX-License-Identifier: GPL-2.0
2 *
3 * IO cost model based controller.
4 *
5 * Copyright (C) 2019 Tejun Heo <tj@kernel.org>
6 * Copyright (C) 2019 Andy Newell <newella@fb.com>
7 * Copyright (C) 2019 Facebook
8 *
9 * One challenge of controlling IO resources is the lack of trivially
10 * observable cost metric. This is distinguished from CPU and memory where
11 * wallclock time and the number of bytes can serve as accurate enough
12 * approximations.
13 *
14 * Bandwidth and iops are the most commonly used metrics for IO devices but
15 * depending on the type and specifics of the device, different IO patterns
16 * easily lead to multiple orders of magnitude variations rendering them
17 * useless for the purpose of IO capacity distribution. While on-device
18 * time, with a lot of clutches, could serve as a useful approximation for
19 * non-queued rotational devices, this is no longer viable with modern
20 * devices, even the rotational ones.
21 *
22 * While there is no cost metric we can trivially observe, it isn't a
23 * complete mystery. For example, on a rotational device, seek cost
24 * dominates while a contiguous transfer contributes a smaller amount
25 * proportional to the size. If we can characterize at least the relative
26 * costs of these different types of IOs, it should be possible to
27 * implement a reasonable work-conserving proportional IO resource
28 * distribution.
29 *
30 * 1. IO Cost Model
31 *
32 * IO cost model estimates the cost of an IO given its basic parameters and
33 * history (e.g. the end sector of the last IO). The cost is measured in
34 * device time. If a given IO is estimated to cost 10ms, the device should
35 * be able to process ~100 of those IOs in a second.
36 *
37 * Currently, there's only one builtin cost model - linear. Each IO is
38 * classified as sequential or random and given a base cost accordingly.
39 * On top of that, a size cost proportional to the length of the IO is
40 * added. While simple, this model captures the operational
41 * characteristics of a wide varienty of devices well enough. Default
42 * paramters for several different classes of devices are provided and the
43 * parameters can be configured from userspace via
44 * /sys/fs/cgroup/io.cost.model.
45 *
46 * If needed, tools/cgroup/iocost_coef_gen.py can be used to generate
47 * device-specific coefficients.
48 *
49 * 2. Control Strategy
50 *
51 * The device virtual time (vtime) is used as the primary control metric.
52 * The control strategy is composed of the following three parts.
53 *
54 * 2-1. Vtime Distribution
55 *
56 * When a cgroup becomes active in terms of IOs, its hierarchical share is
57 * calculated. Please consider the following hierarchy where the numbers
58 * inside parentheses denote the configured weights.
59 *
60 * root
61 * / \
62 * A (w:100) B (w:300)
63 * / \
64 * A0 (w:100) A1 (w:100)
65 *
66 * If B is idle and only A0 and A1 are actively issuing IOs, as the two are
67 * of equal weight, each gets 50% share. If then B starts issuing IOs, B
68 * gets 300/(100+300) or 75% share, and A0 and A1 equally splits the rest,
69 * 12.5% each. The distribution mechanism only cares about these flattened
70 * shares. They're called hweights (hierarchical weights) and always add
Tejun Heofe20cdb52020-09-01 14:52:38 -040071 * upto 1 (WEIGHT_ONE).
Tejun Heo7caa4712019-08-28 15:05:58 -070072 *
73 * A given cgroup's vtime runs slower in inverse proportion to its hweight.
74 * For example, with 12.5% weight, A0's time runs 8 times slower (100/12.5)
75 * against the device vtime - an IO which takes 10ms on the underlying
76 * device is considered to take 80ms on A0.
77 *
78 * This constitutes the basis of IO capacity distribution. Each cgroup's
79 * vtime is running at a rate determined by its hweight. A cgroup tracks
80 * the vtime consumed by past IOs and can issue a new IO iff doing so
81 * wouldn't outrun the current device vtime. Otherwise, the IO is
82 * suspended until the vtime has progressed enough to cover it.
83 *
84 * 2-2. Vrate Adjustment
85 *
86 * It's unrealistic to expect the cost model to be perfect. There are too
87 * many devices and even on the same device the overall performance
88 * fluctuates depending on numerous factors such as IO mixture and device
89 * internal garbage collection. The controller needs to adapt dynamically.
90 *
91 * This is achieved by adjusting the overall IO rate according to how busy
92 * the device is. If the device becomes overloaded, we're sending down too
93 * many IOs and should generally slow down. If there are waiting issuers
94 * but the device isn't saturated, we're issuing too few and should
95 * generally speed up.
96 *
97 * To slow down, we lower the vrate - the rate at which the device vtime
98 * passes compared to the wall clock. For example, if the vtime is running
99 * at the vrate of 75%, all cgroups added up would only be able to issue
100 * 750ms worth of IOs per second, and vice-versa for speeding up.
101 *
102 * Device business is determined using two criteria - rq wait and
103 * completion latencies.
104 *
105 * When a device gets saturated, the on-device and then the request queues
106 * fill up and a bio which is ready to be issued has to wait for a request
107 * to become available. When this delay becomes noticeable, it's a clear
108 * indication that the device is saturated and we lower the vrate. This
109 * saturation signal is fairly conservative as it only triggers when both
110 * hardware and software queues are filled up, and is used as the default
111 * busy signal.
112 *
113 * As devices can have deep queues and be unfair in how the queued commands
114 * are executed, soley depending on rq wait may not result in satisfactory
115 * control quality. For a better control quality, completion latency QoS
116 * parameters can be configured so that the device is considered saturated
117 * if N'th percentile completion latency rises above the set point.
118 *
119 * The completion latency requirements are a function of both the
120 * underlying device characteristics and the desired IO latency quality of
121 * service. There is an inherent trade-off - the tighter the latency QoS,
122 * the higher the bandwidth lossage. Latency QoS is disabled by default
123 * and can be set through /sys/fs/cgroup/io.cost.qos.
124 *
125 * 2-3. Work Conservation
126 *
127 * Imagine two cgroups A and B with equal weights. A is issuing a small IO
128 * periodically while B is sending out enough parallel IOs to saturate the
129 * device on its own. Let's say A's usage amounts to 100ms worth of IO
130 * cost per second, i.e., 10% of the device capacity. The naive
131 * distribution of half and half would lead to 60% utilization of the
132 * device, a significant reduction in the total amount of work done
133 * compared to free-for-all competition. This is too high a cost to pay
134 * for IO control.
135 *
136 * To conserve the total amount of work done, we keep track of how much
137 * each active cgroup is actually using and yield part of its weight if
138 * there are other cgroups which can make use of it. In the above case,
139 * A's weight will be lowered so that it hovers above the actual usage and
140 * B would be able to use the rest.
141 *
142 * As we don't want to penalize a cgroup for donating its weight, the
143 * surplus weight adjustment factors in a margin and has an immediate
144 * snapback mechanism in case the cgroup needs more IO vtime for itself.
145 *
146 * Note that adjusting down surplus weights has the same effects as
147 * accelerating vtime for other cgroups and work conservation can also be
148 * implemented by adjusting vrate dynamically. However, squaring who can
149 * donate and should take back how much requires hweight propagations
150 * anyway making it easier to implement and understand as a separate
151 * mechanism.
Tejun Heo6954ff12019-08-28 15:05:59 -0700152 *
153 * 3. Monitoring
154 *
155 * Instead of debugfs or other clumsy monitoring mechanisms, this
156 * controller uses a drgn based monitoring script -
157 * tools/cgroup/iocost_monitor.py. For details on drgn, please see
158 * https://github.com/osandov/drgn. The ouput looks like the following.
159 *
160 * sdb RUN per=300ms cur_per=234.218:v203.695 busy= +1 vrate= 62.12%
Tejun Heo7c1ee702019-09-04 12:45:56 -0700161 * active weight hweight% inflt% dbt delay usages%
162 * test/a * 50/ 50 33.33/ 33.33 27.65 2 0*041 033:033:033
163 * test/b * 100/ 100 66.67/ 66.67 17.56 0 0*000 066:079:077
Tejun Heo6954ff12019-08-28 15:05:59 -0700164 *
165 * - per : Timer period
166 * - cur_per : Internal wall and device vtime clock
167 * - vrate : Device virtual time rate against wall clock
168 * - weight : Surplus-adjusted and configured weights
169 * - hweight : Surplus-adjusted and configured hierarchical weights
170 * - inflt : The percentage of in-flight IO cost at the end of last period
171 * - del_ms : Deferred issuer delay induction level and duration
172 * - usages : Usage history
Tejun Heo7caa4712019-08-28 15:05:58 -0700173 */
174
175#include <linux/kernel.h>
176#include <linux/module.h>
177#include <linux/timer.h>
178#include <linux/time64.h>
179#include <linux/parser.h>
180#include <linux/sched/signal.h>
181#include <linux/blk-cgroup.h>
Tejun Heo5e124f72020-09-01 14:52:33 -0400182#include <asm/local.h>
183#include <asm/local64.h>
Tejun Heo7caa4712019-08-28 15:05:58 -0700184#include "blk-rq-qos.h"
185#include "blk-stat.h"
186#include "blk-wbt.h"
187
188#ifdef CONFIG_TRACEPOINTS
189
190/* copied from TRACE_CGROUP_PATH, see cgroup-internal.h */
191#define TRACE_IOCG_PATH_LEN 1024
192static DEFINE_SPINLOCK(trace_iocg_path_lock);
193static char trace_iocg_path[TRACE_IOCG_PATH_LEN];
194
195#define TRACE_IOCG_PATH(type, iocg, ...) \
196 do { \
197 unsigned long flags; \
198 if (trace_iocost_##type##_enabled()) { \
199 spin_lock_irqsave(&trace_iocg_path_lock, flags); \
200 cgroup_path(iocg_to_blkg(iocg)->blkcg->css.cgroup, \
201 trace_iocg_path, TRACE_IOCG_PATH_LEN); \
202 trace_iocost_##type(iocg, trace_iocg_path, \
203 ##__VA_ARGS__); \
204 spin_unlock_irqrestore(&trace_iocg_path_lock, flags); \
205 } \
206 } while (0)
207
208#else /* CONFIG_TRACE_POINTS */
209#define TRACE_IOCG_PATH(type, iocg, ...) do { } while (0)
210#endif /* CONFIG_TRACE_POINTS */
211
212enum {
213 MILLION = 1000000,
214
215 /* timer period is calculated from latency requirements, bound it */
216 MIN_PERIOD = USEC_PER_MSEC,
217 MAX_PERIOD = USEC_PER_SEC,
218
219 /*
Tejun Heof1de2432020-09-01 14:52:49 -0400220 * iocg->vtime is targeted at 50% behind the device vtime, which
Tejun Heo7caa4712019-08-28 15:05:58 -0700221 * serves as its IO credit buffer. Surplus weight adjustment is
222 * immediately canceled if the vtime margin runs below 10%.
223 */
Tejun Heo7ca5b2e2020-09-01 14:52:41 -0400224 MARGIN_MIN_PCT = 10,
Tejun Heof1de2432020-09-01 14:52:49 -0400225 MARGIN_LOW_PCT = 20,
226 MARGIN_TARGET_PCT = 50,
227 MARGIN_MAX_PCT = 100,
Tejun Heo7caa4712019-08-28 15:05:58 -0700228
Tejun Heob0853ab2020-09-01 14:52:50 -0400229 INUSE_ADJ_STEP_PCT = 25,
230
Tejun Heo7ca5b2e2020-09-01 14:52:41 -0400231 /* Have some play in timer operations */
232 TIMER_SLACK_PCT = 1,
Tejun Heo7caa4712019-08-28 15:05:58 -0700233
234 /*
235 * vtime can wrap well within a reasonable uptime when vrate is
236 * consistently raised. Don't trust recorded cgroup vtime if the
237 * period counter indicates that it's older than 5mins.
238 */
239 VTIME_VALID_DUR = 300 * USEC_PER_SEC,
240
Tejun Heo7caa4712019-08-28 15:05:58 -0700241 /* 1/64k is granular enough and can easily be handled w/ u32 */
Tejun Heofe20cdb52020-09-01 14:52:38 -0400242 WEIGHT_ONE = 1 << 16,
Tejun Heo7caa4712019-08-28 15:05:58 -0700243
244 /*
245 * As vtime is used to calculate the cost of each IO, it needs to
246 * be fairly high precision. For example, it should be able to
247 * represent the cost of a single page worth of discard with
248 * suffificient accuracy. At the same time, it should be able to
249 * represent reasonably long enough durations to be useful and
250 * convenient during operation.
251 *
252 * 1s worth of vtime is 2^37. This gives us both sub-nanosecond
253 * granularity and days of wrap-around time even at extreme vrates.
254 */
255 VTIME_PER_SEC_SHIFT = 37,
256 VTIME_PER_SEC = 1LLU << VTIME_PER_SEC_SHIFT,
257 VTIME_PER_USEC = VTIME_PER_SEC / USEC_PER_SEC,
Tejun Heocd006502020-04-13 12:27:56 -0400258 VTIME_PER_NSEC = VTIME_PER_SEC / NSEC_PER_SEC,
Tejun Heo7caa4712019-08-28 15:05:58 -0700259
260 /* bound vrate adjustments within two orders of magnitude */
261 VRATE_MIN_PPM = 10000, /* 1% */
262 VRATE_MAX_PPM = 100000000, /* 10000% */
263
264 VRATE_MIN = VTIME_PER_USEC * VRATE_MIN_PPM / MILLION,
265 VRATE_CLAMP_ADJ_PCT = 4,
266
267 /* if IOs end up waiting for requests, issue less */
268 RQ_WAIT_BUSY_PCT = 5,
269
270 /* unbusy hysterisis */
271 UNBUSY_THR_PCT = 75,
272
273 /* don't let cmds which take a very long time pin lagging for too long */
274 MAX_LAGGING_PERIODS = 10,
275
Tejun Heo7caa4712019-08-28 15:05:58 -0700276 /* switch iff the conditions are met for longer than this */
277 AUTOP_CYCLE_NSEC = 10LLU * NSEC_PER_SEC,
278
279 /*
280 * Count IO size in 4k pages. The 12bit shift helps keeping
281 * size-proportional components of cost calculation in closer
282 * numbers of digits to per-IO cost components.
283 */
284 IOC_PAGE_SHIFT = 12,
285 IOC_PAGE_SIZE = 1 << IOC_PAGE_SHIFT,
286 IOC_SECT_TO_PAGE_SHIFT = IOC_PAGE_SHIFT - SECTOR_SHIFT,
287
288 /* if apart further than 16M, consider randio for linear model */
289 LCOEF_RANDIO_PAGES = 4096,
290};
291
292enum ioc_running {
293 IOC_IDLE,
294 IOC_RUNNING,
295 IOC_STOP,
296};
297
298/* io.cost.qos controls including per-dev enable of the whole controller */
299enum {
300 QOS_ENABLE,
301 QOS_CTRL,
302 NR_QOS_CTRL_PARAMS,
303};
304
305/* io.cost.qos params */
306enum {
307 QOS_RPPM,
308 QOS_RLAT,
309 QOS_WPPM,
310 QOS_WLAT,
311 QOS_MIN,
312 QOS_MAX,
313 NR_QOS_PARAMS,
314};
315
316/* io.cost.model controls */
317enum {
318 COST_CTRL,
319 COST_MODEL,
320 NR_COST_CTRL_PARAMS,
321};
322
323/* builtin linear cost model coefficients */
324enum {
325 I_LCOEF_RBPS,
326 I_LCOEF_RSEQIOPS,
327 I_LCOEF_RRANDIOPS,
328 I_LCOEF_WBPS,
329 I_LCOEF_WSEQIOPS,
330 I_LCOEF_WRANDIOPS,
331 NR_I_LCOEFS,
332};
333
334enum {
335 LCOEF_RPAGE,
336 LCOEF_RSEQIO,
337 LCOEF_RRANDIO,
338 LCOEF_WPAGE,
339 LCOEF_WSEQIO,
340 LCOEF_WRANDIO,
341 NR_LCOEFS,
342};
343
344enum {
345 AUTOP_INVALID,
346 AUTOP_HDD,
347 AUTOP_SSD_QD1,
348 AUTOP_SSD_DFL,
349 AUTOP_SSD_FAST,
350};
351
352struct ioc_gq;
353
354struct ioc_params {
355 u32 qos[NR_QOS_PARAMS];
356 u64 i_lcoefs[NR_I_LCOEFS];
357 u64 lcoefs[NR_LCOEFS];
358 u32 too_fast_vrate_pct;
359 u32 too_slow_vrate_pct;
360};
361
Tejun Heo7ca5b2e2020-09-01 14:52:41 -0400362struct ioc_margins {
363 s64 min;
Tejun Heof1de2432020-09-01 14:52:49 -0400364 s64 low;
365 s64 target;
Tejun Heo7ca5b2e2020-09-01 14:52:41 -0400366 s64 max;
367};
368
Tejun Heo7caa4712019-08-28 15:05:58 -0700369struct ioc_missed {
Tejun Heo5e124f72020-09-01 14:52:33 -0400370 local_t nr_met;
371 local_t nr_missed;
Tejun Heo7caa4712019-08-28 15:05:58 -0700372 u32 last_met;
373 u32 last_missed;
374};
375
376struct ioc_pcpu_stat {
377 struct ioc_missed missed[2];
378
Tejun Heo5e124f72020-09-01 14:52:33 -0400379 local64_t rq_wait_ns;
Tejun Heo7caa4712019-08-28 15:05:58 -0700380 u64 last_rq_wait_ns;
381};
382
383/* per device */
384struct ioc {
385 struct rq_qos rqos;
386
387 bool enabled;
388
389 struct ioc_params params;
Tejun Heo7ca5b2e2020-09-01 14:52:41 -0400390 struct ioc_margins margins;
Tejun Heo7caa4712019-08-28 15:05:58 -0700391 u32 period_us;
Tejun Heo7ca5b2e2020-09-01 14:52:41 -0400392 u32 timer_slack_ns;
Tejun Heo7caa4712019-08-28 15:05:58 -0700393 u64 vrate_min;
394 u64 vrate_max;
395
396 spinlock_t lock;
397 struct timer_list timer;
398 struct list_head active_iocgs; /* active cgroups */
399 struct ioc_pcpu_stat __percpu *pcpu_stat;
400
401 enum ioc_running running;
402 atomic64_t vtime_rate;
403
Ahmed S. Darwish67b7b642020-07-20 17:55:26 +0200404 seqcount_spinlock_t period_seqcount;
Tejun Heoce955702020-09-01 14:52:40 -0400405 u64 period_at; /* wallclock starttime */
Tejun Heo7caa4712019-08-28 15:05:58 -0700406 u64 period_at_vtime; /* vtime starttime */
407
408 atomic64_t cur_period; /* inc'd each period */
409 int busy_level; /* saturation history */
410
Tejun Heo7caa4712019-08-28 15:05:58 -0700411 bool weights_updated;
412 atomic_t hweight_gen; /* for lazy hweights */
413
414 u64 autop_too_fast_at;
415 u64 autop_too_slow_at;
416 int autop_idx;
417 bool user_qos_params:1;
418 bool user_cost_model:1;
419};
420
Tejun Heo97eb1972020-09-01 14:52:43 -0400421struct iocg_pcpu_stat {
422 local64_t abs_vusage;
423};
424
425struct iocg_stat {
426 u64 usage_us;
427};
428
Tejun Heo7caa4712019-08-28 15:05:58 -0700429/* per device-cgroup pair */
430struct ioc_gq {
431 struct blkg_policy_data pd;
432 struct ioc *ioc;
433
434 /*
435 * A iocg can get its weight from two sources - an explicit
436 * per-device-cgroup configuration or the default weight of the
437 * cgroup. `cfg_weight` is the explicit per-device-cgroup
438 * configuration. `weight` is the effective considering both
439 * sources.
440 *
441 * When an idle cgroup becomes active its `active` goes from 0 to
442 * `weight`. `inuse` is the surplus adjusted active weight.
443 * `active` and `inuse` are used to calculate `hweight_active` and
444 * `hweight_inuse`.
445 *
446 * `last_inuse` remembers `inuse` while an iocg is idle to persist
447 * surplus adjustments.
Tejun Heob0853ab2020-09-01 14:52:50 -0400448 *
449 * `inuse` may be adjusted dynamically during period. `saved_*` are used
450 * to determine and track adjustments.
Tejun Heo7caa4712019-08-28 15:05:58 -0700451 */
452 u32 cfg_weight;
453 u32 weight;
454 u32 active;
455 u32 inuse;
Tejun Heob0853ab2020-09-01 14:52:50 -0400456
Tejun Heo7caa4712019-08-28 15:05:58 -0700457 u32 last_inuse;
Tejun Heob0853ab2020-09-01 14:52:50 -0400458 s64 saved_margin;
Tejun Heo7caa4712019-08-28 15:05:58 -0700459
460 sector_t cursor; /* to detect randio */
461
462 /*
463 * `vtime` is this iocg's vtime cursor which progresses as IOs are
464 * issued. If lagging behind device vtime, the delta represents
465 * the currently available IO budget. If runnning ahead, the
466 * overage.
467 *
468 * `vtime_done` is the same but progressed on completion rather
469 * than issue. The delta behind `vtime` represents the cost of
470 * currently in-flight IOs.
Tejun Heo7caa4712019-08-28 15:05:58 -0700471 */
472 atomic64_t vtime;
473 atomic64_t done_vtime;
Tejun Heo0b80f982020-05-04 19:27:54 -0400474 u64 abs_vdebt;
Tejun Heo7caa4712019-08-28 15:05:58 -0700475
476 /*
477 * The period this iocg was last active in. Used for deactivation
478 * and invalidating `vtime`.
479 */
480 atomic64_t active_period;
481 struct list_head active_list;
482
Tejun Heo00410f12020-09-01 14:52:34 -0400483 /* see __propagate_weights() and current_hweight() for details */
Tejun Heo7caa4712019-08-28 15:05:58 -0700484 u64 child_active_sum;
485 u64 child_inuse_sum;
Tejun Heoe08d02a2020-09-01 14:52:48 -0400486 u64 child_adjusted_sum;
Tejun Heo7caa4712019-08-28 15:05:58 -0700487 int hweight_gen;
488 u32 hweight_active;
489 u32 hweight_inuse;
Tejun Heoe08d02a2020-09-01 14:52:48 -0400490 u32 hweight_donating;
Tejun Heo93f7d2d2020-09-01 14:52:47 -0400491 u32 hweight_after_donation;
Tejun Heo7caa4712019-08-28 15:05:58 -0700492
Tejun Heo97eb1972020-09-01 14:52:43 -0400493 struct list_head walk_list;
Tejun Heo8692d2d2020-09-01 14:52:45 -0400494 struct list_head surplus_list;
Tejun Heo97eb1972020-09-01 14:52:43 -0400495
Tejun Heo7caa4712019-08-28 15:05:58 -0700496 struct wait_queue_head waitq;
497 struct hrtimer waitq_timer;
498 struct hrtimer delay_timer;
499
Tejun Heo1aa50d02020-09-01 14:52:44 -0400500 /* timestamp at the latest activation */
501 u64 activated_at;
502
Tejun Heo97eb1972020-09-01 14:52:43 -0400503 /* statistics */
504 struct iocg_pcpu_stat __percpu *pcpu_stat;
505 struct iocg_stat local_stat;
506 struct iocg_stat desc_stat;
507 struct iocg_stat last_stat;
508 u64 last_stat_abs_vusage;
Tejun Heof1de2432020-09-01 14:52:49 -0400509 u64 usage_delta_us;
Tejun Heo7caa4712019-08-28 15:05:58 -0700510
511 /* this iocg's depth in the hierarchy and ancestors including self */
512 int level;
513 struct ioc_gq *ancestors[];
514};
515
516/* per cgroup */
517struct ioc_cgrp {
518 struct blkcg_policy_data cpd;
519 unsigned int dfl_weight;
520};
521
522struct ioc_now {
523 u64 now_ns;
Tejun Heoce955702020-09-01 14:52:40 -0400524 u64 now;
Tejun Heo7caa4712019-08-28 15:05:58 -0700525 u64 vnow;
526 u64 vrate;
527};
528
529struct iocg_wait {
530 struct wait_queue_entry wait;
531 struct bio *bio;
532 u64 abs_cost;
533 bool committed;
534};
535
536struct iocg_wake_ctx {
537 struct ioc_gq *iocg;
538 u32 hw_inuse;
539 s64 vbudget;
540};
541
542static const struct ioc_params autop[] = {
543 [AUTOP_HDD] = {
544 .qos = {
Tejun Heo7afccca2019-09-25 16:03:35 -0700545 [QOS_RLAT] = 250000, /* 250ms */
546 [QOS_WLAT] = 250000,
Tejun Heo7caa4712019-08-28 15:05:58 -0700547 [QOS_MIN] = VRATE_MIN_PPM,
548 [QOS_MAX] = VRATE_MAX_PPM,
549 },
550 .i_lcoefs = {
551 [I_LCOEF_RBPS] = 174019176,
552 [I_LCOEF_RSEQIOPS] = 41708,
553 [I_LCOEF_RRANDIOPS] = 370,
554 [I_LCOEF_WBPS] = 178075866,
555 [I_LCOEF_WSEQIOPS] = 42705,
556 [I_LCOEF_WRANDIOPS] = 378,
557 },
558 },
559 [AUTOP_SSD_QD1] = {
560 .qos = {
561 [QOS_RLAT] = 25000, /* 25ms */
562 [QOS_WLAT] = 25000,
563 [QOS_MIN] = VRATE_MIN_PPM,
564 [QOS_MAX] = VRATE_MAX_PPM,
565 },
566 .i_lcoefs = {
567 [I_LCOEF_RBPS] = 245855193,
568 [I_LCOEF_RSEQIOPS] = 61575,
569 [I_LCOEF_RRANDIOPS] = 6946,
570 [I_LCOEF_WBPS] = 141365009,
571 [I_LCOEF_WSEQIOPS] = 33716,
572 [I_LCOEF_WRANDIOPS] = 26796,
573 },
574 },
575 [AUTOP_SSD_DFL] = {
576 .qos = {
577 [QOS_RLAT] = 25000, /* 25ms */
578 [QOS_WLAT] = 25000,
579 [QOS_MIN] = VRATE_MIN_PPM,
580 [QOS_MAX] = VRATE_MAX_PPM,
581 },
582 .i_lcoefs = {
583 [I_LCOEF_RBPS] = 488636629,
584 [I_LCOEF_RSEQIOPS] = 8932,
585 [I_LCOEF_RRANDIOPS] = 8518,
586 [I_LCOEF_WBPS] = 427891549,
587 [I_LCOEF_WSEQIOPS] = 28755,
588 [I_LCOEF_WRANDIOPS] = 21940,
589 },
590 .too_fast_vrate_pct = 500,
591 },
592 [AUTOP_SSD_FAST] = {
593 .qos = {
594 [QOS_RLAT] = 5000, /* 5ms */
595 [QOS_WLAT] = 5000,
596 [QOS_MIN] = VRATE_MIN_PPM,
597 [QOS_MAX] = VRATE_MAX_PPM,
598 },
599 .i_lcoefs = {
600 [I_LCOEF_RBPS] = 3102524156LLU,
601 [I_LCOEF_RSEQIOPS] = 724816,
602 [I_LCOEF_RRANDIOPS] = 778122,
603 [I_LCOEF_WBPS] = 1742780862LLU,
604 [I_LCOEF_WSEQIOPS] = 425702,
605 [I_LCOEF_WRANDIOPS] = 443193,
606 },
607 .too_slow_vrate_pct = 10,
608 },
609};
610
611/*
612 * vrate adjust percentages indexed by ioc->busy_level. We adjust up on
613 * vtime credit shortage and down on device saturation.
614 */
615static u32 vrate_adj_pct[] =
616 { 0, 0, 0, 0,
617 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
618 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
619 4, 4, 4, 4, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8, 16 };
620
621static struct blkcg_policy blkcg_policy_iocost;
622
623/* accessors and helpers */
624static struct ioc *rqos_to_ioc(struct rq_qos *rqos)
625{
626 return container_of(rqos, struct ioc, rqos);
627}
628
629static struct ioc *q_to_ioc(struct request_queue *q)
630{
631 return rqos_to_ioc(rq_qos_id(q, RQ_QOS_COST));
632}
633
634static const char *q_name(struct request_queue *q)
635{
636 if (test_bit(QUEUE_FLAG_REGISTERED, &q->queue_flags))
637 return kobject_name(q->kobj.parent);
638 else
639 return "<unknown>";
640}
641
642static const char __maybe_unused *ioc_name(struct ioc *ioc)
643{
644 return q_name(ioc->rqos.q);
645}
646
647static struct ioc_gq *pd_to_iocg(struct blkg_policy_data *pd)
648{
649 return pd ? container_of(pd, struct ioc_gq, pd) : NULL;
650}
651
652static struct ioc_gq *blkg_to_iocg(struct blkcg_gq *blkg)
653{
654 return pd_to_iocg(blkg_to_pd(blkg, &blkcg_policy_iocost));
655}
656
657static struct blkcg_gq *iocg_to_blkg(struct ioc_gq *iocg)
658{
659 return pd_to_blkg(&iocg->pd);
660}
661
662static struct ioc_cgrp *blkcg_to_iocc(struct blkcg *blkcg)
663{
664 return container_of(blkcg_to_cpd(blkcg, &blkcg_policy_iocost),
665 struct ioc_cgrp, cpd);
666}
667
668/*
669 * Scale @abs_cost to the inverse of @hw_inuse. The lower the hierarchical
Tejun Heo36a52482019-09-04 12:45:52 -0700670 * weight, the more expensive each IO. Must round up.
Tejun Heo7caa4712019-08-28 15:05:58 -0700671 */
672static u64 abs_cost_to_cost(u64 abs_cost, u32 hw_inuse)
673{
Tejun Heofe20cdb52020-09-01 14:52:38 -0400674 return DIV64_U64_ROUND_UP(abs_cost * WEIGHT_ONE, hw_inuse);
Tejun Heo7caa4712019-08-28 15:05:58 -0700675}
676
Tejun Heo36a52482019-09-04 12:45:52 -0700677/*
678 * The inverse of abs_cost_to_cost(). Must round up.
679 */
680static u64 cost_to_abs_cost(u64 cost, u32 hw_inuse)
681{
Tejun Heofe20cdb52020-09-01 14:52:38 -0400682 return DIV64_U64_ROUND_UP(cost * hw_inuse, WEIGHT_ONE);
Tejun Heo36a52482019-09-04 12:45:52 -0700683}
684
Tejun Heo97eb1972020-09-01 14:52:43 -0400685static void iocg_commit_bio(struct ioc_gq *iocg, struct bio *bio,
686 u64 abs_cost, u64 cost)
Tejun Heo7caa4712019-08-28 15:05:58 -0700687{
Tejun Heo97eb1972020-09-01 14:52:43 -0400688 struct iocg_pcpu_stat *gcs;
689
Tejun Heo7caa4712019-08-28 15:05:58 -0700690 bio->bi_iocost_cost = cost;
691 atomic64_add(cost, &iocg->vtime);
Tejun Heo97eb1972020-09-01 14:52:43 -0400692
693 gcs = get_cpu_ptr(iocg->pcpu_stat);
694 local64_add(abs_cost, &gcs->abs_vusage);
695 put_cpu_ptr(gcs);
Tejun Heo7caa4712019-08-28 15:05:58 -0700696}
697
Tejun Heoda437b92020-09-01 14:52:42 -0400698static void iocg_lock(struct ioc_gq *iocg, bool lock_ioc, unsigned long *flags)
699{
700 if (lock_ioc) {
701 spin_lock_irqsave(&iocg->ioc->lock, *flags);
702 spin_lock(&iocg->waitq.lock);
703 } else {
704 spin_lock_irqsave(&iocg->waitq.lock, *flags);
705 }
706}
707
708static void iocg_unlock(struct ioc_gq *iocg, bool unlock_ioc, unsigned long *flags)
709{
710 if (unlock_ioc) {
711 spin_unlock(&iocg->waitq.lock);
712 spin_unlock_irqrestore(&iocg->ioc->lock, *flags);
713 } else {
714 spin_unlock_irqrestore(&iocg->waitq.lock, *flags);
715 }
716}
717
Tejun Heo7caa4712019-08-28 15:05:58 -0700718#define CREATE_TRACE_POINTS
719#include <trace/events/iocost.h>
720
Tejun Heo7ca5b2e2020-09-01 14:52:41 -0400721static void ioc_refresh_margins(struct ioc *ioc)
722{
723 struct ioc_margins *margins = &ioc->margins;
724 u32 period_us = ioc->period_us;
725 u64 vrate = atomic64_read(&ioc->vtime_rate);
726
727 margins->min = (period_us * MARGIN_MIN_PCT / 100) * vrate;
Tejun Heof1de2432020-09-01 14:52:49 -0400728 margins->low = (period_us * MARGIN_LOW_PCT / 100) * vrate;
729 margins->target = (period_us * MARGIN_TARGET_PCT / 100) * vrate;
Tejun Heo7ca5b2e2020-09-01 14:52:41 -0400730 margins->max = (period_us * MARGIN_MAX_PCT / 100) * vrate;
731}
732
Tejun Heo7caa4712019-08-28 15:05:58 -0700733/* latency Qos params changed, update period_us and all the dependent params */
734static void ioc_refresh_period_us(struct ioc *ioc)
735{
736 u32 ppm, lat, multi, period_us;
737
738 lockdep_assert_held(&ioc->lock);
739
740 /* pick the higher latency target */
741 if (ioc->params.qos[QOS_RLAT] >= ioc->params.qos[QOS_WLAT]) {
742 ppm = ioc->params.qos[QOS_RPPM];
743 lat = ioc->params.qos[QOS_RLAT];
744 } else {
745 ppm = ioc->params.qos[QOS_WPPM];
746 lat = ioc->params.qos[QOS_WLAT];
747 }
748
749 /*
750 * We want the period to be long enough to contain a healthy number
751 * of IOs while short enough for granular control. Define it as a
752 * multiple of the latency target. Ideally, the multiplier should
753 * be scaled according to the percentile so that it would nominally
754 * contain a certain number of requests. Let's be simpler and
755 * scale it linearly so that it's 2x >= pct(90) and 10x at pct(50).
756 */
757 if (ppm)
758 multi = max_t(u32, (MILLION - ppm) / 50000, 2);
759 else
760 multi = 2;
761 period_us = multi * lat;
762 period_us = clamp_t(u32, period_us, MIN_PERIOD, MAX_PERIOD);
763
764 /* calculate dependent params */
765 ioc->period_us = period_us;
Tejun Heo7ca5b2e2020-09-01 14:52:41 -0400766 ioc->timer_slack_ns = div64_u64(
767 (u64)period_us * NSEC_PER_USEC * TIMER_SLACK_PCT,
768 100);
769 ioc_refresh_margins(ioc);
Tejun Heo7caa4712019-08-28 15:05:58 -0700770}
771
772static int ioc_autop_idx(struct ioc *ioc)
773{
774 int idx = ioc->autop_idx;
775 const struct ioc_params *p = &autop[idx];
776 u32 vrate_pct;
777 u64 now_ns;
778
779 /* rotational? */
780 if (!blk_queue_nonrot(ioc->rqos.q))
781 return AUTOP_HDD;
782
783 /* handle SATA SSDs w/ broken NCQ */
784 if (blk_queue_depth(ioc->rqos.q) == 1)
785 return AUTOP_SSD_QD1;
786
787 /* use one of the normal ssd sets */
788 if (idx < AUTOP_SSD_DFL)
789 return AUTOP_SSD_DFL;
790
791 /* if user is overriding anything, maintain what was there */
792 if (ioc->user_qos_params || ioc->user_cost_model)
793 return idx;
794
795 /* step up/down based on the vrate */
796 vrate_pct = div64_u64(atomic64_read(&ioc->vtime_rate) * 100,
797 VTIME_PER_USEC);
798 now_ns = ktime_get_ns();
799
800 if (p->too_fast_vrate_pct && p->too_fast_vrate_pct <= vrate_pct) {
801 if (!ioc->autop_too_fast_at)
802 ioc->autop_too_fast_at = now_ns;
803 if (now_ns - ioc->autop_too_fast_at >= AUTOP_CYCLE_NSEC)
804 return idx + 1;
805 } else {
806 ioc->autop_too_fast_at = 0;
807 }
808
809 if (p->too_slow_vrate_pct && p->too_slow_vrate_pct >= vrate_pct) {
810 if (!ioc->autop_too_slow_at)
811 ioc->autop_too_slow_at = now_ns;
812 if (now_ns - ioc->autop_too_slow_at >= AUTOP_CYCLE_NSEC)
813 return idx - 1;
814 } else {
815 ioc->autop_too_slow_at = 0;
816 }
817
818 return idx;
819}
820
821/*
822 * Take the followings as input
823 *
824 * @bps maximum sequential throughput
825 * @seqiops maximum sequential 4k iops
826 * @randiops maximum random 4k iops
827 *
828 * and calculate the linear model cost coefficients.
829 *
830 * *@page per-page cost 1s / (@bps / 4096)
831 * *@seqio base cost of a seq IO max((1s / @seqiops) - *@page, 0)
832 * @randiops base cost of a rand IO max((1s / @randiops) - *@page, 0)
833 */
834static void calc_lcoefs(u64 bps, u64 seqiops, u64 randiops,
835 u64 *page, u64 *seqio, u64 *randio)
836{
837 u64 v;
838
839 *page = *seqio = *randio = 0;
840
841 if (bps)
842 *page = DIV64_U64_ROUND_UP(VTIME_PER_SEC,
843 DIV_ROUND_UP_ULL(bps, IOC_PAGE_SIZE));
844
845 if (seqiops) {
846 v = DIV64_U64_ROUND_UP(VTIME_PER_SEC, seqiops);
847 if (v > *page)
848 *seqio = v - *page;
849 }
850
851 if (randiops) {
852 v = DIV64_U64_ROUND_UP(VTIME_PER_SEC, randiops);
853 if (v > *page)
854 *randio = v - *page;
855 }
856}
857
858static void ioc_refresh_lcoefs(struct ioc *ioc)
859{
860 u64 *u = ioc->params.i_lcoefs;
861 u64 *c = ioc->params.lcoefs;
862
863 calc_lcoefs(u[I_LCOEF_RBPS], u[I_LCOEF_RSEQIOPS], u[I_LCOEF_RRANDIOPS],
864 &c[LCOEF_RPAGE], &c[LCOEF_RSEQIO], &c[LCOEF_RRANDIO]);
865 calc_lcoefs(u[I_LCOEF_WBPS], u[I_LCOEF_WSEQIOPS], u[I_LCOEF_WRANDIOPS],
866 &c[LCOEF_WPAGE], &c[LCOEF_WSEQIO], &c[LCOEF_WRANDIO]);
867}
868
869static bool ioc_refresh_params(struct ioc *ioc, bool force)
870{
871 const struct ioc_params *p;
872 int idx;
873
874 lockdep_assert_held(&ioc->lock);
875
876 idx = ioc_autop_idx(ioc);
877 p = &autop[idx];
878
879 if (idx == ioc->autop_idx && !force)
880 return false;
881
882 if (idx != ioc->autop_idx)
883 atomic64_set(&ioc->vtime_rate, VTIME_PER_USEC);
884
885 ioc->autop_idx = idx;
886 ioc->autop_too_fast_at = 0;
887 ioc->autop_too_slow_at = 0;
888
889 if (!ioc->user_qos_params)
890 memcpy(ioc->params.qos, p->qos, sizeof(p->qos));
891 if (!ioc->user_cost_model)
892 memcpy(ioc->params.i_lcoefs, p->i_lcoefs, sizeof(p->i_lcoefs));
893
894 ioc_refresh_period_us(ioc);
895 ioc_refresh_lcoefs(ioc);
896
897 ioc->vrate_min = DIV64_U64_ROUND_UP((u64)ioc->params.qos[QOS_MIN] *
898 VTIME_PER_USEC, MILLION);
899 ioc->vrate_max = div64_u64((u64)ioc->params.qos[QOS_MAX] *
900 VTIME_PER_USEC, MILLION);
901
902 return true;
903}
904
905/* take a snapshot of the current [v]time and vrate */
906static void ioc_now(struct ioc *ioc, struct ioc_now *now)
907{
908 unsigned seq;
909
910 now->now_ns = ktime_get();
911 now->now = ktime_to_us(now->now_ns);
912 now->vrate = atomic64_read(&ioc->vtime_rate);
913
914 /*
915 * The current vtime is
916 *
917 * vtime at period start + (wallclock time since the start) * vrate
918 *
919 * As a consistent snapshot of `period_at_vtime` and `period_at` is
920 * needed, they're seqcount protected.
921 */
922 do {
923 seq = read_seqcount_begin(&ioc->period_seqcount);
924 now->vnow = ioc->period_at_vtime +
925 (now->now - ioc->period_at) * now->vrate;
926 } while (read_seqcount_retry(&ioc->period_seqcount, seq));
927}
928
929static void ioc_start_period(struct ioc *ioc, struct ioc_now *now)
930{
Tejun Heo7caa4712019-08-28 15:05:58 -0700931 WARN_ON_ONCE(ioc->running != IOC_RUNNING);
932
933 write_seqcount_begin(&ioc->period_seqcount);
934 ioc->period_at = now->now;
935 ioc->period_at_vtime = now->vnow;
936 write_seqcount_end(&ioc->period_seqcount);
937
938 ioc->timer.expires = jiffies + usecs_to_jiffies(ioc->period_us);
939 add_timer(&ioc->timer);
940}
941
942/*
943 * Update @iocg's `active` and `inuse` to @active and @inuse, update level
Tejun Heob0853ab2020-09-01 14:52:50 -0400944 * weight sums and propagate upwards accordingly. If @save, the current margin
945 * is saved to be used as reference for later inuse in-period adjustments.
Tejun Heo7caa4712019-08-28 15:05:58 -0700946 */
Tejun Heob0853ab2020-09-01 14:52:50 -0400947static void __propagate_weights(struct ioc_gq *iocg, u32 active, u32 inuse,
948 bool save, struct ioc_now *now)
Tejun Heo7caa4712019-08-28 15:05:58 -0700949{
950 struct ioc *ioc = iocg->ioc;
951 int lvl;
952
953 lockdep_assert_held(&ioc->lock);
954
Tejun Heodb84a722020-09-01 14:52:35 -0400955 inuse = clamp_t(u32, inuse, 1, active);
956
Tejun Heob0853ab2020-09-01 14:52:50 -0400957 iocg->last_inuse = iocg->inuse;
958 if (save)
959 iocg->saved_margin = now->vnow - atomic64_read(&iocg->vtime);
960
Tejun Heodb84a722020-09-01 14:52:35 -0400961 if (active == iocg->active && inuse == iocg->inuse)
962 return;
Tejun Heo7caa4712019-08-28 15:05:58 -0700963
964 for (lvl = iocg->level - 1; lvl >= 0; lvl--) {
965 struct ioc_gq *parent = iocg->ancestors[lvl];
966 struct ioc_gq *child = iocg->ancestors[lvl + 1];
967 u32 parent_active = 0, parent_inuse = 0;
968
969 /* update the level sums */
970 parent->child_active_sum += (s32)(active - child->active);
971 parent->child_inuse_sum += (s32)(inuse - child->inuse);
972 /* apply the udpates */
973 child->active = active;
974 child->inuse = inuse;
975
976 /*
977 * The delta between inuse and active sums indicates that
978 * that much of weight is being given away. Parent's inuse
979 * and active should reflect the ratio.
980 */
981 if (parent->child_active_sum) {
982 parent_active = parent->weight;
983 parent_inuse = DIV64_U64_ROUND_UP(
984 parent_active * parent->child_inuse_sum,
985 parent->child_active_sum);
986 }
987
988 /* do we need to keep walking up? */
989 if (parent_active == parent->active &&
990 parent_inuse == parent->inuse)
991 break;
992
993 active = parent_active;
994 inuse = parent_inuse;
995 }
996
997 ioc->weights_updated = true;
998}
999
Tejun Heo00410f12020-09-01 14:52:34 -04001000static void commit_weights(struct ioc *ioc)
Tejun Heo7caa4712019-08-28 15:05:58 -07001001{
1002 lockdep_assert_held(&ioc->lock);
1003
1004 if (ioc->weights_updated) {
1005 /* paired with rmb in current_hweight(), see there */
1006 smp_wmb();
1007 atomic_inc(&ioc->hweight_gen);
1008 ioc->weights_updated = false;
1009 }
1010}
1011
Tejun Heob0853ab2020-09-01 14:52:50 -04001012static void propagate_weights(struct ioc_gq *iocg, u32 active, u32 inuse,
1013 bool save, struct ioc_now *now)
Tejun Heo7caa4712019-08-28 15:05:58 -07001014{
Tejun Heob0853ab2020-09-01 14:52:50 -04001015 __propagate_weights(iocg, active, inuse, save, now);
Tejun Heo00410f12020-09-01 14:52:34 -04001016 commit_weights(iocg->ioc);
Tejun Heo7caa4712019-08-28 15:05:58 -07001017}
1018
1019static void current_hweight(struct ioc_gq *iocg, u32 *hw_activep, u32 *hw_inusep)
1020{
1021 struct ioc *ioc = iocg->ioc;
1022 int lvl;
1023 u32 hwa, hwi;
1024 int ioc_gen;
1025
1026 /* hot path - if uptodate, use cached */
1027 ioc_gen = atomic_read(&ioc->hweight_gen);
1028 if (ioc_gen == iocg->hweight_gen)
1029 goto out;
1030
1031 /*
Tejun Heo00410f12020-09-01 14:52:34 -04001032 * Paired with wmb in commit_weights(). If we saw the updated
1033 * hweight_gen, all the weight updates from __propagate_weights() are
1034 * visible too.
Tejun Heo7caa4712019-08-28 15:05:58 -07001035 *
1036 * We can race with weight updates during calculation and get it
1037 * wrong. However, hweight_gen would have changed and a future
1038 * reader will recalculate and we're guaranteed to discard the
1039 * wrong result soon.
1040 */
1041 smp_rmb();
1042
Tejun Heofe20cdb52020-09-01 14:52:38 -04001043 hwa = hwi = WEIGHT_ONE;
Tejun Heo7caa4712019-08-28 15:05:58 -07001044 for (lvl = 0; lvl <= iocg->level - 1; lvl++) {
1045 struct ioc_gq *parent = iocg->ancestors[lvl];
1046 struct ioc_gq *child = iocg->ancestors[lvl + 1];
Tejun Heobd0adb92020-09-01 14:52:39 -04001047 u64 active_sum = READ_ONCE(parent->child_active_sum);
1048 u64 inuse_sum = READ_ONCE(parent->child_inuse_sum);
Tejun Heo7caa4712019-08-28 15:05:58 -07001049 u32 active = READ_ONCE(child->active);
1050 u32 inuse = READ_ONCE(child->inuse);
1051
1052 /* we can race with deactivations and either may read as zero */
1053 if (!active_sum || !inuse_sum)
1054 continue;
1055
Tejun Heobd0adb92020-09-01 14:52:39 -04001056 active_sum = max_t(u64, active, active_sum);
1057 hwa = div64_u64((u64)hwa * active, active_sum);
Tejun Heo7caa4712019-08-28 15:05:58 -07001058
Tejun Heobd0adb92020-09-01 14:52:39 -04001059 inuse_sum = max_t(u64, inuse, inuse_sum);
1060 hwi = div64_u64((u64)hwi * inuse, inuse_sum);
Tejun Heo7caa4712019-08-28 15:05:58 -07001061 }
1062
1063 iocg->hweight_active = max_t(u32, hwa, 1);
1064 iocg->hweight_inuse = max_t(u32, hwi, 1);
1065 iocg->hweight_gen = ioc_gen;
1066out:
1067 if (hw_activep)
1068 *hw_activep = iocg->hweight_active;
1069 if (hw_inusep)
1070 *hw_inusep = iocg->hweight_inuse;
1071}
1072
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001073/*
1074 * Calculate the hweight_inuse @iocg would get with max @inuse assuming all the
1075 * other weights stay unchanged.
1076 */
1077static u32 current_hweight_max(struct ioc_gq *iocg)
1078{
1079 u32 hwm = WEIGHT_ONE;
1080 u32 inuse = iocg->active;
1081 u64 child_inuse_sum;
1082 int lvl;
1083
1084 lockdep_assert_held(&iocg->ioc->lock);
1085
1086 for (lvl = iocg->level - 1; lvl >= 0; lvl--) {
1087 struct ioc_gq *parent = iocg->ancestors[lvl];
1088 struct ioc_gq *child = iocg->ancestors[lvl + 1];
1089
1090 child_inuse_sum = parent->child_inuse_sum + inuse - child->inuse;
1091 hwm = div64_u64((u64)hwm * inuse, child_inuse_sum);
1092 inuse = DIV64_U64_ROUND_UP(parent->active * child_inuse_sum,
1093 parent->child_active_sum);
1094 }
1095
1096 return max_t(u32, hwm, 1);
1097}
1098
Tejun Heob0853ab2020-09-01 14:52:50 -04001099static void weight_updated(struct ioc_gq *iocg, struct ioc_now *now)
Tejun Heo7caa4712019-08-28 15:05:58 -07001100{
1101 struct ioc *ioc = iocg->ioc;
1102 struct blkcg_gq *blkg = iocg_to_blkg(iocg);
1103 struct ioc_cgrp *iocc = blkcg_to_iocc(blkg->blkcg);
1104 u32 weight;
1105
1106 lockdep_assert_held(&ioc->lock);
1107
1108 weight = iocg->cfg_weight ?: iocc->dfl_weight;
1109 if (weight != iocg->weight && iocg->active)
Tejun Heob0853ab2020-09-01 14:52:50 -04001110 propagate_weights(iocg, weight, iocg->inuse, true, now);
Tejun Heo7caa4712019-08-28 15:05:58 -07001111 iocg->weight = weight;
1112}
1113
1114static bool iocg_activate(struct ioc_gq *iocg, struct ioc_now *now)
1115{
1116 struct ioc *ioc = iocg->ioc;
1117 u64 last_period, cur_period, max_period_delta;
Tejun Heo7ca5b2e2020-09-01 14:52:41 -04001118 u64 vtime, vmin;
Tejun Heo7caa4712019-08-28 15:05:58 -07001119 int i;
1120
1121 /*
1122 * If seem to be already active, just update the stamp to tell the
1123 * timer that we're still active. We don't mind occassional races.
1124 */
1125 if (!list_empty(&iocg->active_list)) {
1126 ioc_now(ioc, now);
1127 cur_period = atomic64_read(&ioc->cur_period);
1128 if (atomic64_read(&iocg->active_period) != cur_period)
1129 atomic64_set(&iocg->active_period, cur_period);
1130 return true;
1131 }
1132
1133 /* racy check on internal node IOs, treat as root level IOs */
1134 if (iocg->child_active_sum)
1135 return false;
1136
1137 spin_lock_irq(&ioc->lock);
1138
1139 ioc_now(ioc, now);
1140
1141 /* update period */
1142 cur_period = atomic64_read(&ioc->cur_period);
1143 last_period = atomic64_read(&iocg->active_period);
1144 atomic64_set(&iocg->active_period, cur_period);
1145
1146 /* already activated or breaking leaf-only constraint? */
Jiufei Xue8b37bc22019-11-13 15:21:31 +08001147 if (!list_empty(&iocg->active_list))
1148 goto succeed_unlock;
1149 for (i = iocg->level - 1; i > 0; i--)
1150 if (!list_empty(&iocg->ancestors[i]->active_list))
Tejun Heo7caa4712019-08-28 15:05:58 -07001151 goto fail_unlock;
Jiufei Xue8b37bc22019-11-13 15:21:31 +08001152
Tejun Heo7caa4712019-08-28 15:05:58 -07001153 if (iocg->child_active_sum)
1154 goto fail_unlock;
1155
1156 /*
1157 * vtime may wrap when vrate is raised substantially due to
1158 * underestimated IO costs. Look at the period and ignore its
1159 * vtime if the iocg has been idle for too long. Also, cap the
1160 * budget it can start with to the margin.
1161 */
1162 max_period_delta = DIV64_U64_ROUND_UP(VTIME_VALID_DUR, ioc->period_us);
1163 vtime = atomic64_read(&iocg->vtime);
Tejun Heo7ca5b2e2020-09-01 14:52:41 -04001164 vmin = now->vnow - ioc->margins.max;
Tejun Heo7caa4712019-08-28 15:05:58 -07001165
1166 if (last_period + max_period_delta < cur_period ||
1167 time_before64(vtime, vmin)) {
1168 atomic64_add(vmin - vtime, &iocg->vtime);
1169 atomic64_add(vmin - vtime, &iocg->done_vtime);
1170 vtime = vmin;
1171 }
1172
1173 /*
1174 * Activate, propagate weight and start period timer if not
1175 * running. Reset hweight_gen to avoid accidental match from
1176 * wrapping.
1177 */
1178 iocg->hweight_gen = atomic_read(&ioc->hweight_gen) - 1;
1179 list_add(&iocg->active_list, &ioc->active_iocgs);
Tejun Heob0853ab2020-09-01 14:52:50 -04001180
Tejun Heo00410f12020-09-01 14:52:34 -04001181 propagate_weights(iocg, iocg->weight,
Tejun Heob0853ab2020-09-01 14:52:50 -04001182 iocg->last_inuse ?: iocg->weight, true, now);
Tejun Heo7caa4712019-08-28 15:05:58 -07001183
1184 TRACE_IOCG_PATH(iocg_activate, iocg, now,
1185 last_period, cur_period, vtime);
1186
Tejun Heo1aa50d02020-09-01 14:52:44 -04001187 iocg->activated_at = now->now;
Tejun Heo7caa4712019-08-28 15:05:58 -07001188
1189 if (ioc->running == IOC_IDLE) {
1190 ioc->running = IOC_RUNNING;
1191 ioc_start_period(ioc, now);
1192 }
1193
Jiufei Xue8b37bc22019-11-13 15:21:31 +08001194succeed_unlock:
Tejun Heo7caa4712019-08-28 15:05:58 -07001195 spin_unlock_irq(&ioc->lock);
1196 return true;
1197
1198fail_unlock:
1199 spin_unlock_irq(&ioc->lock);
1200 return false;
1201}
1202
Tejun Heo6ef20f72020-09-01 14:52:36 -04001203static bool iocg_kick_delay(struct ioc_gq *iocg, struct ioc_now *now)
1204{
1205 struct ioc *ioc = iocg->ioc;
1206 struct blkcg_gq *blkg = iocg_to_blkg(iocg);
1207 u64 vtime = atomic64_read(&iocg->vtime);
Tejun Heo6ef20f72020-09-01 14:52:36 -04001208 u64 delta_ns, expires, oexpires;
Tejun Heoc421a3e2020-09-01 14:52:51 -04001209 u32 hwa;
Tejun Heo6ef20f72020-09-01 14:52:36 -04001210
1211 lockdep_assert_held(&iocg->waitq.lock);
1212
1213 /* debt-adjust vtime */
Tejun Heoc421a3e2020-09-01 14:52:51 -04001214 current_hweight(iocg, &hwa, NULL);
1215 vtime += abs_cost_to_cost(iocg->abs_vdebt, hwa);
Tejun Heo6ef20f72020-09-01 14:52:36 -04001216
1217 /*
1218 * Clear or maintain depending on the overage. Non-zero vdebt is what
1219 * guarantees that @iocg is online and future iocg_kick_delay() will
1220 * clear use_delay. Don't leave it on when there's no vdebt.
1221 */
1222 if (!iocg->abs_vdebt || time_before_eq64(vtime, now->vnow)) {
1223 blkcg_clear_delay(blkg);
1224 return false;
1225 }
1226 if (!atomic_read(&blkg->use_delay) &&
Tejun Heof1de2432020-09-01 14:52:49 -04001227 time_before_eq64(vtime, now->vnow + ioc->margins.target))
Tejun Heo6ef20f72020-09-01 14:52:36 -04001228 return false;
1229
1230 /* use delay */
1231 delta_ns = DIV64_U64_ROUND_UP(vtime - now->vnow,
1232 now->vrate) * NSEC_PER_USEC;
1233 blkcg_set_delay(blkg, delta_ns);
1234 expires = now->now_ns + delta_ns;
1235
1236 /* if already active and close enough, don't bother */
1237 oexpires = ktime_to_ns(hrtimer_get_softexpires(&iocg->delay_timer));
1238 if (hrtimer_is_queued(&iocg->delay_timer) &&
Tejun Heo7ca5b2e2020-09-01 14:52:41 -04001239 abs(oexpires - expires) <= ioc->timer_slack_ns)
Tejun Heo6ef20f72020-09-01 14:52:36 -04001240 return true;
1241
1242 hrtimer_start_range_ns(&iocg->delay_timer, ns_to_ktime(expires),
Tejun Heo7ca5b2e2020-09-01 14:52:41 -04001243 ioc->timer_slack_ns, HRTIMER_MODE_ABS);
Tejun Heo6ef20f72020-09-01 14:52:36 -04001244 return true;
1245}
1246
1247static enum hrtimer_restart iocg_delay_timer_fn(struct hrtimer *timer)
1248{
1249 struct ioc_gq *iocg = container_of(timer, struct ioc_gq, delay_timer);
1250 struct ioc_now now;
1251 unsigned long flags;
1252
1253 spin_lock_irqsave(&iocg->waitq.lock, flags);
1254 ioc_now(iocg->ioc, &now);
1255 iocg_kick_delay(iocg, &now);
1256 spin_unlock_irqrestore(&iocg->waitq.lock, flags);
1257
1258 return HRTIMER_NORESTART;
1259}
1260
Tejun Heoc421a3e2020-09-01 14:52:51 -04001261static void iocg_incur_debt(struct ioc_gq *iocg, u64 abs_cost,
1262 struct ioc_now *now)
1263{
1264 struct iocg_pcpu_stat *gcs;
1265
1266 lockdep_assert_held(&iocg->ioc->lock);
1267 lockdep_assert_held(&iocg->waitq.lock);
1268 WARN_ON_ONCE(list_empty(&iocg->active_list));
1269
1270 /*
1271 * Once in debt, debt handling owns inuse. @iocg stays at the minimum
1272 * inuse donating all of it share to others until its debt is paid off.
1273 */
1274 if (!iocg->abs_vdebt && abs_cost)
1275 propagate_weights(iocg, iocg->active, 0, false, now);
1276
1277 iocg->abs_vdebt += abs_cost;
1278
1279 gcs = get_cpu_ptr(iocg->pcpu_stat);
1280 local64_add(abs_cost, &gcs->abs_vusage);
1281 put_cpu_ptr(gcs);
1282}
1283
1284static void iocg_pay_debt(struct ioc_gq *iocg, u64 abs_vpay,
1285 struct ioc_now *now)
1286{
1287 lockdep_assert_held(&iocg->ioc->lock);
1288 lockdep_assert_held(&iocg->waitq.lock);
1289
1290 /* make sure that nobody messed with @iocg */
1291 WARN_ON_ONCE(list_empty(&iocg->active_list));
1292 WARN_ON_ONCE(iocg->inuse > 1);
1293
1294 iocg->abs_vdebt -= min(abs_vpay, iocg->abs_vdebt);
1295
1296 /* if debt is paid in full, restore inuse */
1297 if (!iocg->abs_vdebt)
1298 propagate_weights(iocg, iocg->active, iocg->last_inuse,
1299 false, now);
1300}
1301
Tejun Heo7caa4712019-08-28 15:05:58 -07001302static int iocg_wake_fn(struct wait_queue_entry *wq_entry, unsigned mode,
1303 int flags, void *key)
1304{
1305 struct iocg_wait *wait = container_of(wq_entry, struct iocg_wait, wait);
1306 struct iocg_wake_ctx *ctx = (struct iocg_wake_ctx *)key;
1307 u64 cost = abs_cost_to_cost(wait->abs_cost, ctx->hw_inuse);
1308
1309 ctx->vbudget -= cost;
1310
1311 if (ctx->vbudget < 0)
1312 return -1;
1313
Tejun Heo97eb1972020-09-01 14:52:43 -04001314 iocg_commit_bio(ctx->iocg, wait->bio, wait->abs_cost, cost);
Tejun Heo7caa4712019-08-28 15:05:58 -07001315
1316 /*
1317 * autoremove_wake_function() removes the wait entry only when it
1318 * actually changed the task state. We want the wait always
1319 * removed. Remove explicitly and use default_wake_function().
1320 */
1321 list_del_init(&wq_entry->entry);
1322 wait->committed = true;
1323
1324 default_wake_function(wq_entry, mode, flags, key);
1325 return 0;
1326}
1327
Tejun Heoda437b92020-09-01 14:52:42 -04001328/*
1329 * Calculate the accumulated budget, pay debt if @pay_debt and wake up waiters
1330 * accordingly. When @pay_debt is %true, the caller must be holding ioc->lock in
1331 * addition to iocg->waitq.lock.
1332 */
1333static void iocg_kick_waitq(struct ioc_gq *iocg, bool pay_debt,
1334 struct ioc_now *now)
Tejun Heo7caa4712019-08-28 15:05:58 -07001335{
1336 struct ioc *ioc = iocg->ioc;
1337 struct iocg_wake_ctx ctx = { .iocg = iocg };
Tejun Heoda437b92020-09-01 14:52:42 -04001338 u64 vshortage, expires, oexpires;
Tejun Heo36a52482019-09-04 12:45:52 -07001339 s64 vbudget;
Tejun Heoc421a3e2020-09-01 14:52:51 -04001340 u32 hwa;
Tejun Heo7caa4712019-08-28 15:05:58 -07001341
1342 lockdep_assert_held(&iocg->waitq.lock);
1343
Tejun Heoc421a3e2020-09-01 14:52:51 -04001344 current_hweight(iocg, &hwa, NULL);
Tejun Heo36a52482019-09-04 12:45:52 -07001345 vbudget = now->vnow - atomic64_read(&iocg->vtime);
1346
1347 /* pay off debt */
Tejun Heoda437b92020-09-01 14:52:42 -04001348 if (pay_debt && iocg->abs_vdebt && vbudget > 0) {
Tejun Heoc421a3e2020-09-01 14:52:51 -04001349 u64 abs_vbudget = cost_to_abs_cost(vbudget, hwa);
1350 u64 abs_vpay = min_t(u64, abs_vbudget, iocg->abs_vdebt);
1351 u64 vpay = abs_cost_to_cost(abs_vpay, hwa);
Tejun Heo36a52482019-09-04 12:45:52 -07001352
Tejun Heoda437b92020-09-01 14:52:42 -04001353 lockdep_assert_held(&ioc->lock);
1354
Tejun Heoc421a3e2020-09-01 14:52:51 -04001355 atomic64_add(vpay, &iocg->vtime);
1356 atomic64_add(vpay, &iocg->done_vtime);
1357 iocg_pay_debt(iocg, abs_vpay, now);
1358 vbudget -= vpay;
Tejun Heo7b84b492020-09-01 14:52:37 -04001359
1360 iocg_kick_delay(iocg, now);
Tejun Heo36a52482019-09-04 12:45:52 -07001361 }
1362
Tejun Heo7caa4712019-08-28 15:05:58 -07001363 /*
Tejun Heoda437b92020-09-01 14:52:42 -04001364 * Debt can still be outstanding if we haven't paid all yet or the
1365 * caller raced and called without @pay_debt. Shouldn't wake up waiters
1366 * under debt. Make sure @vbudget reflects the outstanding amount and is
1367 * not positive.
1368 */
1369 if (iocg->abs_vdebt) {
Tejun Heoc421a3e2020-09-01 14:52:51 -04001370 s64 vdebt = abs_cost_to_cost(iocg->abs_vdebt, hwa);
Tejun Heoda437b92020-09-01 14:52:42 -04001371 vbudget = min_t(s64, 0, vbudget - vdebt);
1372 }
1373
1374 /*
Tejun Heoc421a3e2020-09-01 14:52:51 -04001375 * Wake up the ones which are due and see how much vtime we'll need for
1376 * the next one. As paying off debt restores hw_inuse, it must be read
1377 * after the above debt payment.
Tejun Heo7caa4712019-08-28 15:05:58 -07001378 */
Tejun Heoda437b92020-09-01 14:52:42 -04001379 ctx.vbudget = vbudget;
Tejun Heoc421a3e2020-09-01 14:52:51 -04001380 current_hweight(iocg, NULL, &ctx.hw_inuse);
1381
Tejun Heo7caa4712019-08-28 15:05:58 -07001382 __wake_up_locked_key(&iocg->waitq, TASK_NORMAL, &ctx);
Tejun Heoc421a3e2020-09-01 14:52:51 -04001383
Tejun Heo7caa4712019-08-28 15:05:58 -07001384 if (!waitqueue_active(&iocg->waitq))
1385 return;
1386 if (WARN_ON_ONCE(ctx.vbudget >= 0))
1387 return;
1388
Tejun Heo7ca5b2e2020-09-01 14:52:41 -04001389 /* determine next wakeup, add a timer margin to guarantee chunking */
Tejun Heo7caa4712019-08-28 15:05:58 -07001390 vshortage = -ctx.vbudget;
1391 expires = now->now_ns +
1392 DIV64_U64_ROUND_UP(vshortage, now->vrate) * NSEC_PER_USEC;
Tejun Heo7ca5b2e2020-09-01 14:52:41 -04001393 expires += ioc->timer_slack_ns;
Tejun Heo7caa4712019-08-28 15:05:58 -07001394
1395 /* if already active and close enough, don't bother */
1396 oexpires = ktime_to_ns(hrtimer_get_softexpires(&iocg->waitq_timer));
1397 if (hrtimer_is_queued(&iocg->waitq_timer) &&
Tejun Heo7ca5b2e2020-09-01 14:52:41 -04001398 abs(oexpires - expires) <= ioc->timer_slack_ns)
Tejun Heo7caa4712019-08-28 15:05:58 -07001399 return;
1400
1401 hrtimer_start_range_ns(&iocg->waitq_timer, ns_to_ktime(expires),
Tejun Heo7ca5b2e2020-09-01 14:52:41 -04001402 ioc->timer_slack_ns, HRTIMER_MODE_ABS);
Tejun Heo7caa4712019-08-28 15:05:58 -07001403}
1404
1405static enum hrtimer_restart iocg_waitq_timer_fn(struct hrtimer *timer)
1406{
1407 struct ioc_gq *iocg = container_of(timer, struct ioc_gq, waitq_timer);
Tejun Heoda437b92020-09-01 14:52:42 -04001408 bool pay_debt = READ_ONCE(iocg->abs_vdebt);
Tejun Heo7caa4712019-08-28 15:05:58 -07001409 struct ioc_now now;
1410 unsigned long flags;
1411
1412 ioc_now(iocg->ioc, &now);
1413
Tejun Heoda437b92020-09-01 14:52:42 -04001414 iocg_lock(iocg, pay_debt, &flags);
1415 iocg_kick_waitq(iocg, pay_debt, &now);
1416 iocg_unlock(iocg, pay_debt, &flags);
Tejun Heo7caa4712019-08-28 15:05:58 -07001417
1418 return HRTIMER_NORESTART;
1419}
1420
Tejun Heo7caa4712019-08-28 15:05:58 -07001421static void ioc_lat_stat(struct ioc *ioc, u32 *missed_ppm_ar, u32 *rq_wait_pct_p)
1422{
1423 u32 nr_met[2] = { };
1424 u32 nr_missed[2] = { };
1425 u64 rq_wait_ns = 0;
1426 int cpu, rw;
1427
1428 for_each_online_cpu(cpu) {
1429 struct ioc_pcpu_stat *stat = per_cpu_ptr(ioc->pcpu_stat, cpu);
1430 u64 this_rq_wait_ns;
1431
1432 for (rw = READ; rw <= WRITE; rw++) {
Tejun Heo5e124f72020-09-01 14:52:33 -04001433 u32 this_met = local_read(&stat->missed[rw].nr_met);
1434 u32 this_missed = local_read(&stat->missed[rw].nr_missed);
Tejun Heo7caa4712019-08-28 15:05:58 -07001435
1436 nr_met[rw] += this_met - stat->missed[rw].last_met;
1437 nr_missed[rw] += this_missed - stat->missed[rw].last_missed;
1438 stat->missed[rw].last_met = this_met;
1439 stat->missed[rw].last_missed = this_missed;
1440 }
1441
Tejun Heo5e124f72020-09-01 14:52:33 -04001442 this_rq_wait_ns = local64_read(&stat->rq_wait_ns);
Tejun Heo7caa4712019-08-28 15:05:58 -07001443 rq_wait_ns += this_rq_wait_ns - stat->last_rq_wait_ns;
1444 stat->last_rq_wait_ns = this_rq_wait_ns;
1445 }
1446
1447 for (rw = READ; rw <= WRITE; rw++) {
1448 if (nr_met[rw] + nr_missed[rw])
1449 missed_ppm_ar[rw] =
1450 DIV64_U64_ROUND_UP((u64)nr_missed[rw] * MILLION,
1451 nr_met[rw] + nr_missed[rw]);
1452 else
1453 missed_ppm_ar[rw] = 0;
1454 }
1455
1456 *rq_wait_pct_p = div64_u64(rq_wait_ns * 100,
1457 ioc->period_us * NSEC_PER_USEC);
1458}
1459
1460/* was iocg idle this period? */
1461static bool iocg_is_idle(struct ioc_gq *iocg)
1462{
1463 struct ioc *ioc = iocg->ioc;
1464
1465 /* did something get issued this period? */
1466 if (atomic64_read(&iocg->active_period) ==
1467 atomic64_read(&ioc->cur_period))
1468 return false;
1469
1470 /* is something in flight? */
Tejun Heodcd65892020-03-10 13:07:46 -04001471 if (atomic64_read(&iocg->done_vtime) != atomic64_read(&iocg->vtime))
Tejun Heo7caa4712019-08-28 15:05:58 -07001472 return false;
1473
1474 return true;
1475}
1476
Tejun Heo97eb1972020-09-01 14:52:43 -04001477/*
1478 * Call this function on the target leaf @iocg's to build pre-order traversal
1479 * list of all the ancestors in @inner_walk. The inner nodes are linked through
1480 * ->walk_list and the caller is responsible for dissolving the list after use.
1481 */
1482static void iocg_build_inner_walk(struct ioc_gq *iocg,
1483 struct list_head *inner_walk)
1484{
1485 int lvl;
1486
1487 WARN_ON_ONCE(!list_empty(&iocg->walk_list));
1488
1489 /* find the first ancestor which hasn't been visited yet */
1490 for (lvl = iocg->level - 1; lvl >= 0; lvl--) {
1491 if (!list_empty(&iocg->ancestors[lvl]->walk_list))
1492 break;
1493 }
1494
1495 /* walk down and visit the inner nodes to get pre-order traversal */
1496 while (++lvl <= iocg->level - 1) {
1497 struct ioc_gq *inner = iocg->ancestors[lvl];
1498
1499 /* record traversal order */
1500 list_add_tail(&inner->walk_list, inner_walk);
1501 }
1502}
1503
1504/* collect per-cpu counters and propagate the deltas to the parent */
1505static void iocg_flush_stat_one(struct ioc_gq *iocg, struct ioc_now *now)
1506{
1507 struct iocg_stat new_stat;
1508 u64 abs_vusage = 0;
1509 u64 vusage_delta;
1510 int cpu;
1511
1512 lockdep_assert_held(&iocg->ioc->lock);
1513
1514 /* collect per-cpu counters */
1515 for_each_possible_cpu(cpu) {
1516 abs_vusage += local64_read(
1517 per_cpu_ptr(&iocg->pcpu_stat->abs_vusage, cpu));
1518 }
1519 vusage_delta = abs_vusage - iocg->last_stat_abs_vusage;
1520 iocg->last_stat_abs_vusage = abs_vusage;
1521
Tejun Heo1aa50d02020-09-01 14:52:44 -04001522 iocg->usage_delta_us = div64_u64(vusage_delta, now->vrate);
1523 iocg->local_stat.usage_us += iocg->usage_delta_us;
Tejun Heo97eb1972020-09-01 14:52:43 -04001524
1525 new_stat.usage_us =
1526 iocg->local_stat.usage_us + iocg->desc_stat.usage_us;
1527
1528 /* propagate the deltas to the parent */
1529 if (iocg->level > 0) {
1530 struct iocg_stat *parent_stat =
1531 &iocg->ancestors[iocg->level - 1]->desc_stat;
1532
1533 parent_stat->usage_us +=
1534 new_stat.usage_us - iocg->last_stat.usage_us;
1535 }
1536
1537 iocg->last_stat = new_stat;
1538}
1539
1540/* get stat counters ready for reading on all active iocgs */
1541static void iocg_flush_stat(struct list_head *target_iocgs, struct ioc_now *now)
1542{
1543 LIST_HEAD(inner_walk);
1544 struct ioc_gq *iocg, *tiocg;
1545
1546 /* flush leaves and build inner node walk list */
1547 list_for_each_entry(iocg, target_iocgs, active_list) {
1548 iocg_flush_stat_one(iocg, now);
1549 iocg_build_inner_walk(iocg, &inner_walk);
1550 }
1551
1552 /* keep flushing upwards by walking the inner list backwards */
1553 list_for_each_entry_safe_reverse(iocg, tiocg, &inner_walk, walk_list) {
1554 iocg_flush_stat_one(iocg, now);
1555 list_del_init(&iocg->walk_list);
1556 }
1557}
1558
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001559/*
1560 * Determine what @iocg's hweight_inuse should be after donating unused
1561 * capacity. @hwm is the upper bound and used to signal no donation. This
1562 * function also throws away @iocg's excess budget.
1563 */
1564static u32 hweight_after_donation(struct ioc_gq *iocg, u32 hwm, u32 usage,
1565 struct ioc_now *now)
Tejun Heo7caa4712019-08-28 15:05:58 -07001566{
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001567 struct ioc *ioc = iocg->ioc;
1568 u64 vtime = atomic64_read(&iocg->vtime);
Tejun Heof1de2432020-09-01 14:52:49 -04001569 s64 excess, delta, target, new_hwi;
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001570
Tejun Heoc421a3e2020-09-01 14:52:51 -04001571 /* debt handling owns inuse for debtors */
1572 if (iocg->abs_vdebt)
1573 return 1;
1574
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001575 /* see whether minimum margin requirement is met */
1576 if (waitqueue_active(&iocg->waitq) ||
1577 time_after64(vtime, now->vnow - ioc->margins.min))
1578 return hwm;
1579
1580 /* throw away excess above max */
1581 excess = now->vnow - vtime - ioc->margins.max;
1582 if (excess > 0) {
1583 atomic64_add(excess, &iocg->vtime);
1584 atomic64_add(excess, &iocg->done_vtime);
1585 vtime += excess;
1586 }
1587
Tejun Heof1de2432020-09-01 14:52:49 -04001588 /*
1589 * Let's say the distance between iocg's and device's vtimes as a
1590 * fraction of period duration is delta. Assuming that the iocg will
1591 * consume the usage determined above, we want to determine new_hwi so
1592 * that delta equals MARGIN_TARGET at the end of the next period.
1593 *
1594 * We need to execute usage worth of IOs while spending the sum of the
1595 * new budget (1 - MARGIN_TARGET) and the leftover from the last period
1596 * (delta):
1597 *
1598 * usage = (1 - MARGIN_TARGET + delta) * new_hwi
1599 *
1600 * Therefore, the new_hwi is:
1601 *
1602 * new_hwi = usage / (1 - MARGIN_TARGET + delta)
1603 */
1604 delta = div64_s64(WEIGHT_ONE * (now->vnow - vtime),
1605 now->vnow - ioc->period_at_vtime);
1606 target = WEIGHT_ONE * MARGIN_TARGET_PCT / 100;
1607 new_hwi = div64_s64(WEIGHT_ONE * usage, WEIGHT_ONE - target + delta);
Tejun Heo7caa4712019-08-28 15:05:58 -07001608
Tejun Heof1de2432020-09-01 14:52:49 -04001609 return clamp_t(s64, new_hwi, 1, hwm);
Tejun Heo7caa4712019-08-28 15:05:58 -07001610}
1611
Tejun Heoe08d02a2020-09-01 14:52:48 -04001612/*
1613 * For work-conservation, an iocg which isn't using all of its share should
1614 * donate the leftover to other iocgs. There are two ways to achieve this - 1.
1615 * bumping up vrate accordingly 2. lowering the donating iocg's inuse weight.
1616 *
1617 * #1 is mathematically simpler but has the drawback of requiring synchronous
1618 * global hweight_inuse updates when idle iocg's get activated or inuse weights
1619 * change due to donation snapbacks as it has the possibility of grossly
1620 * overshooting what's allowed by the model and vrate.
1621 *
1622 * #2 is inherently safe with local operations. The donating iocg can easily
1623 * snap back to higher weights when needed without worrying about impacts on
1624 * other nodes as the impacts will be inherently correct. This also makes idle
1625 * iocg activations safe. The only effect activations have is decreasing
1626 * hweight_inuse of others, the right solution to which is for those iocgs to
1627 * snap back to higher weights.
1628 *
1629 * So, we go with #2. The challenge is calculating how each donating iocg's
1630 * inuse should be adjusted to achieve the target donation amounts. This is done
1631 * using Andy's method described in the following pdf.
1632 *
1633 * https://drive.google.com/file/d/1PsJwxPFtjUnwOY1QJ5AeICCcsL7BM3bo
1634 *
1635 * Given the weights and target after-donation hweight_inuse values, Andy's
1636 * method determines how the proportional distribution should look like at each
1637 * sibling level to maintain the relative relationship between all non-donating
1638 * pairs. To roughly summarize, it divides the tree into donating and
1639 * non-donating parts, calculates global donation rate which is used to
1640 * determine the target hweight_inuse for each node, and then derives per-level
1641 * proportions.
1642 *
1643 * The following pdf shows that global distribution calculated this way can be
1644 * achieved by scaling inuse weights of donating leaves and propagating the
1645 * adjustments upwards proportionally.
1646 *
1647 * https://drive.google.com/file/d/1vONz1-fzVO7oY5DXXsLjSxEtYYQbOvsE
1648 *
1649 * Combining the above two, we can determine how each leaf iocg's inuse should
1650 * be adjusted to achieve the target donation.
1651 *
1652 * https://drive.google.com/file/d/1WcrltBOSPN0qXVdBgnKm4mdp9FhuEFQN
1653 *
1654 * The inline comments use symbols from the last pdf.
1655 *
1656 * b is the sum of the absolute budgets in the subtree. 1 for the root node.
1657 * f is the sum of the absolute budgets of non-donating nodes in the subtree.
1658 * t is the sum of the absolute budgets of donating nodes in the subtree.
1659 * w is the weight of the node. w = w_f + w_t
1660 * w_f is the non-donating portion of w. w_f = w * f / b
1661 * w_b is the donating portion of w. w_t = w * t / b
1662 * s is the sum of all sibling weights. s = Sum(w) for siblings
1663 * s_f and s_t are the non-donating and donating portions of s.
1664 *
1665 * Subscript p denotes the parent's counterpart and ' the adjusted value - e.g.
1666 * w_pt is the donating portion of the parent's weight and w'_pt the same value
1667 * after adjustments. Subscript r denotes the root node's values.
1668 */
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001669static void transfer_surpluses(struct list_head *surpluses, struct ioc_now *now)
1670{
Tejun Heoe08d02a2020-09-01 14:52:48 -04001671 LIST_HEAD(over_hwa);
1672 LIST_HEAD(inner_walk);
1673 struct ioc_gq *iocg, *tiocg, *root_iocg;
1674 u32 after_sum, over_sum, over_target, gamma;
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001675
Tejun Heoe08d02a2020-09-01 14:52:48 -04001676 /*
1677 * It's pretty unlikely but possible for the total sum of
1678 * hweight_after_donation's to be higher than WEIGHT_ONE, which will
1679 * confuse the following calculations. If such condition is detected,
1680 * scale down everyone over its full share equally to keep the sum below
1681 * WEIGHT_ONE.
1682 */
1683 after_sum = 0;
1684 over_sum = 0;
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001685 list_for_each_entry(iocg, surpluses, surplus_list) {
Tejun Heoe08d02a2020-09-01 14:52:48 -04001686 u32 hwa;
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001687
Tejun Heoe08d02a2020-09-01 14:52:48 -04001688 current_hweight(iocg, &hwa, NULL);
1689 after_sum += iocg->hweight_after_donation;
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001690
Tejun Heoe08d02a2020-09-01 14:52:48 -04001691 if (iocg->hweight_after_donation > hwa) {
1692 over_sum += iocg->hweight_after_donation;
1693 list_add(&iocg->walk_list, &over_hwa);
1694 }
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001695 }
Tejun Heoe08d02a2020-09-01 14:52:48 -04001696
1697 if (after_sum >= WEIGHT_ONE) {
1698 /*
1699 * The delta should be deducted from the over_sum, calculate
1700 * target over_sum value.
1701 */
1702 u32 over_delta = after_sum - (WEIGHT_ONE - 1);
1703 WARN_ON_ONCE(over_sum <= over_delta);
1704 over_target = over_sum - over_delta;
1705 } else {
1706 over_target = 0;
1707 }
1708
1709 list_for_each_entry_safe(iocg, tiocg, &over_hwa, walk_list) {
1710 if (over_target)
1711 iocg->hweight_after_donation =
1712 div_u64((u64)iocg->hweight_after_donation *
1713 over_target, over_sum);
1714 list_del_init(&iocg->walk_list);
1715 }
1716
1717 /*
1718 * Build pre-order inner node walk list and prepare for donation
1719 * adjustment calculations.
1720 */
1721 list_for_each_entry(iocg, surpluses, surplus_list) {
1722 iocg_build_inner_walk(iocg, &inner_walk);
1723 }
1724
1725 root_iocg = list_first_entry(&inner_walk, struct ioc_gq, walk_list);
1726 WARN_ON_ONCE(root_iocg->level > 0);
1727
1728 list_for_each_entry(iocg, &inner_walk, walk_list) {
1729 iocg->child_adjusted_sum = 0;
1730 iocg->hweight_donating = 0;
1731 iocg->hweight_after_donation = 0;
1732 }
1733
1734 /*
1735 * Propagate the donating budget (b_t) and after donation budget (b'_t)
1736 * up the hierarchy.
1737 */
1738 list_for_each_entry(iocg, surpluses, surplus_list) {
1739 struct ioc_gq *parent = iocg->ancestors[iocg->level - 1];
1740
1741 parent->hweight_donating += iocg->hweight_donating;
1742 parent->hweight_after_donation += iocg->hweight_after_donation;
1743 }
1744
1745 list_for_each_entry_reverse(iocg, &inner_walk, walk_list) {
1746 if (iocg->level > 0) {
1747 struct ioc_gq *parent = iocg->ancestors[iocg->level - 1];
1748
1749 parent->hweight_donating += iocg->hweight_donating;
1750 parent->hweight_after_donation += iocg->hweight_after_donation;
1751 }
1752 }
1753
1754 /*
1755 * Calculate inner hwa's (b) and make sure the donation values are
1756 * within the accepted ranges as we're doing low res calculations with
1757 * roundups.
1758 */
1759 list_for_each_entry(iocg, &inner_walk, walk_list) {
1760 if (iocg->level) {
1761 struct ioc_gq *parent = iocg->ancestors[iocg->level - 1];
1762
1763 iocg->hweight_active = DIV64_U64_ROUND_UP(
1764 (u64)parent->hweight_active * iocg->active,
1765 parent->child_active_sum);
1766
1767 }
1768
1769 iocg->hweight_donating = min(iocg->hweight_donating,
1770 iocg->hweight_active);
1771 iocg->hweight_after_donation = min(iocg->hweight_after_donation,
1772 iocg->hweight_donating - 1);
1773 if (WARN_ON_ONCE(iocg->hweight_active <= 1 ||
1774 iocg->hweight_donating <= 1 ||
1775 iocg->hweight_after_donation == 0)) {
1776 pr_warn("iocg: invalid donation weights in ");
1777 pr_cont_cgroup_path(iocg_to_blkg(iocg)->blkcg->css.cgroup);
1778 pr_cont(": active=%u donating=%u after=%u\n",
1779 iocg->hweight_active, iocg->hweight_donating,
1780 iocg->hweight_after_donation);
1781 }
1782 }
1783
1784 /*
1785 * Calculate the global donation rate (gamma) - the rate to adjust
1786 * non-donating budgets by. No need to use 64bit multiplication here as
1787 * the first operand is guaranteed to be smaller than WEIGHT_ONE
1788 * (1<<16).
1789 *
1790 * gamma = (1 - t_r') / (1 - t_r)
1791 */
1792 gamma = DIV_ROUND_UP(
1793 (WEIGHT_ONE - root_iocg->hweight_after_donation) * WEIGHT_ONE,
1794 WEIGHT_ONE - root_iocg->hweight_donating);
1795
1796 /*
1797 * Calculate adjusted hwi, child_adjusted_sum and inuse for the inner
1798 * nodes.
1799 */
1800 list_for_each_entry(iocg, &inner_walk, walk_list) {
1801 struct ioc_gq *parent;
1802 u32 inuse, wpt, wptp;
1803 u64 st, sf;
1804
1805 if (iocg->level == 0) {
1806 /* adjusted weight sum for 1st level: s' = s * b_pf / b'_pf */
1807 iocg->child_adjusted_sum = DIV64_U64_ROUND_UP(
1808 iocg->child_active_sum * (WEIGHT_ONE - iocg->hweight_donating),
1809 WEIGHT_ONE - iocg->hweight_after_donation);
1810 continue;
1811 }
1812
1813 parent = iocg->ancestors[iocg->level - 1];
1814
1815 /* b' = gamma * b_f + b_t' */
1816 iocg->hweight_inuse = DIV64_U64_ROUND_UP(
1817 (u64)gamma * (iocg->hweight_active - iocg->hweight_donating),
1818 WEIGHT_ONE) + iocg->hweight_after_donation;
1819
1820 /* w' = s' * b' / b'_p */
1821 inuse = DIV64_U64_ROUND_UP(
1822 (u64)parent->child_adjusted_sum * iocg->hweight_inuse,
1823 parent->hweight_inuse);
1824
1825 /* adjusted weight sum for children: s' = s_f + s_t * w'_pt / w_pt */
1826 st = DIV64_U64_ROUND_UP(
1827 iocg->child_active_sum * iocg->hweight_donating,
1828 iocg->hweight_active);
1829 sf = iocg->child_active_sum - st;
1830 wpt = DIV64_U64_ROUND_UP(
1831 (u64)iocg->active * iocg->hweight_donating,
1832 iocg->hweight_active);
1833 wptp = DIV64_U64_ROUND_UP(
1834 (u64)inuse * iocg->hweight_after_donation,
1835 iocg->hweight_inuse);
1836
1837 iocg->child_adjusted_sum = sf + DIV64_U64_ROUND_UP(st * wptp, wpt);
1838 }
1839
1840 /*
1841 * All inner nodes now have ->hweight_inuse and ->child_adjusted_sum and
1842 * we can finally determine leaf adjustments.
1843 */
1844 list_for_each_entry(iocg, surpluses, surplus_list) {
1845 struct ioc_gq *parent = iocg->ancestors[iocg->level - 1];
1846 u32 inuse;
1847
Tejun Heoc421a3e2020-09-01 14:52:51 -04001848 /*
1849 * In-debt iocgs participated in the donation calculation with
1850 * the minimum target hweight_inuse. Configuring inuse
1851 * accordingly would work fine but debt handling expects
1852 * @iocg->inuse stay at the minimum and we don't wanna
1853 * interfere.
1854 */
1855 if (iocg->abs_vdebt) {
1856 WARN_ON_ONCE(iocg->inuse > 1);
1857 continue;
1858 }
1859
Tejun Heoe08d02a2020-09-01 14:52:48 -04001860 /* w' = s' * b' / b'_p, note that b' == b'_t for donating leaves */
1861 inuse = DIV64_U64_ROUND_UP(
1862 parent->child_adjusted_sum * iocg->hweight_after_donation,
1863 parent->hweight_inuse);
Tejun Heob0853ab2020-09-01 14:52:50 -04001864 __propagate_weights(iocg, iocg->active, inuse, true, now);
Tejun Heoe08d02a2020-09-01 14:52:48 -04001865 }
1866
1867 /* walk list should be dissolved after use */
1868 list_for_each_entry_safe(iocg, tiocg, &inner_walk, walk_list)
1869 list_del_init(&iocg->walk_list);
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001870}
1871
Tejun Heo7caa4712019-08-28 15:05:58 -07001872static void ioc_timer_fn(struct timer_list *timer)
1873{
1874 struct ioc *ioc = container_of(timer, struct ioc, timer);
1875 struct ioc_gq *iocg, *tiocg;
1876 struct ioc_now now;
Tejun Heo8692d2d2020-09-01 14:52:45 -04001877 LIST_HEAD(surpluses);
Tejun Heo065655c2020-09-01 14:52:46 -04001878 int nr_shortages = 0, nr_lagging = 0;
Tejun Heo7caa4712019-08-28 15:05:58 -07001879 u32 ppm_rthr = MILLION - ioc->params.qos[QOS_RPPM];
1880 u32 ppm_wthr = MILLION - ioc->params.qos[QOS_WPPM];
1881 u32 missed_ppm[2], rq_wait_pct;
1882 u64 period_vtime;
Tejun Heof1de2432020-09-01 14:52:49 -04001883 int prev_busy_level;
Tejun Heo7caa4712019-08-28 15:05:58 -07001884
1885 /* how were the latencies during the period? */
1886 ioc_lat_stat(ioc, missed_ppm, &rq_wait_pct);
1887
1888 /* take care of active iocgs */
1889 spin_lock_irq(&ioc->lock);
1890
1891 ioc_now(ioc, &now);
1892
1893 period_vtime = now.vnow - ioc->period_at_vtime;
1894 if (WARN_ON_ONCE(!period_vtime)) {
1895 spin_unlock_irq(&ioc->lock);
1896 return;
1897 }
1898
Tejun Heo97eb1972020-09-01 14:52:43 -04001899 iocg_flush_stat(&ioc->active_iocgs, &now);
1900
Tejun Heo7caa4712019-08-28 15:05:58 -07001901 /*
1902 * Waiters determine the sleep durations based on the vrate they
1903 * saw at the time of sleep. If vrate has increased, some waiters
1904 * could be sleeping for too long. Wake up tardy waiters which
1905 * should have woken up in the last period and expire idle iocgs.
1906 */
1907 list_for_each_entry_safe(iocg, tiocg, &ioc->active_iocgs, active_list) {
Chengming Zhoud9012a52020-07-30 17:03:21 +08001908 if (!waitqueue_active(&iocg->waitq) && !iocg->abs_vdebt &&
Tejun Heo0b80f982020-05-04 19:27:54 -04001909 !iocg_is_idle(iocg))
Tejun Heo7caa4712019-08-28 15:05:58 -07001910 continue;
1911
1912 spin_lock(&iocg->waitq.lock);
1913
Tejun Heo0b80f982020-05-04 19:27:54 -04001914 if (waitqueue_active(&iocg->waitq) || iocg->abs_vdebt) {
Tejun Heo7caa4712019-08-28 15:05:58 -07001915 /* might be oversleeping vtime / hweight changes, kick */
Tejun Heoda437b92020-09-01 14:52:42 -04001916 iocg_kick_waitq(iocg, true, &now);
Tejun Heo7caa4712019-08-28 15:05:58 -07001917 } else if (iocg_is_idle(iocg)) {
1918 /* no waiter and idle, deactivate */
Tejun Heob0853ab2020-09-01 14:52:50 -04001919 __propagate_weights(iocg, 0, 0, false, &now);
Tejun Heo7caa4712019-08-28 15:05:58 -07001920 list_del_init(&iocg->active_list);
1921 }
1922
1923 spin_unlock(&iocg->waitq.lock);
1924 }
Tejun Heo00410f12020-09-01 14:52:34 -04001925 commit_weights(ioc);
Tejun Heo7caa4712019-08-28 15:05:58 -07001926
Tejun Heof1de2432020-09-01 14:52:49 -04001927 /* calc usage and see whether some weights need to be moved around */
Tejun Heo7caa4712019-08-28 15:05:58 -07001928 list_for_each_entry(iocg, &ioc->active_iocgs, active_list) {
Tejun Heof1de2432020-09-01 14:52:49 -04001929 u64 vdone, vtime, usage_us, usage_dur;
1930 u32 usage, hw_active, hw_inuse;
Tejun Heo7caa4712019-08-28 15:05:58 -07001931
1932 /*
1933 * Collect unused and wind vtime closer to vnow to prevent
1934 * iocgs from accumulating a large amount of budget.
1935 */
1936 vdone = atomic64_read(&iocg->done_vtime);
1937 vtime = atomic64_read(&iocg->vtime);
1938 current_hweight(iocg, &hw_active, &hw_inuse);
1939
1940 /*
1941 * Latency QoS detection doesn't account for IOs which are
1942 * in-flight for longer than a period. Detect them by
1943 * comparing vdone against period start. If lagging behind
1944 * IOs from past periods, don't increase vrate.
1945 */
Tejun Heo7cd806a2019-09-25 16:03:09 -07001946 if ((ppm_rthr != MILLION || ppm_wthr != MILLION) &&
1947 !atomic_read(&iocg_to_blkg(iocg)->use_delay) &&
Tejun Heo7caa4712019-08-28 15:05:58 -07001948 time_after64(vtime, vdone) &&
1949 time_after64(vtime, now.vnow -
1950 MAX_LAGGING_PERIODS * period_vtime) &&
1951 time_before64(vdone, now.vnow - period_vtime))
1952 nr_lagging++;
1953
Tejun Heo7caa4712019-08-28 15:05:58 -07001954 /*
Tejun Heof1de2432020-09-01 14:52:49 -04001955 * Determine absolute usage factoring in in-flight IOs to avoid
1956 * high-latency completions appearing as idle.
Tejun Heo7caa4712019-08-28 15:05:58 -07001957 */
Tejun Heo1aa50d02020-09-01 14:52:44 -04001958 usage_us = iocg->usage_delta_us;
Tejun Heof1de2432020-09-01 14:52:49 -04001959
Tejun Heo1aa50d02020-09-01 14:52:44 -04001960 if (vdone != vtime) {
1961 u64 inflight_us = DIV64_U64_ROUND_UP(
1962 cost_to_abs_cost(vtime - vdone, hw_inuse),
1963 now.vrate);
1964 usage_us = max(usage_us, inflight_us);
1965 }
Tejun Heo7caa4712019-08-28 15:05:58 -07001966
Tejun Heof1de2432020-09-01 14:52:49 -04001967 /* convert to hweight based usage ratio */
1968 if (time_after64(iocg->activated_at, ioc->period_at))
1969 usage_dur = max_t(u64, now.now - iocg->activated_at, 1);
1970 else
1971 usage_dur = max_t(u64, now.now - ioc->period_at, 1);
Tejun Heo1aa50d02020-09-01 14:52:44 -04001972
Tejun Heof1de2432020-09-01 14:52:49 -04001973 usage = clamp_t(u32,
1974 DIV64_U64_ROUND_UP(usage_us * WEIGHT_ONE,
1975 usage_dur),
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001976 1, WEIGHT_ONE);
Tejun Heo7caa4712019-08-28 15:05:58 -07001977
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001978 /* see whether there's surplus vtime */
1979 WARN_ON_ONCE(!list_empty(&iocg->surplus_list));
1980 if (hw_inuse < hw_active ||
1981 (!waitqueue_active(&iocg->waitq) &&
Tejun Heof1de2432020-09-01 14:52:49 -04001982 time_before64(vtime, now.vnow - ioc->margins.low))) {
Tejun Heoe08d02a2020-09-01 14:52:48 -04001983 u32 hwa, hwm, new_hwi;
Tejun Heo7caa4712019-08-28 15:05:58 -07001984
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001985 /*
1986 * Already donating or accumulated enough to start.
1987 * Determine the donation amount.
1988 */
Tejun Heoe08d02a2020-09-01 14:52:48 -04001989 current_hweight(iocg, &hwa, NULL);
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001990 hwm = current_hweight_max(iocg);
1991 new_hwi = hweight_after_donation(iocg, hwm, usage,
1992 &now);
1993 if (new_hwi < hwm) {
Tejun Heoe08d02a2020-09-01 14:52:48 -04001994 iocg->hweight_donating = hwa;
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001995 iocg->hweight_after_donation = new_hwi;
1996 list_add(&iocg->surplus_list, &surpluses);
1997 } else {
1998 __propagate_weights(iocg, iocg->active,
Tejun Heob0853ab2020-09-01 14:52:50 -04001999 iocg->active, true, &now);
Tejun Heo93f7d2d2020-09-01 14:52:47 -04002000 nr_shortages++;
2001 }
2002 } else {
2003 /* genuinely short on vtime */
2004 nr_shortages++;
Tejun Heo7caa4712019-08-28 15:05:58 -07002005 }
2006 }
Tejun Heo93f7d2d2020-09-01 14:52:47 -04002007
2008 if (!list_empty(&surpluses) && nr_shortages)
2009 transfer_surpluses(&surpluses, &now);
2010
Tejun Heo00410f12020-09-01 14:52:34 -04002011 commit_weights(ioc);
Tejun Heo7caa4712019-08-28 15:05:58 -07002012
Tejun Heo8692d2d2020-09-01 14:52:45 -04002013 /* surplus list should be dissolved after use */
2014 list_for_each_entry_safe(iocg, tiocg, &surpluses, surplus_list)
2015 list_del_init(&iocg->surplus_list);
2016
Tejun Heo7caa4712019-08-28 15:05:58 -07002017 /*
2018 * If q is getting clogged or we're missing too much, we're issuing
2019 * too much IO and should lower vtime rate. If we're not missing
2020 * and experiencing shortages but not surpluses, we're too stingy
2021 * and should increase vtime rate.
2022 */
Tejun Heo25d41e42019-09-25 16:02:07 -07002023 prev_busy_level = ioc->busy_level;
Tejun Heo7caa4712019-08-28 15:05:58 -07002024 if (rq_wait_pct > RQ_WAIT_BUSY_PCT ||
2025 missed_ppm[READ] > ppm_rthr ||
2026 missed_ppm[WRITE] > ppm_wthr) {
Tejun Heo81ca6272019-10-14 17:18:11 -07002027 /* clearly missing QoS targets, slow down vrate */
Tejun Heo7caa4712019-08-28 15:05:58 -07002028 ioc->busy_level = max(ioc->busy_level, 0);
2029 ioc->busy_level++;
Tejun Heo7cd806a2019-09-25 16:03:09 -07002030 } else if (rq_wait_pct <= RQ_WAIT_BUSY_PCT * UNBUSY_THR_PCT / 100 &&
Tejun Heo7caa4712019-08-28 15:05:58 -07002031 missed_ppm[READ] <= ppm_rthr * UNBUSY_THR_PCT / 100 &&
2032 missed_ppm[WRITE] <= ppm_wthr * UNBUSY_THR_PCT / 100) {
Tejun Heo81ca6272019-10-14 17:18:11 -07002033 /* QoS targets are being met with >25% margin */
2034 if (nr_shortages) {
2035 /*
2036 * We're throttling while the device has spare
2037 * capacity. If vrate was being slowed down, stop.
2038 */
Tejun Heo7cd806a2019-09-25 16:03:09 -07002039 ioc->busy_level = min(ioc->busy_level, 0);
Tejun Heo81ca6272019-10-14 17:18:11 -07002040
2041 /*
2042 * If there are IOs spanning multiple periods, wait
Tejun Heo065655c2020-09-01 14:52:46 -04002043 * them out before pushing the device harder.
Tejun Heo81ca6272019-10-14 17:18:11 -07002044 */
Tejun Heo065655c2020-09-01 14:52:46 -04002045 if (!nr_lagging)
Tejun Heo7cd806a2019-09-25 16:03:09 -07002046 ioc->busy_level--;
Tejun Heo81ca6272019-10-14 17:18:11 -07002047 } else {
2048 /*
2049 * Nobody is being throttled and the users aren't
2050 * issuing enough IOs to saturate the device. We
2051 * simply don't know how close the device is to
2052 * saturation. Coast.
2053 */
2054 ioc->busy_level = 0;
Tejun Heo7cd806a2019-09-25 16:03:09 -07002055 }
Tejun Heo7caa4712019-08-28 15:05:58 -07002056 } else {
Tejun Heo81ca6272019-10-14 17:18:11 -07002057 /* inside the hysterisis margin, we're good */
Tejun Heo7caa4712019-08-28 15:05:58 -07002058 ioc->busy_level = 0;
2059 }
2060
2061 ioc->busy_level = clamp(ioc->busy_level, -1000, 1000);
2062
Tejun Heo7cd806a2019-09-25 16:03:09 -07002063 if (ioc->busy_level > 0 || (ioc->busy_level < 0 && !nr_lagging)) {
Tejun Heo7caa4712019-08-28 15:05:58 -07002064 u64 vrate = atomic64_read(&ioc->vtime_rate);
2065 u64 vrate_min = ioc->vrate_min, vrate_max = ioc->vrate_max;
2066
2067 /* rq_wait signal is always reliable, ignore user vrate_min */
2068 if (rq_wait_pct > RQ_WAIT_BUSY_PCT)
2069 vrate_min = VRATE_MIN;
2070
2071 /*
2072 * If vrate is out of bounds, apply clamp gradually as the
2073 * bounds can change abruptly. Otherwise, apply busy_level
2074 * based adjustment.
2075 */
2076 if (vrate < vrate_min) {
2077 vrate = div64_u64(vrate * (100 + VRATE_CLAMP_ADJ_PCT),
2078 100);
2079 vrate = min(vrate, vrate_min);
2080 } else if (vrate > vrate_max) {
2081 vrate = div64_u64(vrate * (100 - VRATE_CLAMP_ADJ_PCT),
2082 100);
2083 vrate = max(vrate, vrate_max);
2084 } else {
2085 int idx = min_t(int, abs(ioc->busy_level),
2086 ARRAY_SIZE(vrate_adj_pct) - 1);
2087 u32 adj_pct = vrate_adj_pct[idx];
2088
2089 if (ioc->busy_level > 0)
2090 adj_pct = 100 - adj_pct;
2091 else
2092 adj_pct = 100 + adj_pct;
2093
2094 vrate = clamp(DIV64_U64_ROUND_UP(vrate * adj_pct, 100),
2095 vrate_min, vrate_max);
2096 }
2097
Waiman Longd6c8e942020-04-21 09:07:55 -04002098 trace_iocost_ioc_vrate_adj(ioc, vrate, missed_ppm, rq_wait_pct,
Tejun Heo065655c2020-09-01 14:52:46 -04002099 nr_lagging, nr_shortages);
Tejun Heo7caa4712019-08-28 15:05:58 -07002100
2101 atomic64_set(&ioc->vtime_rate, vrate);
Tejun Heo7ca5b2e2020-09-01 14:52:41 -04002102 ioc_refresh_margins(ioc);
Tejun Heo25d41e42019-09-25 16:02:07 -07002103 } else if (ioc->busy_level != prev_busy_level || nr_lagging) {
2104 trace_iocost_ioc_vrate_adj(ioc, atomic64_read(&ioc->vtime_rate),
Waiman Longd6c8e942020-04-21 09:07:55 -04002105 missed_ppm, rq_wait_pct, nr_lagging,
Tejun Heo065655c2020-09-01 14:52:46 -04002106 nr_shortages);
Tejun Heo7caa4712019-08-28 15:05:58 -07002107 }
2108
2109 ioc_refresh_params(ioc, false);
2110
2111 /*
2112 * This period is done. Move onto the next one. If nothing's
2113 * going on with the device, stop the timer.
2114 */
2115 atomic64_inc(&ioc->cur_period);
2116
2117 if (ioc->running != IOC_STOP) {
2118 if (!list_empty(&ioc->active_iocgs)) {
2119 ioc_start_period(ioc, &now);
2120 } else {
2121 ioc->busy_level = 0;
2122 ioc->running = IOC_IDLE;
2123 }
2124 }
2125
2126 spin_unlock_irq(&ioc->lock);
2127}
2128
Tejun Heob0853ab2020-09-01 14:52:50 -04002129static u64 adjust_inuse_and_calc_cost(struct ioc_gq *iocg, u64 vtime,
2130 u64 abs_cost, struct ioc_now *now)
2131{
2132 struct ioc *ioc = iocg->ioc;
2133 struct ioc_margins *margins = &ioc->margins;
2134 u32 adj_step = DIV_ROUND_UP(iocg->active * INUSE_ADJ_STEP_PCT, 100);
2135 u32 hwi;
2136 s64 margin;
2137 u64 cost, new_inuse;
2138
2139 current_hweight(iocg, NULL, &hwi);
2140 cost = abs_cost_to_cost(abs_cost, hwi);
2141 margin = now->vnow - vtime - cost;
2142
Tejun Heoc421a3e2020-09-01 14:52:51 -04002143 /* debt handling owns inuse for debtors */
2144 if (iocg->abs_vdebt)
2145 return cost;
2146
Tejun Heob0853ab2020-09-01 14:52:50 -04002147 /*
2148 * We only increase inuse during period and do so iff the margin has
2149 * deteriorated since the previous adjustment.
2150 */
2151 if (margin >= iocg->saved_margin || margin >= margins->low ||
2152 iocg->inuse == iocg->active)
2153 return cost;
2154
2155 spin_lock_irq(&ioc->lock);
2156
2157 /* we own inuse only when @iocg is in the normal active state */
Tejun Heoc421a3e2020-09-01 14:52:51 -04002158 if (iocg->abs_vdebt || list_empty(&iocg->active_list)) {
Tejun Heob0853ab2020-09-01 14:52:50 -04002159 spin_unlock_irq(&ioc->lock);
2160 return cost;
2161 }
2162
2163 /* bump up inuse till @abs_cost fits in the existing budget */
2164 new_inuse = iocg->inuse;
2165 do {
2166 new_inuse = new_inuse + adj_step;
2167 propagate_weights(iocg, iocg->active, new_inuse, true, now);
2168 current_hweight(iocg, NULL, &hwi);
2169 cost = abs_cost_to_cost(abs_cost, hwi);
2170 } while (time_after64(vtime + cost, now->vnow) &&
2171 iocg->inuse != iocg->active);
2172
2173 spin_unlock_irq(&ioc->lock);
2174 return cost;
2175}
2176
Tejun Heo7caa4712019-08-28 15:05:58 -07002177static void calc_vtime_cost_builtin(struct bio *bio, struct ioc_gq *iocg,
2178 bool is_merge, u64 *costp)
2179{
2180 struct ioc *ioc = iocg->ioc;
2181 u64 coef_seqio, coef_randio, coef_page;
2182 u64 pages = max_t(u64, bio_sectors(bio) >> IOC_SECT_TO_PAGE_SHIFT, 1);
2183 u64 seek_pages = 0;
2184 u64 cost = 0;
2185
2186 switch (bio_op(bio)) {
2187 case REQ_OP_READ:
2188 coef_seqio = ioc->params.lcoefs[LCOEF_RSEQIO];
2189 coef_randio = ioc->params.lcoefs[LCOEF_RRANDIO];
2190 coef_page = ioc->params.lcoefs[LCOEF_RPAGE];
2191 break;
2192 case REQ_OP_WRITE:
2193 coef_seqio = ioc->params.lcoefs[LCOEF_WSEQIO];
2194 coef_randio = ioc->params.lcoefs[LCOEF_WRANDIO];
2195 coef_page = ioc->params.lcoefs[LCOEF_WPAGE];
2196 break;
2197 default:
2198 goto out;
2199 }
2200
2201 if (iocg->cursor) {
2202 seek_pages = abs(bio->bi_iter.bi_sector - iocg->cursor);
2203 seek_pages >>= IOC_SECT_TO_PAGE_SHIFT;
2204 }
2205
2206 if (!is_merge) {
2207 if (seek_pages > LCOEF_RANDIO_PAGES) {
2208 cost += coef_randio;
2209 } else {
2210 cost += coef_seqio;
2211 }
2212 }
2213 cost += pages * coef_page;
2214out:
2215 *costp = cost;
2216}
2217
2218static u64 calc_vtime_cost(struct bio *bio, struct ioc_gq *iocg, bool is_merge)
2219{
2220 u64 cost;
2221
2222 calc_vtime_cost_builtin(bio, iocg, is_merge, &cost);
2223 return cost;
2224}
2225
Tejun Heocd006502020-04-13 12:27:56 -04002226static void calc_size_vtime_cost_builtin(struct request *rq, struct ioc *ioc,
2227 u64 *costp)
2228{
2229 unsigned int pages = blk_rq_stats_sectors(rq) >> IOC_SECT_TO_PAGE_SHIFT;
2230
2231 switch (req_op(rq)) {
2232 case REQ_OP_READ:
2233 *costp = pages * ioc->params.lcoefs[LCOEF_RPAGE];
2234 break;
2235 case REQ_OP_WRITE:
2236 *costp = pages * ioc->params.lcoefs[LCOEF_WPAGE];
2237 break;
2238 default:
2239 *costp = 0;
2240 }
2241}
2242
2243static u64 calc_size_vtime_cost(struct request *rq, struct ioc *ioc)
2244{
2245 u64 cost;
2246
2247 calc_size_vtime_cost_builtin(rq, ioc, &cost);
2248 return cost;
2249}
2250
Tejun Heo7caa4712019-08-28 15:05:58 -07002251static void ioc_rqos_throttle(struct rq_qos *rqos, struct bio *bio)
2252{
2253 struct blkcg_gq *blkg = bio->bi_blkg;
2254 struct ioc *ioc = rqos_to_ioc(rqos);
2255 struct ioc_gq *iocg = blkg_to_iocg(blkg);
2256 struct ioc_now now;
2257 struct iocg_wait wait;
Tejun Heo7caa4712019-08-28 15:05:58 -07002258 u64 abs_cost, cost, vtime;
Tejun Heoda437b92020-09-01 14:52:42 -04002259 bool use_debt, ioc_locked;
2260 unsigned long flags;
Tejun Heo7caa4712019-08-28 15:05:58 -07002261
2262 /* bypass IOs if disabled or for root cgroup */
2263 if (!ioc->enabled || !iocg->level)
2264 return;
2265
Tejun Heo7caa4712019-08-28 15:05:58 -07002266 /* calculate the absolute vtime cost */
2267 abs_cost = calc_vtime_cost(bio, iocg, false);
2268 if (!abs_cost)
2269 return;
2270
Tejun Heof1de2432020-09-01 14:52:49 -04002271 if (!iocg_activate(iocg, &now))
2272 return;
2273
Tejun Heo7caa4712019-08-28 15:05:58 -07002274 iocg->cursor = bio_end_sector(bio);
Tejun Heo7caa4712019-08-28 15:05:58 -07002275 vtime = atomic64_read(&iocg->vtime);
Tejun Heob0853ab2020-09-01 14:52:50 -04002276 cost = adjust_inuse_and_calc_cost(iocg, vtime, abs_cost, &now);
Tejun Heo7caa4712019-08-28 15:05:58 -07002277
2278 /*
2279 * If no one's waiting and within budget, issue right away. The
2280 * tests are racy but the races aren't systemic - we only miss once
2281 * in a while which is fine.
2282 */
Tejun Heo0b80f982020-05-04 19:27:54 -04002283 if (!waitqueue_active(&iocg->waitq) && !iocg->abs_vdebt &&
Tejun Heo7caa4712019-08-28 15:05:58 -07002284 time_before_eq64(vtime + cost, now.vnow)) {
Tejun Heo97eb1972020-09-01 14:52:43 -04002285 iocg_commit_bio(iocg, bio, abs_cost, cost);
Tejun Heo7caa4712019-08-28 15:05:58 -07002286 return;
2287 }
2288
Tejun Heo36a52482019-09-04 12:45:52 -07002289 /*
Tejun Heoda437b92020-09-01 14:52:42 -04002290 * We're over budget. This can be handled in two ways. IOs which may
2291 * cause priority inversions are punted to @ioc->aux_iocg and charged as
2292 * debt. Otherwise, the issuer is blocked on @iocg->waitq. Debt handling
2293 * requires @ioc->lock, waitq handling @iocg->waitq.lock. Determine
2294 * whether debt handling is needed and acquire locks accordingly.
Tejun Heo0b80f982020-05-04 19:27:54 -04002295 */
Tejun Heoda437b92020-09-01 14:52:42 -04002296 use_debt = bio_issue_as_root_blkg(bio) || fatal_signal_pending(current);
2297 ioc_locked = use_debt || READ_ONCE(iocg->abs_vdebt);
Tejun Heob0853ab2020-09-01 14:52:50 -04002298retry_lock:
Tejun Heoda437b92020-09-01 14:52:42 -04002299 iocg_lock(iocg, ioc_locked, &flags);
2300
2301 /*
2302 * @iocg must stay activated for debt and waitq handling. Deactivation
2303 * is synchronized against both ioc->lock and waitq.lock and we won't
2304 * get deactivated as long as we're waiting or has debt, so we're good
2305 * if we're activated here. In the unlikely cases that we aren't, just
2306 * issue the IO.
2307 */
Tejun Heo0b80f982020-05-04 19:27:54 -04002308 if (unlikely(list_empty(&iocg->active_list))) {
Tejun Heoda437b92020-09-01 14:52:42 -04002309 iocg_unlock(iocg, ioc_locked, &flags);
Tejun Heo97eb1972020-09-01 14:52:43 -04002310 iocg_commit_bio(iocg, bio, abs_cost, cost);
Tejun Heo0b80f982020-05-04 19:27:54 -04002311 return;
2312 }
2313
2314 /*
2315 * We're over budget. If @bio has to be issued regardless, remember
2316 * the abs_cost instead of advancing vtime. iocg_kick_waitq() will pay
2317 * off the debt before waking more IOs.
2318 *
Tejun Heo36a52482019-09-04 12:45:52 -07002319 * This way, the debt is continuously paid off each period with the
Tejun Heo0b80f982020-05-04 19:27:54 -04002320 * actual budget available to the cgroup. If we just wound vtime, we
2321 * would incorrectly use the current hw_inuse for the entire amount
2322 * which, for example, can lead to the cgroup staying blocked for a
2323 * long time even with substantially raised hw_inuse.
2324 *
2325 * An iocg with vdebt should stay online so that the timer can keep
2326 * deducting its vdebt and [de]activate use_delay mechanism
2327 * accordingly. We don't want to race against the timer trying to
2328 * clear them and leave @iocg inactive w/ dangling use_delay heavily
2329 * penalizing the cgroup and its descendants.
Tejun Heo36a52482019-09-04 12:45:52 -07002330 */
Tejun Heoda437b92020-09-01 14:52:42 -04002331 if (use_debt) {
Tejun Heoc421a3e2020-09-01 14:52:51 -04002332 iocg_incur_debt(iocg, abs_cost, &now);
Tejun Heo54c52e12020-04-13 12:27:55 -04002333 if (iocg_kick_delay(iocg, &now))
Tejun Heod7bd15a2019-12-16 13:34:00 -08002334 blkcg_schedule_throttle(rqos->q,
2335 (bio->bi_opf & REQ_SWAP) == REQ_SWAP);
Tejun Heoda437b92020-09-01 14:52:42 -04002336 iocg_unlock(iocg, ioc_locked, &flags);
Tejun Heo7caa4712019-08-28 15:05:58 -07002337 return;
2338 }
2339
Tejun Heob0853ab2020-09-01 14:52:50 -04002340 /* guarantee that iocgs w/ waiters have maximum inuse */
Tejun Heoc421a3e2020-09-01 14:52:51 -04002341 if (!iocg->abs_vdebt && iocg->inuse != iocg->active) {
Tejun Heob0853ab2020-09-01 14:52:50 -04002342 if (!ioc_locked) {
2343 iocg_unlock(iocg, false, &flags);
2344 ioc_locked = true;
2345 goto retry_lock;
2346 }
2347 propagate_weights(iocg, iocg->active, iocg->active, true,
2348 &now);
2349 }
2350
Tejun Heo7caa4712019-08-28 15:05:58 -07002351 /*
2352 * Append self to the waitq and schedule the wakeup timer if we're
2353 * the first waiter. The timer duration is calculated based on the
2354 * current vrate. vtime and hweight changes can make it too short
2355 * or too long. Each wait entry records the absolute cost it's
2356 * waiting for to allow re-evaluation using a custom wait entry.
2357 *
2358 * If too short, the timer simply reschedules itself. If too long,
2359 * the period timer will notice and trigger wakeups.
2360 *
2361 * All waiters are on iocg->waitq and the wait states are
2362 * synchronized using waitq.lock.
2363 */
Tejun Heo7caa4712019-08-28 15:05:58 -07002364 init_waitqueue_func_entry(&wait.wait, iocg_wake_fn);
2365 wait.wait.private = current;
2366 wait.bio = bio;
2367 wait.abs_cost = abs_cost;
2368 wait.committed = false; /* will be set true by waker */
2369
2370 __add_wait_queue_entry_tail(&iocg->waitq, &wait.wait);
Tejun Heoda437b92020-09-01 14:52:42 -04002371 iocg_kick_waitq(iocg, ioc_locked, &now);
Tejun Heo7caa4712019-08-28 15:05:58 -07002372
Tejun Heoda437b92020-09-01 14:52:42 -04002373 iocg_unlock(iocg, ioc_locked, &flags);
Tejun Heo7caa4712019-08-28 15:05:58 -07002374
2375 while (true) {
2376 set_current_state(TASK_UNINTERRUPTIBLE);
2377 if (wait.committed)
2378 break;
2379 io_schedule();
2380 }
2381
2382 /* waker already committed us, proceed */
2383 finish_wait(&iocg->waitq, &wait.wait);
2384}
2385
2386static void ioc_rqos_merge(struct rq_qos *rqos, struct request *rq,
2387 struct bio *bio)
2388{
2389 struct ioc_gq *iocg = blkg_to_iocg(bio->bi_blkg);
Tejun Heoe1518f62019-09-04 12:45:53 -07002390 struct ioc *ioc = iocg->ioc;
Tejun Heo7caa4712019-08-28 15:05:58 -07002391 sector_t bio_end = bio_end_sector(bio);
Tejun Heoe1518f62019-09-04 12:45:53 -07002392 struct ioc_now now;
Tejun Heob0853ab2020-09-01 14:52:50 -04002393 u64 vtime, abs_cost, cost;
Tejun Heo0b80f982020-05-04 19:27:54 -04002394 unsigned long flags;
Tejun Heo7caa4712019-08-28 15:05:58 -07002395
Tejun Heoe1518f62019-09-04 12:45:53 -07002396 /* bypass if disabled or for root cgroup */
2397 if (!ioc->enabled || !iocg->level)
Tejun Heo7caa4712019-08-28 15:05:58 -07002398 return;
2399
2400 abs_cost = calc_vtime_cost(bio, iocg, true);
2401 if (!abs_cost)
2402 return;
2403
Tejun Heoe1518f62019-09-04 12:45:53 -07002404 ioc_now(ioc, &now);
Tejun Heob0853ab2020-09-01 14:52:50 -04002405
2406 vtime = atomic64_read(&iocg->vtime);
2407 cost = adjust_inuse_and_calc_cost(iocg, vtime, abs_cost, &now);
Tejun Heoe1518f62019-09-04 12:45:53 -07002408
Tejun Heo7caa4712019-08-28 15:05:58 -07002409 /* update cursor if backmerging into the request at the cursor */
2410 if (blk_rq_pos(rq) < bio_end &&
2411 blk_rq_pos(rq) + blk_rq_sectors(rq) == iocg->cursor)
2412 iocg->cursor = bio_end;
2413
Tejun Heoe1518f62019-09-04 12:45:53 -07002414 /*
Tejun Heo0b80f982020-05-04 19:27:54 -04002415 * Charge if there's enough vtime budget and the existing request has
2416 * cost assigned.
Tejun Heoe1518f62019-09-04 12:45:53 -07002417 */
2418 if (rq->bio && rq->bio->bi_iocost_cost &&
Tejun Heo0b80f982020-05-04 19:27:54 -04002419 time_before_eq64(atomic64_read(&iocg->vtime) + cost, now.vnow)) {
Tejun Heo97eb1972020-09-01 14:52:43 -04002420 iocg_commit_bio(iocg, bio, abs_cost, cost);
Tejun Heo0b80f982020-05-04 19:27:54 -04002421 return;
2422 }
2423
2424 /*
2425 * Otherwise, account it as debt if @iocg is online, which it should
2426 * be for the vast majority of cases. See debt handling in
2427 * ioc_rqos_throttle() for details.
2428 */
Tejun Heoc421a3e2020-09-01 14:52:51 -04002429 spin_lock_irqsave(&ioc->lock, flags);
2430 spin_lock(&iocg->waitq.lock);
2431
Tejun Heo0b80f982020-05-04 19:27:54 -04002432 if (likely(!list_empty(&iocg->active_list))) {
Tejun Heoc421a3e2020-09-01 14:52:51 -04002433 iocg_incur_debt(iocg, abs_cost, &now);
2434 if (iocg_kick_delay(iocg, &now))
2435 blkcg_schedule_throttle(rqos->q,
2436 (bio->bi_opf & REQ_SWAP) == REQ_SWAP);
Tejun Heo0b80f982020-05-04 19:27:54 -04002437 } else {
Tejun Heo97eb1972020-09-01 14:52:43 -04002438 iocg_commit_bio(iocg, bio, abs_cost, cost);
Tejun Heo0b80f982020-05-04 19:27:54 -04002439 }
Tejun Heoc421a3e2020-09-01 14:52:51 -04002440
2441 spin_unlock(&iocg->waitq.lock);
2442 spin_unlock_irqrestore(&ioc->lock, flags);
Tejun Heo7caa4712019-08-28 15:05:58 -07002443}
2444
2445static void ioc_rqos_done_bio(struct rq_qos *rqos, struct bio *bio)
2446{
2447 struct ioc_gq *iocg = blkg_to_iocg(bio->bi_blkg);
2448
2449 if (iocg && bio->bi_iocost_cost)
2450 atomic64_add(bio->bi_iocost_cost, &iocg->done_vtime);
2451}
2452
2453static void ioc_rqos_done(struct rq_qos *rqos, struct request *rq)
2454{
2455 struct ioc *ioc = rqos_to_ioc(rqos);
Tejun Heo5e124f72020-09-01 14:52:33 -04002456 struct ioc_pcpu_stat *ccs;
Tejun Heocd006502020-04-13 12:27:56 -04002457 u64 on_q_ns, rq_wait_ns, size_nsec;
Tejun Heo7caa4712019-08-28 15:05:58 -07002458 int pidx, rw;
2459
2460 if (!ioc->enabled || !rq->alloc_time_ns || !rq->start_time_ns)
2461 return;
2462
2463 switch (req_op(rq) & REQ_OP_MASK) {
2464 case REQ_OP_READ:
2465 pidx = QOS_RLAT;
2466 rw = READ;
2467 break;
2468 case REQ_OP_WRITE:
2469 pidx = QOS_WLAT;
2470 rw = WRITE;
2471 break;
2472 default:
2473 return;
2474 }
2475
2476 on_q_ns = ktime_get_ns() - rq->alloc_time_ns;
2477 rq_wait_ns = rq->start_time_ns - rq->alloc_time_ns;
Tejun Heocd006502020-04-13 12:27:56 -04002478 size_nsec = div64_u64(calc_size_vtime_cost(rq, ioc), VTIME_PER_NSEC);
Tejun Heo7caa4712019-08-28 15:05:58 -07002479
Tejun Heo5e124f72020-09-01 14:52:33 -04002480 ccs = get_cpu_ptr(ioc->pcpu_stat);
2481
Tejun Heocd006502020-04-13 12:27:56 -04002482 if (on_q_ns <= size_nsec ||
2483 on_q_ns - size_nsec <= ioc->params.qos[pidx] * NSEC_PER_USEC)
Tejun Heo5e124f72020-09-01 14:52:33 -04002484 local_inc(&ccs->missed[rw].nr_met);
Tejun Heo7caa4712019-08-28 15:05:58 -07002485 else
Tejun Heo5e124f72020-09-01 14:52:33 -04002486 local_inc(&ccs->missed[rw].nr_missed);
Tejun Heo7caa4712019-08-28 15:05:58 -07002487
Tejun Heo5e124f72020-09-01 14:52:33 -04002488 local64_add(rq_wait_ns, &ccs->rq_wait_ns);
2489
2490 put_cpu_ptr(ccs);
Tejun Heo7caa4712019-08-28 15:05:58 -07002491}
2492
2493static void ioc_rqos_queue_depth_changed(struct rq_qos *rqos)
2494{
2495 struct ioc *ioc = rqos_to_ioc(rqos);
2496
2497 spin_lock_irq(&ioc->lock);
2498 ioc_refresh_params(ioc, false);
2499 spin_unlock_irq(&ioc->lock);
2500}
2501
2502static void ioc_rqos_exit(struct rq_qos *rqos)
2503{
2504 struct ioc *ioc = rqos_to_ioc(rqos);
2505
2506 blkcg_deactivate_policy(rqos->q, &blkcg_policy_iocost);
2507
2508 spin_lock_irq(&ioc->lock);
2509 ioc->running = IOC_STOP;
2510 spin_unlock_irq(&ioc->lock);
2511
2512 del_timer_sync(&ioc->timer);
2513 free_percpu(ioc->pcpu_stat);
2514 kfree(ioc);
2515}
2516
2517static struct rq_qos_ops ioc_rqos_ops = {
2518 .throttle = ioc_rqos_throttle,
2519 .merge = ioc_rqos_merge,
2520 .done_bio = ioc_rqos_done_bio,
2521 .done = ioc_rqos_done,
2522 .queue_depth_changed = ioc_rqos_queue_depth_changed,
2523 .exit = ioc_rqos_exit,
2524};
2525
2526static int blk_iocost_init(struct request_queue *q)
2527{
2528 struct ioc *ioc;
2529 struct rq_qos *rqos;
Tejun Heo5e124f72020-09-01 14:52:33 -04002530 int i, cpu, ret;
Tejun Heo7caa4712019-08-28 15:05:58 -07002531
2532 ioc = kzalloc(sizeof(*ioc), GFP_KERNEL);
2533 if (!ioc)
2534 return -ENOMEM;
2535
2536 ioc->pcpu_stat = alloc_percpu(struct ioc_pcpu_stat);
2537 if (!ioc->pcpu_stat) {
2538 kfree(ioc);
2539 return -ENOMEM;
2540 }
2541
Tejun Heo5e124f72020-09-01 14:52:33 -04002542 for_each_possible_cpu(cpu) {
2543 struct ioc_pcpu_stat *ccs = per_cpu_ptr(ioc->pcpu_stat, cpu);
2544
2545 for (i = 0; i < ARRAY_SIZE(ccs->missed); i++) {
2546 local_set(&ccs->missed[i].nr_met, 0);
2547 local_set(&ccs->missed[i].nr_missed, 0);
2548 }
2549 local64_set(&ccs->rq_wait_ns, 0);
2550 }
2551
Tejun Heo7caa4712019-08-28 15:05:58 -07002552 rqos = &ioc->rqos;
2553 rqos->id = RQ_QOS_COST;
2554 rqos->ops = &ioc_rqos_ops;
2555 rqos->q = q;
2556
2557 spin_lock_init(&ioc->lock);
2558 timer_setup(&ioc->timer, ioc_timer_fn, 0);
2559 INIT_LIST_HEAD(&ioc->active_iocgs);
2560
2561 ioc->running = IOC_IDLE;
2562 atomic64_set(&ioc->vtime_rate, VTIME_PER_USEC);
Ahmed S. Darwish67b7b642020-07-20 17:55:26 +02002563 seqcount_spinlock_init(&ioc->period_seqcount, &ioc->lock);
Tejun Heo7caa4712019-08-28 15:05:58 -07002564 ioc->period_at = ktime_to_us(ktime_get());
2565 atomic64_set(&ioc->cur_period, 0);
2566 atomic_set(&ioc->hweight_gen, 0);
2567
2568 spin_lock_irq(&ioc->lock);
2569 ioc->autop_idx = AUTOP_INVALID;
2570 ioc_refresh_params(ioc, true);
2571 spin_unlock_irq(&ioc->lock);
2572
2573 rq_qos_add(q, rqos);
2574 ret = blkcg_activate_policy(q, &blkcg_policy_iocost);
2575 if (ret) {
2576 rq_qos_del(q, rqos);
Tejun Heo3532e722019-08-29 08:53:06 -07002577 free_percpu(ioc->pcpu_stat);
Tejun Heo7caa4712019-08-28 15:05:58 -07002578 kfree(ioc);
2579 return ret;
2580 }
2581 return 0;
2582}
2583
2584static struct blkcg_policy_data *ioc_cpd_alloc(gfp_t gfp)
2585{
2586 struct ioc_cgrp *iocc;
2587
2588 iocc = kzalloc(sizeof(struct ioc_cgrp), gfp);
Tejun Heoe916ad22019-08-30 06:10:58 -07002589 if (!iocc)
2590 return NULL;
Tejun Heo7caa4712019-08-28 15:05:58 -07002591
Tejun Heobd0adb92020-09-01 14:52:39 -04002592 iocc->dfl_weight = CGROUP_WEIGHT_DFL * WEIGHT_ONE;
Tejun Heo7caa4712019-08-28 15:05:58 -07002593 return &iocc->cpd;
2594}
2595
2596static void ioc_cpd_free(struct blkcg_policy_data *cpd)
2597{
2598 kfree(container_of(cpd, struct ioc_cgrp, cpd));
2599}
2600
2601static struct blkg_policy_data *ioc_pd_alloc(gfp_t gfp, struct request_queue *q,
2602 struct blkcg *blkcg)
2603{
2604 int levels = blkcg->css.cgroup->level + 1;
2605 struct ioc_gq *iocg;
2606
Gustavo A. R. Silvaf61d6e22020-06-19 18:08:30 -05002607 iocg = kzalloc_node(struct_size(iocg, ancestors, levels), gfp, q->node);
Tejun Heo7caa4712019-08-28 15:05:58 -07002608 if (!iocg)
2609 return NULL;
2610
Tejun Heo97eb1972020-09-01 14:52:43 -04002611 iocg->pcpu_stat = alloc_percpu_gfp(struct iocg_pcpu_stat, gfp);
2612 if (!iocg->pcpu_stat) {
2613 kfree(iocg);
2614 return NULL;
2615 }
2616
Tejun Heo7caa4712019-08-28 15:05:58 -07002617 return &iocg->pd;
2618}
2619
2620static void ioc_pd_init(struct blkg_policy_data *pd)
2621{
2622 struct ioc_gq *iocg = pd_to_iocg(pd);
2623 struct blkcg_gq *blkg = pd_to_blkg(&iocg->pd);
2624 struct ioc *ioc = q_to_ioc(blkg->q);
2625 struct ioc_now now;
2626 struct blkcg_gq *tblkg;
2627 unsigned long flags;
2628
2629 ioc_now(ioc, &now);
2630
2631 iocg->ioc = ioc;
2632 atomic64_set(&iocg->vtime, now.vnow);
2633 atomic64_set(&iocg->done_vtime, now.vnow);
2634 atomic64_set(&iocg->active_period, atomic64_read(&ioc->cur_period));
2635 INIT_LIST_HEAD(&iocg->active_list);
Tejun Heo97eb1972020-09-01 14:52:43 -04002636 INIT_LIST_HEAD(&iocg->walk_list);
Tejun Heo8692d2d2020-09-01 14:52:45 -04002637 INIT_LIST_HEAD(&iocg->surplus_list);
Tejun Heofe20cdb52020-09-01 14:52:38 -04002638 iocg->hweight_active = WEIGHT_ONE;
2639 iocg->hweight_inuse = WEIGHT_ONE;
Tejun Heo7caa4712019-08-28 15:05:58 -07002640
2641 init_waitqueue_head(&iocg->waitq);
2642 hrtimer_init(&iocg->waitq_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
2643 iocg->waitq_timer.function = iocg_waitq_timer_fn;
2644 hrtimer_init(&iocg->delay_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
2645 iocg->delay_timer.function = iocg_delay_timer_fn;
2646
2647 iocg->level = blkg->blkcg->css.cgroup->level;
2648
2649 for (tblkg = blkg; tblkg; tblkg = tblkg->parent) {
2650 struct ioc_gq *tiocg = blkg_to_iocg(tblkg);
2651 iocg->ancestors[tiocg->level] = tiocg;
2652 }
2653
2654 spin_lock_irqsave(&ioc->lock, flags);
Tejun Heob0853ab2020-09-01 14:52:50 -04002655 weight_updated(iocg, &now);
Tejun Heo7caa4712019-08-28 15:05:58 -07002656 spin_unlock_irqrestore(&ioc->lock, flags);
2657}
2658
2659static void ioc_pd_free(struct blkg_policy_data *pd)
2660{
2661 struct ioc_gq *iocg = pd_to_iocg(pd);
2662 struct ioc *ioc = iocg->ioc;
Tejun Heo5aeac7c2020-09-01 14:52:31 -04002663 unsigned long flags;
Tejun Heo7caa4712019-08-28 15:05:58 -07002664
2665 if (ioc) {
Tejun Heo5aeac7c2020-09-01 14:52:31 -04002666 spin_lock_irqsave(&ioc->lock, flags);
Tejun Heo97eb1972020-09-01 14:52:43 -04002667
Tejun Heo7caa4712019-08-28 15:05:58 -07002668 if (!list_empty(&iocg->active_list)) {
Tejun Heob0853ab2020-09-01 14:52:50 -04002669 struct ioc_now now;
2670
2671 ioc_now(ioc, &now);
2672 propagate_weights(iocg, 0, 0, false, &now);
Tejun Heo7caa4712019-08-28 15:05:58 -07002673 list_del_init(&iocg->active_list);
2674 }
Tejun Heo97eb1972020-09-01 14:52:43 -04002675
2676 WARN_ON_ONCE(!list_empty(&iocg->walk_list));
Tejun Heo8692d2d2020-09-01 14:52:45 -04002677 WARN_ON_ONCE(!list_empty(&iocg->surplus_list));
Tejun Heo97eb1972020-09-01 14:52:43 -04002678
Tejun Heo5aeac7c2020-09-01 14:52:31 -04002679 spin_unlock_irqrestore(&ioc->lock, flags);
Tejun Heoe036c4c2019-09-10 09:15:25 -07002680
2681 hrtimer_cancel(&iocg->waitq_timer);
2682 hrtimer_cancel(&iocg->delay_timer);
Tejun Heo7caa4712019-08-28 15:05:58 -07002683 }
Tejun Heo97eb1972020-09-01 14:52:43 -04002684 free_percpu(iocg->pcpu_stat);
Tejun Heo7caa4712019-08-28 15:05:58 -07002685 kfree(iocg);
2686}
2687
Tejun Heo97eb1972020-09-01 14:52:43 -04002688static size_t ioc_pd_stat(struct blkg_policy_data *pd, char *buf, size_t size)
2689{
2690 struct ioc_gq *iocg = pd_to_iocg(pd);
2691 struct ioc *ioc = iocg->ioc;
2692 size_t pos = 0;
2693
2694 if (!ioc->enabled)
2695 return 0;
2696
2697 if (iocg->level == 0) {
2698 unsigned vp10k = DIV64_U64_ROUND_CLOSEST(
2699 atomic64_read(&ioc->vtime_rate) * 10000,
2700 VTIME_PER_USEC);
2701 pos += scnprintf(buf + pos, size - pos, " cost.vrate=%u.%02u",
2702 vp10k / 100, vp10k % 100);
2703 }
2704
2705 pos += scnprintf(buf + pos, size - pos, " cost.usage=%llu",
2706 iocg->last_stat.usage_us);
2707
2708 return pos;
2709}
2710
Tejun Heo7caa4712019-08-28 15:05:58 -07002711static u64 ioc_weight_prfill(struct seq_file *sf, struct blkg_policy_data *pd,
2712 int off)
2713{
2714 const char *dname = blkg_dev_name(pd->blkg);
2715 struct ioc_gq *iocg = pd_to_iocg(pd);
2716
2717 if (dname && iocg->cfg_weight)
Tejun Heobd0adb92020-09-01 14:52:39 -04002718 seq_printf(sf, "%s %u\n", dname, iocg->cfg_weight / WEIGHT_ONE);
Tejun Heo7caa4712019-08-28 15:05:58 -07002719 return 0;
2720}
2721
2722
2723static int ioc_weight_show(struct seq_file *sf, void *v)
2724{
2725 struct blkcg *blkcg = css_to_blkcg(seq_css(sf));
2726 struct ioc_cgrp *iocc = blkcg_to_iocc(blkcg);
2727
Tejun Heobd0adb92020-09-01 14:52:39 -04002728 seq_printf(sf, "default %u\n", iocc->dfl_weight / WEIGHT_ONE);
Tejun Heo7caa4712019-08-28 15:05:58 -07002729 blkcg_print_blkgs(sf, blkcg, ioc_weight_prfill,
2730 &blkcg_policy_iocost, seq_cft(sf)->private, false);
2731 return 0;
2732}
2733
2734static ssize_t ioc_weight_write(struct kernfs_open_file *of, char *buf,
2735 size_t nbytes, loff_t off)
2736{
2737 struct blkcg *blkcg = css_to_blkcg(of_css(of));
2738 struct ioc_cgrp *iocc = blkcg_to_iocc(blkcg);
2739 struct blkg_conf_ctx ctx;
Tejun Heob0853ab2020-09-01 14:52:50 -04002740 struct ioc_now now;
Tejun Heo7caa4712019-08-28 15:05:58 -07002741 struct ioc_gq *iocg;
2742 u32 v;
2743 int ret;
2744
2745 if (!strchr(buf, ':')) {
2746 struct blkcg_gq *blkg;
2747
2748 if (!sscanf(buf, "default %u", &v) && !sscanf(buf, "%u", &v))
2749 return -EINVAL;
2750
2751 if (v < CGROUP_WEIGHT_MIN || v > CGROUP_WEIGHT_MAX)
2752 return -EINVAL;
2753
2754 spin_lock(&blkcg->lock);
Tejun Heobd0adb92020-09-01 14:52:39 -04002755 iocc->dfl_weight = v * WEIGHT_ONE;
Tejun Heo7caa4712019-08-28 15:05:58 -07002756 hlist_for_each_entry(blkg, &blkcg->blkg_list, blkcg_node) {
2757 struct ioc_gq *iocg = blkg_to_iocg(blkg);
2758
2759 if (iocg) {
2760 spin_lock_irq(&iocg->ioc->lock);
Tejun Heob0853ab2020-09-01 14:52:50 -04002761 ioc_now(iocg->ioc, &now);
2762 weight_updated(iocg, &now);
Tejun Heo7caa4712019-08-28 15:05:58 -07002763 spin_unlock_irq(&iocg->ioc->lock);
2764 }
2765 }
2766 spin_unlock(&blkcg->lock);
2767
2768 return nbytes;
2769 }
2770
2771 ret = blkg_conf_prep(blkcg, &blkcg_policy_iocost, buf, &ctx);
2772 if (ret)
2773 return ret;
2774
2775 iocg = blkg_to_iocg(ctx.blkg);
2776
2777 if (!strncmp(ctx.body, "default", 7)) {
2778 v = 0;
2779 } else {
2780 if (!sscanf(ctx.body, "%u", &v))
2781 goto einval;
2782 if (v < CGROUP_WEIGHT_MIN || v > CGROUP_WEIGHT_MAX)
2783 goto einval;
2784 }
2785
Dan Carpenter41591a52019-10-31 13:53:41 +03002786 spin_lock(&iocg->ioc->lock);
Tejun Heobd0adb92020-09-01 14:52:39 -04002787 iocg->cfg_weight = v * WEIGHT_ONE;
Tejun Heob0853ab2020-09-01 14:52:50 -04002788 ioc_now(iocg->ioc, &now);
2789 weight_updated(iocg, &now);
Dan Carpenter41591a52019-10-31 13:53:41 +03002790 spin_unlock(&iocg->ioc->lock);
Tejun Heo7caa4712019-08-28 15:05:58 -07002791
2792 blkg_conf_finish(&ctx);
2793 return nbytes;
2794
2795einval:
2796 blkg_conf_finish(&ctx);
2797 return -EINVAL;
2798}
2799
2800static u64 ioc_qos_prfill(struct seq_file *sf, struct blkg_policy_data *pd,
2801 int off)
2802{
2803 const char *dname = blkg_dev_name(pd->blkg);
2804 struct ioc *ioc = pd_to_iocg(pd)->ioc;
2805
2806 if (!dname)
2807 return 0;
2808
2809 seq_printf(sf, "%s enable=%d ctrl=%s rpct=%u.%02u rlat=%u wpct=%u.%02u wlat=%u min=%u.%02u max=%u.%02u\n",
2810 dname, ioc->enabled, ioc->user_qos_params ? "user" : "auto",
2811 ioc->params.qos[QOS_RPPM] / 10000,
2812 ioc->params.qos[QOS_RPPM] % 10000 / 100,
2813 ioc->params.qos[QOS_RLAT],
2814 ioc->params.qos[QOS_WPPM] / 10000,
2815 ioc->params.qos[QOS_WPPM] % 10000 / 100,
2816 ioc->params.qos[QOS_WLAT],
2817 ioc->params.qos[QOS_MIN] / 10000,
2818 ioc->params.qos[QOS_MIN] % 10000 / 100,
2819 ioc->params.qos[QOS_MAX] / 10000,
2820 ioc->params.qos[QOS_MAX] % 10000 / 100);
2821 return 0;
2822}
2823
2824static int ioc_qos_show(struct seq_file *sf, void *v)
2825{
2826 struct blkcg *blkcg = css_to_blkcg(seq_css(sf));
2827
2828 blkcg_print_blkgs(sf, blkcg, ioc_qos_prfill,
2829 &blkcg_policy_iocost, seq_cft(sf)->private, false);
2830 return 0;
2831}
2832
2833static const match_table_t qos_ctrl_tokens = {
2834 { QOS_ENABLE, "enable=%u" },
2835 { QOS_CTRL, "ctrl=%s" },
2836 { NR_QOS_CTRL_PARAMS, NULL },
2837};
2838
2839static const match_table_t qos_tokens = {
2840 { QOS_RPPM, "rpct=%s" },
2841 { QOS_RLAT, "rlat=%u" },
2842 { QOS_WPPM, "wpct=%s" },
2843 { QOS_WLAT, "wlat=%u" },
2844 { QOS_MIN, "min=%s" },
2845 { QOS_MAX, "max=%s" },
2846 { NR_QOS_PARAMS, NULL },
2847};
2848
2849static ssize_t ioc_qos_write(struct kernfs_open_file *of, char *input,
2850 size_t nbytes, loff_t off)
2851{
2852 struct gendisk *disk;
2853 struct ioc *ioc;
2854 u32 qos[NR_QOS_PARAMS];
2855 bool enable, user;
2856 char *p;
2857 int ret;
2858
2859 disk = blkcg_conf_get_disk(&input);
2860 if (IS_ERR(disk))
2861 return PTR_ERR(disk);
2862
2863 ioc = q_to_ioc(disk->queue);
2864 if (!ioc) {
2865 ret = blk_iocost_init(disk->queue);
2866 if (ret)
2867 goto err;
2868 ioc = q_to_ioc(disk->queue);
2869 }
2870
2871 spin_lock_irq(&ioc->lock);
2872 memcpy(qos, ioc->params.qos, sizeof(qos));
2873 enable = ioc->enabled;
2874 user = ioc->user_qos_params;
2875 spin_unlock_irq(&ioc->lock);
2876
2877 while ((p = strsep(&input, " \t\n"))) {
2878 substring_t args[MAX_OPT_ARGS];
2879 char buf[32];
2880 int tok;
2881 s64 v;
2882
2883 if (!*p)
2884 continue;
2885
2886 switch (match_token(p, qos_ctrl_tokens, args)) {
2887 case QOS_ENABLE:
2888 match_u64(&args[0], &v);
2889 enable = v;
2890 continue;
2891 case QOS_CTRL:
2892 match_strlcpy(buf, &args[0], sizeof(buf));
2893 if (!strcmp(buf, "auto"))
2894 user = false;
2895 else if (!strcmp(buf, "user"))
2896 user = true;
2897 else
2898 goto einval;
2899 continue;
2900 }
2901
2902 tok = match_token(p, qos_tokens, args);
2903 switch (tok) {
2904 case QOS_RPPM:
2905 case QOS_WPPM:
2906 if (match_strlcpy(buf, &args[0], sizeof(buf)) >=
2907 sizeof(buf))
2908 goto einval;
2909 if (cgroup_parse_float(buf, 2, &v))
2910 goto einval;
2911 if (v < 0 || v > 10000)
2912 goto einval;
2913 qos[tok] = v * 100;
2914 break;
2915 case QOS_RLAT:
2916 case QOS_WLAT:
2917 if (match_u64(&args[0], &v))
2918 goto einval;
2919 qos[tok] = v;
2920 break;
2921 case QOS_MIN:
2922 case QOS_MAX:
2923 if (match_strlcpy(buf, &args[0], sizeof(buf)) >=
2924 sizeof(buf))
2925 goto einval;
2926 if (cgroup_parse_float(buf, 2, &v))
2927 goto einval;
2928 if (v < 0)
2929 goto einval;
2930 qos[tok] = clamp_t(s64, v * 100,
2931 VRATE_MIN_PPM, VRATE_MAX_PPM);
2932 break;
2933 default:
2934 goto einval;
2935 }
2936 user = true;
2937 }
2938
2939 if (qos[QOS_MIN] > qos[QOS_MAX])
2940 goto einval;
2941
2942 spin_lock_irq(&ioc->lock);
2943
2944 if (enable) {
Tejun Heocd006502020-04-13 12:27:56 -04002945 blk_stat_enable_accounting(ioc->rqos.q);
Tejun Heo7caa4712019-08-28 15:05:58 -07002946 blk_queue_flag_set(QUEUE_FLAG_RQ_ALLOC_TIME, ioc->rqos.q);
2947 ioc->enabled = true;
2948 } else {
2949 blk_queue_flag_clear(QUEUE_FLAG_RQ_ALLOC_TIME, ioc->rqos.q);
2950 ioc->enabled = false;
2951 }
2952
2953 if (user) {
2954 memcpy(ioc->params.qos, qos, sizeof(qos));
2955 ioc->user_qos_params = true;
2956 } else {
2957 ioc->user_qos_params = false;
2958 }
2959
2960 ioc_refresh_params(ioc, true);
2961 spin_unlock_irq(&ioc->lock);
2962
2963 put_disk_and_module(disk);
2964 return nbytes;
2965einval:
2966 ret = -EINVAL;
2967err:
2968 put_disk_and_module(disk);
2969 return ret;
2970}
2971
2972static u64 ioc_cost_model_prfill(struct seq_file *sf,
2973 struct blkg_policy_data *pd, int off)
2974{
2975 const char *dname = blkg_dev_name(pd->blkg);
2976 struct ioc *ioc = pd_to_iocg(pd)->ioc;
2977 u64 *u = ioc->params.i_lcoefs;
2978
2979 if (!dname)
2980 return 0;
2981
2982 seq_printf(sf, "%s ctrl=%s model=linear "
2983 "rbps=%llu rseqiops=%llu rrandiops=%llu "
2984 "wbps=%llu wseqiops=%llu wrandiops=%llu\n",
2985 dname, ioc->user_cost_model ? "user" : "auto",
2986 u[I_LCOEF_RBPS], u[I_LCOEF_RSEQIOPS], u[I_LCOEF_RRANDIOPS],
2987 u[I_LCOEF_WBPS], u[I_LCOEF_WSEQIOPS], u[I_LCOEF_WRANDIOPS]);
2988 return 0;
2989}
2990
2991static int ioc_cost_model_show(struct seq_file *sf, void *v)
2992{
2993 struct blkcg *blkcg = css_to_blkcg(seq_css(sf));
2994
2995 blkcg_print_blkgs(sf, blkcg, ioc_cost_model_prfill,
2996 &blkcg_policy_iocost, seq_cft(sf)->private, false);
2997 return 0;
2998}
2999
3000static const match_table_t cost_ctrl_tokens = {
3001 { COST_CTRL, "ctrl=%s" },
3002 { COST_MODEL, "model=%s" },
3003 { NR_COST_CTRL_PARAMS, NULL },
3004};
3005
3006static const match_table_t i_lcoef_tokens = {
3007 { I_LCOEF_RBPS, "rbps=%u" },
3008 { I_LCOEF_RSEQIOPS, "rseqiops=%u" },
3009 { I_LCOEF_RRANDIOPS, "rrandiops=%u" },
3010 { I_LCOEF_WBPS, "wbps=%u" },
3011 { I_LCOEF_WSEQIOPS, "wseqiops=%u" },
3012 { I_LCOEF_WRANDIOPS, "wrandiops=%u" },
3013 { NR_I_LCOEFS, NULL },
3014};
3015
3016static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
3017 size_t nbytes, loff_t off)
3018{
3019 struct gendisk *disk;
3020 struct ioc *ioc;
3021 u64 u[NR_I_LCOEFS];
3022 bool user;
3023 char *p;
3024 int ret;
3025
3026 disk = blkcg_conf_get_disk(&input);
3027 if (IS_ERR(disk))
3028 return PTR_ERR(disk);
3029
3030 ioc = q_to_ioc(disk->queue);
3031 if (!ioc) {
3032 ret = blk_iocost_init(disk->queue);
3033 if (ret)
3034 goto err;
3035 ioc = q_to_ioc(disk->queue);
3036 }
3037
3038 spin_lock_irq(&ioc->lock);
3039 memcpy(u, ioc->params.i_lcoefs, sizeof(u));
3040 user = ioc->user_cost_model;
3041 spin_unlock_irq(&ioc->lock);
3042
3043 while ((p = strsep(&input, " \t\n"))) {
3044 substring_t args[MAX_OPT_ARGS];
3045 char buf[32];
3046 int tok;
3047 u64 v;
3048
3049 if (!*p)
3050 continue;
3051
3052 switch (match_token(p, cost_ctrl_tokens, args)) {
3053 case COST_CTRL:
3054 match_strlcpy(buf, &args[0], sizeof(buf));
3055 if (!strcmp(buf, "auto"))
3056 user = false;
3057 else if (!strcmp(buf, "user"))
3058 user = true;
3059 else
3060 goto einval;
3061 continue;
3062 case COST_MODEL:
3063 match_strlcpy(buf, &args[0], sizeof(buf));
3064 if (strcmp(buf, "linear"))
3065 goto einval;
3066 continue;
3067 }
3068
3069 tok = match_token(p, i_lcoef_tokens, args);
3070 if (tok == NR_I_LCOEFS)
3071 goto einval;
3072 if (match_u64(&args[0], &v))
3073 goto einval;
3074 u[tok] = v;
3075 user = true;
3076 }
3077
3078 spin_lock_irq(&ioc->lock);
3079 if (user) {
3080 memcpy(ioc->params.i_lcoefs, u, sizeof(u));
3081 ioc->user_cost_model = true;
3082 } else {
3083 ioc->user_cost_model = false;
3084 }
3085 ioc_refresh_params(ioc, true);
3086 spin_unlock_irq(&ioc->lock);
3087
3088 put_disk_and_module(disk);
3089 return nbytes;
3090
3091einval:
3092 ret = -EINVAL;
3093err:
3094 put_disk_and_module(disk);
3095 return ret;
3096}
3097
3098static struct cftype ioc_files[] = {
3099 {
3100 .name = "weight",
3101 .flags = CFTYPE_NOT_ON_ROOT,
3102 .seq_show = ioc_weight_show,
3103 .write = ioc_weight_write,
3104 },
3105 {
3106 .name = "cost.qos",
3107 .flags = CFTYPE_ONLY_ON_ROOT,
3108 .seq_show = ioc_qos_show,
3109 .write = ioc_qos_write,
3110 },
3111 {
3112 .name = "cost.model",
3113 .flags = CFTYPE_ONLY_ON_ROOT,
3114 .seq_show = ioc_cost_model_show,
3115 .write = ioc_cost_model_write,
3116 },
3117 {}
3118};
3119
3120static struct blkcg_policy blkcg_policy_iocost = {
3121 .dfl_cftypes = ioc_files,
3122 .cpd_alloc_fn = ioc_cpd_alloc,
3123 .cpd_free_fn = ioc_cpd_free,
3124 .pd_alloc_fn = ioc_pd_alloc,
3125 .pd_init_fn = ioc_pd_init,
3126 .pd_free_fn = ioc_pd_free,
Tejun Heo97eb1972020-09-01 14:52:43 -04003127 .pd_stat_fn = ioc_pd_stat,
Tejun Heo7caa4712019-08-28 15:05:58 -07003128};
3129
3130static int __init ioc_init(void)
3131{
3132 return blkcg_policy_register(&blkcg_policy_iocost);
3133}
3134
3135static void __exit ioc_exit(void)
3136{
3137 return blkcg_policy_unregister(&blkcg_policy_iocost);
3138}
3139
3140module_init(ioc_init);
3141module_exit(ioc_exit);