blob: d09b4011449c3469612d64e9e67195aed462ad1d [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;
1209 u32 hw_inuse;
1210
1211 lockdep_assert_held(&iocg->waitq.lock);
1212
1213 /* debt-adjust vtime */
1214 current_hweight(iocg, NULL, &hw_inuse);
1215 vtime += abs_cost_to_cost(iocg->abs_vdebt, hw_inuse);
1216
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 Heo7caa4712019-08-28 15:05:58 -07001261static int iocg_wake_fn(struct wait_queue_entry *wq_entry, unsigned mode,
1262 int flags, void *key)
1263{
1264 struct iocg_wait *wait = container_of(wq_entry, struct iocg_wait, wait);
1265 struct iocg_wake_ctx *ctx = (struct iocg_wake_ctx *)key;
1266 u64 cost = abs_cost_to_cost(wait->abs_cost, ctx->hw_inuse);
1267
1268 ctx->vbudget -= cost;
1269
1270 if (ctx->vbudget < 0)
1271 return -1;
1272
Tejun Heo97eb1972020-09-01 14:52:43 -04001273 iocg_commit_bio(ctx->iocg, wait->bio, wait->abs_cost, cost);
Tejun Heo7caa4712019-08-28 15:05:58 -07001274
1275 /*
1276 * autoremove_wake_function() removes the wait entry only when it
1277 * actually changed the task state. We want the wait always
1278 * removed. Remove explicitly and use default_wake_function().
1279 */
1280 list_del_init(&wq_entry->entry);
1281 wait->committed = true;
1282
1283 default_wake_function(wq_entry, mode, flags, key);
1284 return 0;
1285}
1286
Tejun Heoda437b92020-09-01 14:52:42 -04001287/*
1288 * Calculate the accumulated budget, pay debt if @pay_debt and wake up waiters
1289 * accordingly. When @pay_debt is %true, the caller must be holding ioc->lock in
1290 * addition to iocg->waitq.lock.
1291 */
1292static void iocg_kick_waitq(struct ioc_gq *iocg, bool pay_debt,
1293 struct ioc_now *now)
Tejun Heo7caa4712019-08-28 15:05:58 -07001294{
1295 struct ioc *ioc = iocg->ioc;
1296 struct iocg_wake_ctx ctx = { .iocg = iocg };
Tejun Heoda437b92020-09-01 14:52:42 -04001297 u64 vshortage, expires, oexpires;
Tejun Heo36a52482019-09-04 12:45:52 -07001298 s64 vbudget;
1299 u32 hw_inuse;
Tejun Heo7caa4712019-08-28 15:05:58 -07001300
1301 lockdep_assert_held(&iocg->waitq.lock);
1302
Tejun Heo36a52482019-09-04 12:45:52 -07001303 current_hweight(iocg, NULL, &hw_inuse);
1304 vbudget = now->vnow - atomic64_read(&iocg->vtime);
1305
1306 /* pay off debt */
Tejun Heoda437b92020-09-01 14:52:42 -04001307 if (pay_debt && iocg->abs_vdebt && vbudget > 0) {
1308 u64 vdebt = abs_cost_to_cost(iocg->abs_vdebt, hw_inuse);
Tejun Heo36a52482019-09-04 12:45:52 -07001309 u64 delta = min_t(u64, vbudget, vdebt);
1310 u64 abs_delta = min(cost_to_abs_cost(delta, hw_inuse),
Tejun Heo0b80f982020-05-04 19:27:54 -04001311 iocg->abs_vdebt);
Tejun Heo36a52482019-09-04 12:45:52 -07001312
Tejun Heoda437b92020-09-01 14:52:42 -04001313 lockdep_assert_held(&ioc->lock);
1314
Tejun Heo36a52482019-09-04 12:45:52 -07001315 atomic64_add(delta, &iocg->vtime);
1316 atomic64_add(delta, &iocg->done_vtime);
Tejun Heo0b80f982020-05-04 19:27:54 -04001317 iocg->abs_vdebt -= abs_delta;
Tejun Heoda437b92020-09-01 14:52:42 -04001318 vbudget -= vdebt;
Tejun Heo7b84b492020-09-01 14:52:37 -04001319
1320 iocg_kick_delay(iocg, now);
Tejun Heo36a52482019-09-04 12:45:52 -07001321 }
1322
Tejun Heo7caa4712019-08-28 15:05:58 -07001323 /*
Tejun Heoda437b92020-09-01 14:52:42 -04001324 * Debt can still be outstanding if we haven't paid all yet or the
1325 * caller raced and called without @pay_debt. Shouldn't wake up waiters
1326 * under debt. Make sure @vbudget reflects the outstanding amount and is
1327 * not positive.
1328 */
1329 if (iocg->abs_vdebt) {
1330 s64 vdebt = abs_cost_to_cost(iocg->abs_vdebt, hw_inuse);
1331 vbudget = min_t(s64, 0, vbudget - vdebt);
1332 }
1333
1334 /*
Tejun Heo7caa4712019-08-28 15:05:58 -07001335 * Wake up the ones which are due and see how much vtime we'll need
1336 * for the next one.
1337 */
Tejun Heo36a52482019-09-04 12:45:52 -07001338 ctx.hw_inuse = hw_inuse;
Tejun Heoda437b92020-09-01 14:52:42 -04001339 ctx.vbudget = vbudget;
Tejun Heo7caa4712019-08-28 15:05:58 -07001340 __wake_up_locked_key(&iocg->waitq, TASK_NORMAL, &ctx);
1341 if (!waitqueue_active(&iocg->waitq))
1342 return;
1343 if (WARN_ON_ONCE(ctx.vbudget >= 0))
1344 return;
1345
Tejun Heo7ca5b2e2020-09-01 14:52:41 -04001346 /* determine next wakeup, add a timer margin to guarantee chunking */
Tejun Heo7caa4712019-08-28 15:05:58 -07001347 vshortage = -ctx.vbudget;
1348 expires = now->now_ns +
1349 DIV64_U64_ROUND_UP(vshortage, now->vrate) * NSEC_PER_USEC;
Tejun Heo7ca5b2e2020-09-01 14:52:41 -04001350 expires += ioc->timer_slack_ns;
Tejun Heo7caa4712019-08-28 15:05:58 -07001351
1352 /* if already active and close enough, don't bother */
1353 oexpires = ktime_to_ns(hrtimer_get_softexpires(&iocg->waitq_timer));
1354 if (hrtimer_is_queued(&iocg->waitq_timer) &&
Tejun Heo7ca5b2e2020-09-01 14:52:41 -04001355 abs(oexpires - expires) <= ioc->timer_slack_ns)
Tejun Heo7caa4712019-08-28 15:05:58 -07001356 return;
1357
1358 hrtimer_start_range_ns(&iocg->waitq_timer, ns_to_ktime(expires),
Tejun Heo7ca5b2e2020-09-01 14:52:41 -04001359 ioc->timer_slack_ns, HRTIMER_MODE_ABS);
Tejun Heo7caa4712019-08-28 15:05:58 -07001360}
1361
1362static enum hrtimer_restart iocg_waitq_timer_fn(struct hrtimer *timer)
1363{
1364 struct ioc_gq *iocg = container_of(timer, struct ioc_gq, waitq_timer);
Tejun Heoda437b92020-09-01 14:52:42 -04001365 bool pay_debt = READ_ONCE(iocg->abs_vdebt);
Tejun Heo7caa4712019-08-28 15:05:58 -07001366 struct ioc_now now;
1367 unsigned long flags;
1368
1369 ioc_now(iocg->ioc, &now);
1370
Tejun Heoda437b92020-09-01 14:52:42 -04001371 iocg_lock(iocg, pay_debt, &flags);
1372 iocg_kick_waitq(iocg, pay_debt, &now);
1373 iocg_unlock(iocg, pay_debt, &flags);
Tejun Heo7caa4712019-08-28 15:05:58 -07001374
1375 return HRTIMER_NORESTART;
1376}
1377
Tejun Heo7caa4712019-08-28 15:05:58 -07001378static void ioc_lat_stat(struct ioc *ioc, u32 *missed_ppm_ar, u32 *rq_wait_pct_p)
1379{
1380 u32 nr_met[2] = { };
1381 u32 nr_missed[2] = { };
1382 u64 rq_wait_ns = 0;
1383 int cpu, rw;
1384
1385 for_each_online_cpu(cpu) {
1386 struct ioc_pcpu_stat *stat = per_cpu_ptr(ioc->pcpu_stat, cpu);
1387 u64 this_rq_wait_ns;
1388
1389 for (rw = READ; rw <= WRITE; rw++) {
Tejun Heo5e124f72020-09-01 14:52:33 -04001390 u32 this_met = local_read(&stat->missed[rw].nr_met);
1391 u32 this_missed = local_read(&stat->missed[rw].nr_missed);
Tejun Heo7caa4712019-08-28 15:05:58 -07001392
1393 nr_met[rw] += this_met - stat->missed[rw].last_met;
1394 nr_missed[rw] += this_missed - stat->missed[rw].last_missed;
1395 stat->missed[rw].last_met = this_met;
1396 stat->missed[rw].last_missed = this_missed;
1397 }
1398
Tejun Heo5e124f72020-09-01 14:52:33 -04001399 this_rq_wait_ns = local64_read(&stat->rq_wait_ns);
Tejun Heo7caa4712019-08-28 15:05:58 -07001400 rq_wait_ns += this_rq_wait_ns - stat->last_rq_wait_ns;
1401 stat->last_rq_wait_ns = this_rq_wait_ns;
1402 }
1403
1404 for (rw = READ; rw <= WRITE; rw++) {
1405 if (nr_met[rw] + nr_missed[rw])
1406 missed_ppm_ar[rw] =
1407 DIV64_U64_ROUND_UP((u64)nr_missed[rw] * MILLION,
1408 nr_met[rw] + nr_missed[rw]);
1409 else
1410 missed_ppm_ar[rw] = 0;
1411 }
1412
1413 *rq_wait_pct_p = div64_u64(rq_wait_ns * 100,
1414 ioc->period_us * NSEC_PER_USEC);
1415}
1416
1417/* was iocg idle this period? */
1418static bool iocg_is_idle(struct ioc_gq *iocg)
1419{
1420 struct ioc *ioc = iocg->ioc;
1421
1422 /* did something get issued this period? */
1423 if (atomic64_read(&iocg->active_period) ==
1424 atomic64_read(&ioc->cur_period))
1425 return false;
1426
1427 /* is something in flight? */
Tejun Heodcd65892020-03-10 13:07:46 -04001428 if (atomic64_read(&iocg->done_vtime) != atomic64_read(&iocg->vtime))
Tejun Heo7caa4712019-08-28 15:05:58 -07001429 return false;
1430
1431 return true;
1432}
1433
Tejun Heo97eb1972020-09-01 14:52:43 -04001434/*
1435 * Call this function on the target leaf @iocg's to build pre-order traversal
1436 * list of all the ancestors in @inner_walk. The inner nodes are linked through
1437 * ->walk_list and the caller is responsible for dissolving the list after use.
1438 */
1439static void iocg_build_inner_walk(struct ioc_gq *iocg,
1440 struct list_head *inner_walk)
1441{
1442 int lvl;
1443
1444 WARN_ON_ONCE(!list_empty(&iocg->walk_list));
1445
1446 /* find the first ancestor which hasn't been visited yet */
1447 for (lvl = iocg->level - 1; lvl >= 0; lvl--) {
1448 if (!list_empty(&iocg->ancestors[lvl]->walk_list))
1449 break;
1450 }
1451
1452 /* walk down and visit the inner nodes to get pre-order traversal */
1453 while (++lvl <= iocg->level - 1) {
1454 struct ioc_gq *inner = iocg->ancestors[lvl];
1455
1456 /* record traversal order */
1457 list_add_tail(&inner->walk_list, inner_walk);
1458 }
1459}
1460
1461/* collect per-cpu counters and propagate the deltas to the parent */
1462static void iocg_flush_stat_one(struct ioc_gq *iocg, struct ioc_now *now)
1463{
1464 struct iocg_stat new_stat;
1465 u64 abs_vusage = 0;
1466 u64 vusage_delta;
1467 int cpu;
1468
1469 lockdep_assert_held(&iocg->ioc->lock);
1470
1471 /* collect per-cpu counters */
1472 for_each_possible_cpu(cpu) {
1473 abs_vusage += local64_read(
1474 per_cpu_ptr(&iocg->pcpu_stat->abs_vusage, cpu));
1475 }
1476 vusage_delta = abs_vusage - iocg->last_stat_abs_vusage;
1477 iocg->last_stat_abs_vusage = abs_vusage;
1478
Tejun Heo1aa50d02020-09-01 14:52:44 -04001479 iocg->usage_delta_us = div64_u64(vusage_delta, now->vrate);
1480 iocg->local_stat.usage_us += iocg->usage_delta_us;
Tejun Heo97eb1972020-09-01 14:52:43 -04001481
1482 new_stat.usage_us =
1483 iocg->local_stat.usage_us + iocg->desc_stat.usage_us;
1484
1485 /* propagate the deltas to the parent */
1486 if (iocg->level > 0) {
1487 struct iocg_stat *parent_stat =
1488 &iocg->ancestors[iocg->level - 1]->desc_stat;
1489
1490 parent_stat->usage_us +=
1491 new_stat.usage_us - iocg->last_stat.usage_us;
1492 }
1493
1494 iocg->last_stat = new_stat;
1495}
1496
1497/* get stat counters ready for reading on all active iocgs */
1498static void iocg_flush_stat(struct list_head *target_iocgs, struct ioc_now *now)
1499{
1500 LIST_HEAD(inner_walk);
1501 struct ioc_gq *iocg, *tiocg;
1502
1503 /* flush leaves and build inner node walk list */
1504 list_for_each_entry(iocg, target_iocgs, active_list) {
1505 iocg_flush_stat_one(iocg, now);
1506 iocg_build_inner_walk(iocg, &inner_walk);
1507 }
1508
1509 /* keep flushing upwards by walking the inner list backwards */
1510 list_for_each_entry_safe_reverse(iocg, tiocg, &inner_walk, walk_list) {
1511 iocg_flush_stat_one(iocg, now);
1512 list_del_init(&iocg->walk_list);
1513 }
1514}
1515
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001516/*
1517 * Determine what @iocg's hweight_inuse should be after donating unused
1518 * capacity. @hwm is the upper bound and used to signal no donation. This
1519 * function also throws away @iocg's excess budget.
1520 */
1521static u32 hweight_after_donation(struct ioc_gq *iocg, u32 hwm, u32 usage,
1522 struct ioc_now *now)
Tejun Heo7caa4712019-08-28 15:05:58 -07001523{
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001524 struct ioc *ioc = iocg->ioc;
1525 u64 vtime = atomic64_read(&iocg->vtime);
Tejun Heof1de2432020-09-01 14:52:49 -04001526 s64 excess, delta, target, new_hwi;
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001527
1528 /* see whether minimum margin requirement is met */
1529 if (waitqueue_active(&iocg->waitq) ||
1530 time_after64(vtime, now->vnow - ioc->margins.min))
1531 return hwm;
1532
1533 /* throw away excess above max */
1534 excess = now->vnow - vtime - ioc->margins.max;
1535 if (excess > 0) {
1536 atomic64_add(excess, &iocg->vtime);
1537 atomic64_add(excess, &iocg->done_vtime);
1538 vtime += excess;
1539 }
1540
Tejun Heof1de2432020-09-01 14:52:49 -04001541 /*
1542 * Let's say the distance between iocg's and device's vtimes as a
1543 * fraction of period duration is delta. Assuming that the iocg will
1544 * consume the usage determined above, we want to determine new_hwi so
1545 * that delta equals MARGIN_TARGET at the end of the next period.
1546 *
1547 * We need to execute usage worth of IOs while spending the sum of the
1548 * new budget (1 - MARGIN_TARGET) and the leftover from the last period
1549 * (delta):
1550 *
1551 * usage = (1 - MARGIN_TARGET + delta) * new_hwi
1552 *
1553 * Therefore, the new_hwi is:
1554 *
1555 * new_hwi = usage / (1 - MARGIN_TARGET + delta)
1556 */
1557 delta = div64_s64(WEIGHT_ONE * (now->vnow - vtime),
1558 now->vnow - ioc->period_at_vtime);
1559 target = WEIGHT_ONE * MARGIN_TARGET_PCT / 100;
1560 new_hwi = div64_s64(WEIGHT_ONE * usage, WEIGHT_ONE - target + delta);
Tejun Heo7caa4712019-08-28 15:05:58 -07001561
Tejun Heof1de2432020-09-01 14:52:49 -04001562 return clamp_t(s64, new_hwi, 1, hwm);
Tejun Heo7caa4712019-08-28 15:05:58 -07001563}
1564
Tejun Heoe08d02a2020-09-01 14:52:48 -04001565/*
1566 * For work-conservation, an iocg which isn't using all of its share should
1567 * donate the leftover to other iocgs. There are two ways to achieve this - 1.
1568 * bumping up vrate accordingly 2. lowering the donating iocg's inuse weight.
1569 *
1570 * #1 is mathematically simpler but has the drawback of requiring synchronous
1571 * global hweight_inuse updates when idle iocg's get activated or inuse weights
1572 * change due to donation snapbacks as it has the possibility of grossly
1573 * overshooting what's allowed by the model and vrate.
1574 *
1575 * #2 is inherently safe with local operations. The donating iocg can easily
1576 * snap back to higher weights when needed without worrying about impacts on
1577 * other nodes as the impacts will be inherently correct. This also makes idle
1578 * iocg activations safe. The only effect activations have is decreasing
1579 * hweight_inuse of others, the right solution to which is for those iocgs to
1580 * snap back to higher weights.
1581 *
1582 * So, we go with #2. The challenge is calculating how each donating iocg's
1583 * inuse should be adjusted to achieve the target donation amounts. This is done
1584 * using Andy's method described in the following pdf.
1585 *
1586 * https://drive.google.com/file/d/1PsJwxPFtjUnwOY1QJ5AeICCcsL7BM3bo
1587 *
1588 * Given the weights and target after-donation hweight_inuse values, Andy's
1589 * method determines how the proportional distribution should look like at each
1590 * sibling level to maintain the relative relationship between all non-donating
1591 * pairs. To roughly summarize, it divides the tree into donating and
1592 * non-donating parts, calculates global donation rate which is used to
1593 * determine the target hweight_inuse for each node, and then derives per-level
1594 * proportions.
1595 *
1596 * The following pdf shows that global distribution calculated this way can be
1597 * achieved by scaling inuse weights of donating leaves and propagating the
1598 * adjustments upwards proportionally.
1599 *
1600 * https://drive.google.com/file/d/1vONz1-fzVO7oY5DXXsLjSxEtYYQbOvsE
1601 *
1602 * Combining the above two, we can determine how each leaf iocg's inuse should
1603 * be adjusted to achieve the target donation.
1604 *
1605 * https://drive.google.com/file/d/1WcrltBOSPN0qXVdBgnKm4mdp9FhuEFQN
1606 *
1607 * The inline comments use symbols from the last pdf.
1608 *
1609 * b is the sum of the absolute budgets in the subtree. 1 for the root node.
1610 * f is the sum of the absolute budgets of non-donating nodes in the subtree.
1611 * t is the sum of the absolute budgets of donating nodes in the subtree.
1612 * w is the weight of the node. w = w_f + w_t
1613 * w_f is the non-donating portion of w. w_f = w * f / b
1614 * w_b is the donating portion of w. w_t = w * t / b
1615 * s is the sum of all sibling weights. s = Sum(w) for siblings
1616 * s_f and s_t are the non-donating and donating portions of s.
1617 *
1618 * Subscript p denotes the parent's counterpart and ' the adjusted value - e.g.
1619 * w_pt is the donating portion of the parent's weight and w'_pt the same value
1620 * after adjustments. Subscript r denotes the root node's values.
1621 */
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001622static void transfer_surpluses(struct list_head *surpluses, struct ioc_now *now)
1623{
Tejun Heoe08d02a2020-09-01 14:52:48 -04001624 LIST_HEAD(over_hwa);
1625 LIST_HEAD(inner_walk);
1626 struct ioc_gq *iocg, *tiocg, *root_iocg;
1627 u32 after_sum, over_sum, over_target, gamma;
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001628
Tejun Heoe08d02a2020-09-01 14:52:48 -04001629 /*
1630 * It's pretty unlikely but possible for the total sum of
1631 * hweight_after_donation's to be higher than WEIGHT_ONE, which will
1632 * confuse the following calculations. If such condition is detected,
1633 * scale down everyone over its full share equally to keep the sum below
1634 * WEIGHT_ONE.
1635 */
1636 after_sum = 0;
1637 over_sum = 0;
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001638 list_for_each_entry(iocg, surpluses, surplus_list) {
Tejun Heoe08d02a2020-09-01 14:52:48 -04001639 u32 hwa;
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001640
Tejun Heoe08d02a2020-09-01 14:52:48 -04001641 current_hweight(iocg, &hwa, NULL);
1642 after_sum += iocg->hweight_after_donation;
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001643
Tejun Heoe08d02a2020-09-01 14:52:48 -04001644 if (iocg->hweight_after_donation > hwa) {
1645 over_sum += iocg->hweight_after_donation;
1646 list_add(&iocg->walk_list, &over_hwa);
1647 }
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001648 }
Tejun Heoe08d02a2020-09-01 14:52:48 -04001649
1650 if (after_sum >= WEIGHT_ONE) {
1651 /*
1652 * The delta should be deducted from the over_sum, calculate
1653 * target over_sum value.
1654 */
1655 u32 over_delta = after_sum - (WEIGHT_ONE - 1);
1656 WARN_ON_ONCE(over_sum <= over_delta);
1657 over_target = over_sum - over_delta;
1658 } else {
1659 over_target = 0;
1660 }
1661
1662 list_for_each_entry_safe(iocg, tiocg, &over_hwa, walk_list) {
1663 if (over_target)
1664 iocg->hweight_after_donation =
1665 div_u64((u64)iocg->hweight_after_donation *
1666 over_target, over_sum);
1667 list_del_init(&iocg->walk_list);
1668 }
1669
1670 /*
1671 * Build pre-order inner node walk list and prepare for donation
1672 * adjustment calculations.
1673 */
1674 list_for_each_entry(iocg, surpluses, surplus_list) {
1675 iocg_build_inner_walk(iocg, &inner_walk);
1676 }
1677
1678 root_iocg = list_first_entry(&inner_walk, struct ioc_gq, walk_list);
1679 WARN_ON_ONCE(root_iocg->level > 0);
1680
1681 list_for_each_entry(iocg, &inner_walk, walk_list) {
1682 iocg->child_adjusted_sum = 0;
1683 iocg->hweight_donating = 0;
1684 iocg->hweight_after_donation = 0;
1685 }
1686
1687 /*
1688 * Propagate the donating budget (b_t) and after donation budget (b'_t)
1689 * up the hierarchy.
1690 */
1691 list_for_each_entry(iocg, surpluses, surplus_list) {
1692 struct ioc_gq *parent = iocg->ancestors[iocg->level - 1];
1693
1694 parent->hweight_donating += iocg->hweight_donating;
1695 parent->hweight_after_donation += iocg->hweight_after_donation;
1696 }
1697
1698 list_for_each_entry_reverse(iocg, &inner_walk, walk_list) {
1699 if (iocg->level > 0) {
1700 struct ioc_gq *parent = iocg->ancestors[iocg->level - 1];
1701
1702 parent->hweight_donating += iocg->hweight_donating;
1703 parent->hweight_after_donation += iocg->hweight_after_donation;
1704 }
1705 }
1706
1707 /*
1708 * Calculate inner hwa's (b) and make sure the donation values are
1709 * within the accepted ranges as we're doing low res calculations with
1710 * roundups.
1711 */
1712 list_for_each_entry(iocg, &inner_walk, walk_list) {
1713 if (iocg->level) {
1714 struct ioc_gq *parent = iocg->ancestors[iocg->level - 1];
1715
1716 iocg->hweight_active = DIV64_U64_ROUND_UP(
1717 (u64)parent->hweight_active * iocg->active,
1718 parent->child_active_sum);
1719
1720 }
1721
1722 iocg->hweight_donating = min(iocg->hweight_donating,
1723 iocg->hweight_active);
1724 iocg->hweight_after_donation = min(iocg->hweight_after_donation,
1725 iocg->hweight_donating - 1);
1726 if (WARN_ON_ONCE(iocg->hweight_active <= 1 ||
1727 iocg->hweight_donating <= 1 ||
1728 iocg->hweight_after_donation == 0)) {
1729 pr_warn("iocg: invalid donation weights in ");
1730 pr_cont_cgroup_path(iocg_to_blkg(iocg)->blkcg->css.cgroup);
1731 pr_cont(": active=%u donating=%u after=%u\n",
1732 iocg->hweight_active, iocg->hweight_donating,
1733 iocg->hweight_after_donation);
1734 }
1735 }
1736
1737 /*
1738 * Calculate the global donation rate (gamma) - the rate to adjust
1739 * non-donating budgets by. No need to use 64bit multiplication here as
1740 * the first operand is guaranteed to be smaller than WEIGHT_ONE
1741 * (1<<16).
1742 *
1743 * gamma = (1 - t_r') / (1 - t_r)
1744 */
1745 gamma = DIV_ROUND_UP(
1746 (WEIGHT_ONE - root_iocg->hweight_after_donation) * WEIGHT_ONE,
1747 WEIGHT_ONE - root_iocg->hweight_donating);
1748
1749 /*
1750 * Calculate adjusted hwi, child_adjusted_sum and inuse for the inner
1751 * nodes.
1752 */
1753 list_for_each_entry(iocg, &inner_walk, walk_list) {
1754 struct ioc_gq *parent;
1755 u32 inuse, wpt, wptp;
1756 u64 st, sf;
1757
1758 if (iocg->level == 0) {
1759 /* adjusted weight sum for 1st level: s' = s * b_pf / b'_pf */
1760 iocg->child_adjusted_sum = DIV64_U64_ROUND_UP(
1761 iocg->child_active_sum * (WEIGHT_ONE - iocg->hweight_donating),
1762 WEIGHT_ONE - iocg->hweight_after_donation);
1763 continue;
1764 }
1765
1766 parent = iocg->ancestors[iocg->level - 1];
1767
1768 /* b' = gamma * b_f + b_t' */
1769 iocg->hweight_inuse = DIV64_U64_ROUND_UP(
1770 (u64)gamma * (iocg->hweight_active - iocg->hweight_donating),
1771 WEIGHT_ONE) + iocg->hweight_after_donation;
1772
1773 /* w' = s' * b' / b'_p */
1774 inuse = DIV64_U64_ROUND_UP(
1775 (u64)parent->child_adjusted_sum * iocg->hweight_inuse,
1776 parent->hweight_inuse);
1777
1778 /* adjusted weight sum for children: s' = s_f + s_t * w'_pt / w_pt */
1779 st = DIV64_U64_ROUND_UP(
1780 iocg->child_active_sum * iocg->hweight_donating,
1781 iocg->hweight_active);
1782 sf = iocg->child_active_sum - st;
1783 wpt = DIV64_U64_ROUND_UP(
1784 (u64)iocg->active * iocg->hweight_donating,
1785 iocg->hweight_active);
1786 wptp = DIV64_U64_ROUND_UP(
1787 (u64)inuse * iocg->hweight_after_donation,
1788 iocg->hweight_inuse);
1789
1790 iocg->child_adjusted_sum = sf + DIV64_U64_ROUND_UP(st * wptp, wpt);
1791 }
1792
1793 /*
1794 * All inner nodes now have ->hweight_inuse and ->child_adjusted_sum and
1795 * we can finally determine leaf adjustments.
1796 */
1797 list_for_each_entry(iocg, surpluses, surplus_list) {
1798 struct ioc_gq *parent = iocg->ancestors[iocg->level - 1];
1799 u32 inuse;
1800
1801 /* w' = s' * b' / b'_p, note that b' == b'_t for donating leaves */
1802 inuse = DIV64_U64_ROUND_UP(
1803 parent->child_adjusted_sum * iocg->hweight_after_donation,
1804 parent->hweight_inuse);
Tejun Heob0853ab2020-09-01 14:52:50 -04001805 __propagate_weights(iocg, iocg->active, inuse, true, now);
Tejun Heoe08d02a2020-09-01 14:52:48 -04001806 }
1807
1808 /* walk list should be dissolved after use */
1809 list_for_each_entry_safe(iocg, tiocg, &inner_walk, walk_list)
1810 list_del_init(&iocg->walk_list);
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001811}
1812
Tejun Heo7caa4712019-08-28 15:05:58 -07001813static void ioc_timer_fn(struct timer_list *timer)
1814{
1815 struct ioc *ioc = container_of(timer, struct ioc, timer);
1816 struct ioc_gq *iocg, *tiocg;
1817 struct ioc_now now;
Tejun Heo8692d2d2020-09-01 14:52:45 -04001818 LIST_HEAD(surpluses);
Tejun Heo065655c2020-09-01 14:52:46 -04001819 int nr_shortages = 0, nr_lagging = 0;
Tejun Heo7caa4712019-08-28 15:05:58 -07001820 u32 ppm_rthr = MILLION - ioc->params.qos[QOS_RPPM];
1821 u32 ppm_wthr = MILLION - ioc->params.qos[QOS_WPPM];
1822 u32 missed_ppm[2], rq_wait_pct;
1823 u64 period_vtime;
Tejun Heof1de2432020-09-01 14:52:49 -04001824 int prev_busy_level;
Tejun Heo7caa4712019-08-28 15:05:58 -07001825
1826 /* how were the latencies during the period? */
1827 ioc_lat_stat(ioc, missed_ppm, &rq_wait_pct);
1828
1829 /* take care of active iocgs */
1830 spin_lock_irq(&ioc->lock);
1831
1832 ioc_now(ioc, &now);
1833
1834 period_vtime = now.vnow - ioc->period_at_vtime;
1835 if (WARN_ON_ONCE(!period_vtime)) {
1836 spin_unlock_irq(&ioc->lock);
1837 return;
1838 }
1839
Tejun Heo97eb1972020-09-01 14:52:43 -04001840 iocg_flush_stat(&ioc->active_iocgs, &now);
1841
Tejun Heo7caa4712019-08-28 15:05:58 -07001842 /*
1843 * Waiters determine the sleep durations based on the vrate they
1844 * saw at the time of sleep. If vrate has increased, some waiters
1845 * could be sleeping for too long. Wake up tardy waiters which
1846 * should have woken up in the last period and expire idle iocgs.
1847 */
1848 list_for_each_entry_safe(iocg, tiocg, &ioc->active_iocgs, active_list) {
Chengming Zhoud9012a52020-07-30 17:03:21 +08001849 if (!waitqueue_active(&iocg->waitq) && !iocg->abs_vdebt &&
Tejun Heo0b80f982020-05-04 19:27:54 -04001850 !iocg_is_idle(iocg))
Tejun Heo7caa4712019-08-28 15:05:58 -07001851 continue;
1852
1853 spin_lock(&iocg->waitq.lock);
1854
Tejun Heo0b80f982020-05-04 19:27:54 -04001855 if (waitqueue_active(&iocg->waitq) || iocg->abs_vdebt) {
Tejun Heo7caa4712019-08-28 15:05:58 -07001856 /* might be oversleeping vtime / hweight changes, kick */
Tejun Heoda437b92020-09-01 14:52:42 -04001857 iocg_kick_waitq(iocg, true, &now);
Tejun Heo7caa4712019-08-28 15:05:58 -07001858 } else if (iocg_is_idle(iocg)) {
1859 /* no waiter and idle, deactivate */
Tejun Heob0853ab2020-09-01 14:52:50 -04001860 __propagate_weights(iocg, 0, 0, false, &now);
Tejun Heo7caa4712019-08-28 15:05:58 -07001861 list_del_init(&iocg->active_list);
1862 }
1863
1864 spin_unlock(&iocg->waitq.lock);
1865 }
Tejun Heo00410f12020-09-01 14:52:34 -04001866 commit_weights(ioc);
Tejun Heo7caa4712019-08-28 15:05:58 -07001867
Tejun Heof1de2432020-09-01 14:52:49 -04001868 /* calc usage and see whether some weights need to be moved around */
Tejun Heo7caa4712019-08-28 15:05:58 -07001869 list_for_each_entry(iocg, &ioc->active_iocgs, active_list) {
Tejun Heof1de2432020-09-01 14:52:49 -04001870 u64 vdone, vtime, usage_us, usage_dur;
1871 u32 usage, hw_active, hw_inuse;
Tejun Heo7caa4712019-08-28 15:05:58 -07001872
1873 /*
1874 * Collect unused and wind vtime closer to vnow to prevent
1875 * iocgs from accumulating a large amount of budget.
1876 */
1877 vdone = atomic64_read(&iocg->done_vtime);
1878 vtime = atomic64_read(&iocg->vtime);
1879 current_hweight(iocg, &hw_active, &hw_inuse);
1880
1881 /*
1882 * Latency QoS detection doesn't account for IOs which are
1883 * in-flight for longer than a period. Detect them by
1884 * comparing vdone against period start. If lagging behind
1885 * IOs from past periods, don't increase vrate.
1886 */
Tejun Heo7cd806a2019-09-25 16:03:09 -07001887 if ((ppm_rthr != MILLION || ppm_wthr != MILLION) &&
1888 !atomic_read(&iocg_to_blkg(iocg)->use_delay) &&
Tejun Heo7caa4712019-08-28 15:05:58 -07001889 time_after64(vtime, vdone) &&
1890 time_after64(vtime, now.vnow -
1891 MAX_LAGGING_PERIODS * period_vtime) &&
1892 time_before64(vdone, now.vnow - period_vtime))
1893 nr_lagging++;
1894
Tejun Heo7caa4712019-08-28 15:05:58 -07001895 /*
Tejun Heof1de2432020-09-01 14:52:49 -04001896 * Determine absolute usage factoring in in-flight IOs to avoid
1897 * high-latency completions appearing as idle.
Tejun Heo7caa4712019-08-28 15:05:58 -07001898 */
Tejun Heo1aa50d02020-09-01 14:52:44 -04001899 usage_us = iocg->usage_delta_us;
Tejun Heof1de2432020-09-01 14:52:49 -04001900
Tejun Heo1aa50d02020-09-01 14:52:44 -04001901 if (vdone != vtime) {
1902 u64 inflight_us = DIV64_U64_ROUND_UP(
1903 cost_to_abs_cost(vtime - vdone, hw_inuse),
1904 now.vrate);
1905 usage_us = max(usage_us, inflight_us);
1906 }
Tejun Heo7caa4712019-08-28 15:05:58 -07001907
Tejun Heof1de2432020-09-01 14:52:49 -04001908 /* convert to hweight based usage ratio */
1909 if (time_after64(iocg->activated_at, ioc->period_at))
1910 usage_dur = max_t(u64, now.now - iocg->activated_at, 1);
1911 else
1912 usage_dur = max_t(u64, now.now - ioc->period_at, 1);
Tejun Heo1aa50d02020-09-01 14:52:44 -04001913
Tejun Heof1de2432020-09-01 14:52:49 -04001914 usage = clamp_t(u32,
1915 DIV64_U64_ROUND_UP(usage_us * WEIGHT_ONE,
1916 usage_dur),
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001917 1, WEIGHT_ONE);
Tejun Heo7caa4712019-08-28 15:05:58 -07001918
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001919 /* see whether there's surplus vtime */
1920 WARN_ON_ONCE(!list_empty(&iocg->surplus_list));
1921 if (hw_inuse < hw_active ||
1922 (!waitqueue_active(&iocg->waitq) &&
Tejun Heof1de2432020-09-01 14:52:49 -04001923 time_before64(vtime, now.vnow - ioc->margins.low))) {
Tejun Heoe08d02a2020-09-01 14:52:48 -04001924 u32 hwa, hwm, new_hwi;
Tejun Heo7caa4712019-08-28 15:05:58 -07001925
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001926 /*
1927 * Already donating or accumulated enough to start.
1928 * Determine the donation amount.
1929 */
Tejun Heoe08d02a2020-09-01 14:52:48 -04001930 current_hweight(iocg, &hwa, NULL);
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001931 hwm = current_hweight_max(iocg);
1932 new_hwi = hweight_after_donation(iocg, hwm, usage,
1933 &now);
1934 if (new_hwi < hwm) {
Tejun Heoe08d02a2020-09-01 14:52:48 -04001935 iocg->hweight_donating = hwa;
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001936 iocg->hweight_after_donation = new_hwi;
1937 list_add(&iocg->surplus_list, &surpluses);
1938 } else {
1939 __propagate_weights(iocg, iocg->active,
Tejun Heob0853ab2020-09-01 14:52:50 -04001940 iocg->active, true, &now);
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001941 nr_shortages++;
1942 }
1943 } else {
1944 /* genuinely short on vtime */
1945 nr_shortages++;
Tejun Heo7caa4712019-08-28 15:05:58 -07001946 }
1947 }
Tejun Heo93f7d2d2020-09-01 14:52:47 -04001948
1949 if (!list_empty(&surpluses) && nr_shortages)
1950 transfer_surpluses(&surpluses, &now);
1951
Tejun Heo00410f12020-09-01 14:52:34 -04001952 commit_weights(ioc);
Tejun Heo7caa4712019-08-28 15:05:58 -07001953
Tejun Heo8692d2d2020-09-01 14:52:45 -04001954 /* surplus list should be dissolved after use */
1955 list_for_each_entry_safe(iocg, tiocg, &surpluses, surplus_list)
1956 list_del_init(&iocg->surplus_list);
1957
Tejun Heo7caa4712019-08-28 15:05:58 -07001958 /*
1959 * If q is getting clogged or we're missing too much, we're issuing
1960 * too much IO and should lower vtime rate. If we're not missing
1961 * and experiencing shortages but not surpluses, we're too stingy
1962 * and should increase vtime rate.
1963 */
Tejun Heo25d41e42019-09-25 16:02:07 -07001964 prev_busy_level = ioc->busy_level;
Tejun Heo7caa4712019-08-28 15:05:58 -07001965 if (rq_wait_pct > RQ_WAIT_BUSY_PCT ||
1966 missed_ppm[READ] > ppm_rthr ||
1967 missed_ppm[WRITE] > ppm_wthr) {
Tejun Heo81ca6272019-10-14 17:18:11 -07001968 /* clearly missing QoS targets, slow down vrate */
Tejun Heo7caa4712019-08-28 15:05:58 -07001969 ioc->busy_level = max(ioc->busy_level, 0);
1970 ioc->busy_level++;
Tejun Heo7cd806a2019-09-25 16:03:09 -07001971 } else if (rq_wait_pct <= RQ_WAIT_BUSY_PCT * UNBUSY_THR_PCT / 100 &&
Tejun Heo7caa4712019-08-28 15:05:58 -07001972 missed_ppm[READ] <= ppm_rthr * UNBUSY_THR_PCT / 100 &&
1973 missed_ppm[WRITE] <= ppm_wthr * UNBUSY_THR_PCT / 100) {
Tejun Heo81ca6272019-10-14 17:18:11 -07001974 /* QoS targets are being met with >25% margin */
1975 if (nr_shortages) {
1976 /*
1977 * We're throttling while the device has spare
1978 * capacity. If vrate was being slowed down, stop.
1979 */
Tejun Heo7cd806a2019-09-25 16:03:09 -07001980 ioc->busy_level = min(ioc->busy_level, 0);
Tejun Heo81ca6272019-10-14 17:18:11 -07001981
1982 /*
1983 * If there are IOs spanning multiple periods, wait
Tejun Heo065655c2020-09-01 14:52:46 -04001984 * them out before pushing the device harder.
Tejun Heo81ca6272019-10-14 17:18:11 -07001985 */
Tejun Heo065655c2020-09-01 14:52:46 -04001986 if (!nr_lagging)
Tejun Heo7cd806a2019-09-25 16:03:09 -07001987 ioc->busy_level--;
Tejun Heo81ca6272019-10-14 17:18:11 -07001988 } else {
1989 /*
1990 * Nobody is being throttled and the users aren't
1991 * issuing enough IOs to saturate the device. We
1992 * simply don't know how close the device is to
1993 * saturation. Coast.
1994 */
1995 ioc->busy_level = 0;
Tejun Heo7cd806a2019-09-25 16:03:09 -07001996 }
Tejun Heo7caa4712019-08-28 15:05:58 -07001997 } else {
Tejun Heo81ca6272019-10-14 17:18:11 -07001998 /* inside the hysterisis margin, we're good */
Tejun Heo7caa4712019-08-28 15:05:58 -07001999 ioc->busy_level = 0;
2000 }
2001
2002 ioc->busy_level = clamp(ioc->busy_level, -1000, 1000);
2003
Tejun Heo7cd806a2019-09-25 16:03:09 -07002004 if (ioc->busy_level > 0 || (ioc->busy_level < 0 && !nr_lagging)) {
Tejun Heo7caa4712019-08-28 15:05:58 -07002005 u64 vrate = atomic64_read(&ioc->vtime_rate);
2006 u64 vrate_min = ioc->vrate_min, vrate_max = ioc->vrate_max;
2007
2008 /* rq_wait signal is always reliable, ignore user vrate_min */
2009 if (rq_wait_pct > RQ_WAIT_BUSY_PCT)
2010 vrate_min = VRATE_MIN;
2011
2012 /*
2013 * If vrate is out of bounds, apply clamp gradually as the
2014 * bounds can change abruptly. Otherwise, apply busy_level
2015 * based adjustment.
2016 */
2017 if (vrate < vrate_min) {
2018 vrate = div64_u64(vrate * (100 + VRATE_CLAMP_ADJ_PCT),
2019 100);
2020 vrate = min(vrate, vrate_min);
2021 } else if (vrate > vrate_max) {
2022 vrate = div64_u64(vrate * (100 - VRATE_CLAMP_ADJ_PCT),
2023 100);
2024 vrate = max(vrate, vrate_max);
2025 } else {
2026 int idx = min_t(int, abs(ioc->busy_level),
2027 ARRAY_SIZE(vrate_adj_pct) - 1);
2028 u32 adj_pct = vrate_adj_pct[idx];
2029
2030 if (ioc->busy_level > 0)
2031 adj_pct = 100 - adj_pct;
2032 else
2033 adj_pct = 100 + adj_pct;
2034
2035 vrate = clamp(DIV64_U64_ROUND_UP(vrate * adj_pct, 100),
2036 vrate_min, vrate_max);
2037 }
2038
Waiman Longd6c8e942020-04-21 09:07:55 -04002039 trace_iocost_ioc_vrate_adj(ioc, vrate, missed_ppm, rq_wait_pct,
Tejun Heo065655c2020-09-01 14:52:46 -04002040 nr_lagging, nr_shortages);
Tejun Heo7caa4712019-08-28 15:05:58 -07002041
2042 atomic64_set(&ioc->vtime_rate, vrate);
Tejun Heo7ca5b2e2020-09-01 14:52:41 -04002043 ioc_refresh_margins(ioc);
Tejun Heo25d41e42019-09-25 16:02:07 -07002044 } else if (ioc->busy_level != prev_busy_level || nr_lagging) {
2045 trace_iocost_ioc_vrate_adj(ioc, atomic64_read(&ioc->vtime_rate),
Waiman Longd6c8e942020-04-21 09:07:55 -04002046 missed_ppm, rq_wait_pct, nr_lagging,
Tejun Heo065655c2020-09-01 14:52:46 -04002047 nr_shortages);
Tejun Heo7caa4712019-08-28 15:05:58 -07002048 }
2049
2050 ioc_refresh_params(ioc, false);
2051
2052 /*
2053 * This period is done. Move onto the next one. If nothing's
2054 * going on with the device, stop the timer.
2055 */
2056 atomic64_inc(&ioc->cur_period);
2057
2058 if (ioc->running != IOC_STOP) {
2059 if (!list_empty(&ioc->active_iocgs)) {
2060 ioc_start_period(ioc, &now);
2061 } else {
2062 ioc->busy_level = 0;
2063 ioc->running = IOC_IDLE;
2064 }
2065 }
2066
2067 spin_unlock_irq(&ioc->lock);
2068}
2069
Tejun Heob0853ab2020-09-01 14:52:50 -04002070static u64 adjust_inuse_and_calc_cost(struct ioc_gq *iocg, u64 vtime,
2071 u64 abs_cost, struct ioc_now *now)
2072{
2073 struct ioc *ioc = iocg->ioc;
2074 struct ioc_margins *margins = &ioc->margins;
2075 u32 adj_step = DIV_ROUND_UP(iocg->active * INUSE_ADJ_STEP_PCT, 100);
2076 u32 hwi;
2077 s64 margin;
2078 u64 cost, new_inuse;
2079
2080 current_hweight(iocg, NULL, &hwi);
2081 cost = abs_cost_to_cost(abs_cost, hwi);
2082 margin = now->vnow - vtime - cost;
2083
2084 /*
2085 * We only increase inuse during period and do so iff the margin has
2086 * deteriorated since the previous adjustment.
2087 */
2088 if (margin >= iocg->saved_margin || margin >= margins->low ||
2089 iocg->inuse == iocg->active)
2090 return cost;
2091
2092 spin_lock_irq(&ioc->lock);
2093
2094 /* we own inuse only when @iocg is in the normal active state */
2095 if (list_empty(&iocg->active_list)) {
2096 spin_unlock_irq(&ioc->lock);
2097 return cost;
2098 }
2099
2100 /* bump up inuse till @abs_cost fits in the existing budget */
2101 new_inuse = iocg->inuse;
2102 do {
2103 new_inuse = new_inuse + adj_step;
2104 propagate_weights(iocg, iocg->active, new_inuse, true, now);
2105 current_hweight(iocg, NULL, &hwi);
2106 cost = abs_cost_to_cost(abs_cost, hwi);
2107 } while (time_after64(vtime + cost, now->vnow) &&
2108 iocg->inuse != iocg->active);
2109
2110 spin_unlock_irq(&ioc->lock);
2111 return cost;
2112}
2113
Tejun Heo7caa4712019-08-28 15:05:58 -07002114static void calc_vtime_cost_builtin(struct bio *bio, struct ioc_gq *iocg,
2115 bool is_merge, u64 *costp)
2116{
2117 struct ioc *ioc = iocg->ioc;
2118 u64 coef_seqio, coef_randio, coef_page;
2119 u64 pages = max_t(u64, bio_sectors(bio) >> IOC_SECT_TO_PAGE_SHIFT, 1);
2120 u64 seek_pages = 0;
2121 u64 cost = 0;
2122
2123 switch (bio_op(bio)) {
2124 case REQ_OP_READ:
2125 coef_seqio = ioc->params.lcoefs[LCOEF_RSEQIO];
2126 coef_randio = ioc->params.lcoefs[LCOEF_RRANDIO];
2127 coef_page = ioc->params.lcoefs[LCOEF_RPAGE];
2128 break;
2129 case REQ_OP_WRITE:
2130 coef_seqio = ioc->params.lcoefs[LCOEF_WSEQIO];
2131 coef_randio = ioc->params.lcoefs[LCOEF_WRANDIO];
2132 coef_page = ioc->params.lcoefs[LCOEF_WPAGE];
2133 break;
2134 default:
2135 goto out;
2136 }
2137
2138 if (iocg->cursor) {
2139 seek_pages = abs(bio->bi_iter.bi_sector - iocg->cursor);
2140 seek_pages >>= IOC_SECT_TO_PAGE_SHIFT;
2141 }
2142
2143 if (!is_merge) {
2144 if (seek_pages > LCOEF_RANDIO_PAGES) {
2145 cost += coef_randio;
2146 } else {
2147 cost += coef_seqio;
2148 }
2149 }
2150 cost += pages * coef_page;
2151out:
2152 *costp = cost;
2153}
2154
2155static u64 calc_vtime_cost(struct bio *bio, struct ioc_gq *iocg, bool is_merge)
2156{
2157 u64 cost;
2158
2159 calc_vtime_cost_builtin(bio, iocg, is_merge, &cost);
2160 return cost;
2161}
2162
Tejun Heocd006502020-04-13 12:27:56 -04002163static void calc_size_vtime_cost_builtin(struct request *rq, struct ioc *ioc,
2164 u64 *costp)
2165{
2166 unsigned int pages = blk_rq_stats_sectors(rq) >> IOC_SECT_TO_PAGE_SHIFT;
2167
2168 switch (req_op(rq)) {
2169 case REQ_OP_READ:
2170 *costp = pages * ioc->params.lcoefs[LCOEF_RPAGE];
2171 break;
2172 case REQ_OP_WRITE:
2173 *costp = pages * ioc->params.lcoefs[LCOEF_WPAGE];
2174 break;
2175 default:
2176 *costp = 0;
2177 }
2178}
2179
2180static u64 calc_size_vtime_cost(struct request *rq, struct ioc *ioc)
2181{
2182 u64 cost;
2183
2184 calc_size_vtime_cost_builtin(rq, ioc, &cost);
2185 return cost;
2186}
2187
Tejun Heo7caa4712019-08-28 15:05:58 -07002188static void ioc_rqos_throttle(struct rq_qos *rqos, struct bio *bio)
2189{
2190 struct blkcg_gq *blkg = bio->bi_blkg;
2191 struct ioc *ioc = rqos_to_ioc(rqos);
2192 struct ioc_gq *iocg = blkg_to_iocg(blkg);
2193 struct ioc_now now;
2194 struct iocg_wait wait;
Tejun Heo7caa4712019-08-28 15:05:58 -07002195 u64 abs_cost, cost, vtime;
Tejun Heoda437b92020-09-01 14:52:42 -04002196 bool use_debt, ioc_locked;
2197 unsigned long flags;
Tejun Heo7caa4712019-08-28 15:05:58 -07002198
2199 /* bypass IOs if disabled or for root cgroup */
2200 if (!ioc->enabled || !iocg->level)
2201 return;
2202
Tejun Heo7caa4712019-08-28 15:05:58 -07002203 /* calculate the absolute vtime cost */
2204 abs_cost = calc_vtime_cost(bio, iocg, false);
2205 if (!abs_cost)
2206 return;
2207
Tejun Heof1de2432020-09-01 14:52:49 -04002208 if (!iocg_activate(iocg, &now))
2209 return;
2210
Tejun Heo7caa4712019-08-28 15:05:58 -07002211 iocg->cursor = bio_end_sector(bio);
Tejun Heo7caa4712019-08-28 15:05:58 -07002212 vtime = atomic64_read(&iocg->vtime);
Tejun Heob0853ab2020-09-01 14:52:50 -04002213 cost = adjust_inuse_and_calc_cost(iocg, vtime, abs_cost, &now);
Tejun Heo7caa4712019-08-28 15:05:58 -07002214
2215 /*
2216 * If no one's waiting and within budget, issue right away. The
2217 * tests are racy but the races aren't systemic - we only miss once
2218 * in a while which is fine.
2219 */
Tejun Heo0b80f982020-05-04 19:27:54 -04002220 if (!waitqueue_active(&iocg->waitq) && !iocg->abs_vdebt &&
Tejun Heo7caa4712019-08-28 15:05:58 -07002221 time_before_eq64(vtime + cost, now.vnow)) {
Tejun Heo97eb1972020-09-01 14:52:43 -04002222 iocg_commit_bio(iocg, bio, abs_cost, cost);
Tejun Heo7caa4712019-08-28 15:05:58 -07002223 return;
2224 }
2225
Tejun Heo36a52482019-09-04 12:45:52 -07002226 /*
Tejun Heoda437b92020-09-01 14:52:42 -04002227 * We're over budget. This can be handled in two ways. IOs which may
2228 * cause priority inversions are punted to @ioc->aux_iocg and charged as
2229 * debt. Otherwise, the issuer is blocked on @iocg->waitq. Debt handling
2230 * requires @ioc->lock, waitq handling @iocg->waitq.lock. Determine
2231 * whether debt handling is needed and acquire locks accordingly.
Tejun Heo0b80f982020-05-04 19:27:54 -04002232 */
Tejun Heoda437b92020-09-01 14:52:42 -04002233 use_debt = bio_issue_as_root_blkg(bio) || fatal_signal_pending(current);
2234 ioc_locked = use_debt || READ_ONCE(iocg->abs_vdebt);
Tejun Heob0853ab2020-09-01 14:52:50 -04002235retry_lock:
Tejun Heoda437b92020-09-01 14:52:42 -04002236 iocg_lock(iocg, ioc_locked, &flags);
2237
2238 /*
2239 * @iocg must stay activated for debt and waitq handling. Deactivation
2240 * is synchronized against both ioc->lock and waitq.lock and we won't
2241 * get deactivated as long as we're waiting or has debt, so we're good
2242 * if we're activated here. In the unlikely cases that we aren't, just
2243 * issue the IO.
2244 */
Tejun Heo0b80f982020-05-04 19:27:54 -04002245 if (unlikely(list_empty(&iocg->active_list))) {
Tejun Heoda437b92020-09-01 14:52:42 -04002246 iocg_unlock(iocg, ioc_locked, &flags);
Tejun Heo97eb1972020-09-01 14:52:43 -04002247 iocg_commit_bio(iocg, bio, abs_cost, cost);
Tejun Heo0b80f982020-05-04 19:27:54 -04002248 return;
2249 }
2250
2251 /*
2252 * We're over budget. If @bio has to be issued regardless, remember
2253 * the abs_cost instead of advancing vtime. iocg_kick_waitq() will pay
2254 * off the debt before waking more IOs.
2255 *
Tejun Heo36a52482019-09-04 12:45:52 -07002256 * This way, the debt is continuously paid off each period with the
Tejun Heo0b80f982020-05-04 19:27:54 -04002257 * actual budget available to the cgroup. If we just wound vtime, we
2258 * would incorrectly use the current hw_inuse for the entire amount
2259 * which, for example, can lead to the cgroup staying blocked for a
2260 * long time even with substantially raised hw_inuse.
2261 *
2262 * An iocg with vdebt should stay online so that the timer can keep
2263 * deducting its vdebt and [de]activate use_delay mechanism
2264 * accordingly. We don't want to race against the timer trying to
2265 * clear them and leave @iocg inactive w/ dangling use_delay heavily
2266 * penalizing the cgroup and its descendants.
Tejun Heo36a52482019-09-04 12:45:52 -07002267 */
Tejun Heoda437b92020-09-01 14:52:42 -04002268 if (use_debt) {
Tejun Heo0b80f982020-05-04 19:27:54 -04002269 iocg->abs_vdebt += abs_cost;
Tejun Heo54c52e12020-04-13 12:27:55 -04002270 if (iocg_kick_delay(iocg, &now))
Tejun Heod7bd15a2019-12-16 13:34:00 -08002271 blkcg_schedule_throttle(rqos->q,
2272 (bio->bi_opf & REQ_SWAP) == REQ_SWAP);
Tejun Heoda437b92020-09-01 14:52:42 -04002273 iocg_unlock(iocg, ioc_locked, &flags);
Tejun Heo7caa4712019-08-28 15:05:58 -07002274 return;
2275 }
2276
Tejun Heob0853ab2020-09-01 14:52:50 -04002277 /* guarantee that iocgs w/ waiters have maximum inuse */
2278 if (iocg->inuse != iocg->active) {
2279 if (!ioc_locked) {
2280 iocg_unlock(iocg, false, &flags);
2281 ioc_locked = true;
2282 goto retry_lock;
2283 }
2284 propagate_weights(iocg, iocg->active, iocg->active, true,
2285 &now);
2286 }
2287
Tejun Heo7caa4712019-08-28 15:05:58 -07002288 /*
2289 * Append self to the waitq and schedule the wakeup timer if we're
2290 * the first waiter. The timer duration is calculated based on the
2291 * current vrate. vtime and hweight changes can make it too short
2292 * or too long. Each wait entry records the absolute cost it's
2293 * waiting for to allow re-evaluation using a custom wait entry.
2294 *
2295 * If too short, the timer simply reschedules itself. If too long,
2296 * the period timer will notice and trigger wakeups.
2297 *
2298 * All waiters are on iocg->waitq and the wait states are
2299 * synchronized using waitq.lock.
2300 */
Tejun Heo7caa4712019-08-28 15:05:58 -07002301 init_waitqueue_func_entry(&wait.wait, iocg_wake_fn);
2302 wait.wait.private = current;
2303 wait.bio = bio;
2304 wait.abs_cost = abs_cost;
2305 wait.committed = false; /* will be set true by waker */
2306
2307 __add_wait_queue_entry_tail(&iocg->waitq, &wait.wait);
Tejun Heoda437b92020-09-01 14:52:42 -04002308 iocg_kick_waitq(iocg, ioc_locked, &now);
Tejun Heo7caa4712019-08-28 15:05:58 -07002309
Tejun Heoda437b92020-09-01 14:52:42 -04002310 iocg_unlock(iocg, ioc_locked, &flags);
Tejun Heo7caa4712019-08-28 15:05:58 -07002311
2312 while (true) {
2313 set_current_state(TASK_UNINTERRUPTIBLE);
2314 if (wait.committed)
2315 break;
2316 io_schedule();
2317 }
2318
2319 /* waker already committed us, proceed */
2320 finish_wait(&iocg->waitq, &wait.wait);
2321}
2322
2323static void ioc_rqos_merge(struct rq_qos *rqos, struct request *rq,
2324 struct bio *bio)
2325{
2326 struct ioc_gq *iocg = blkg_to_iocg(bio->bi_blkg);
Tejun Heoe1518f62019-09-04 12:45:53 -07002327 struct ioc *ioc = iocg->ioc;
Tejun Heo7caa4712019-08-28 15:05:58 -07002328 sector_t bio_end = bio_end_sector(bio);
Tejun Heoe1518f62019-09-04 12:45:53 -07002329 struct ioc_now now;
Tejun Heob0853ab2020-09-01 14:52:50 -04002330 u64 vtime, abs_cost, cost;
Tejun Heo0b80f982020-05-04 19:27:54 -04002331 unsigned long flags;
Tejun Heo7caa4712019-08-28 15:05:58 -07002332
Tejun Heoe1518f62019-09-04 12:45:53 -07002333 /* bypass if disabled or for root cgroup */
2334 if (!ioc->enabled || !iocg->level)
Tejun Heo7caa4712019-08-28 15:05:58 -07002335 return;
2336
2337 abs_cost = calc_vtime_cost(bio, iocg, true);
2338 if (!abs_cost)
2339 return;
2340
Tejun Heoe1518f62019-09-04 12:45:53 -07002341 ioc_now(ioc, &now);
Tejun Heob0853ab2020-09-01 14:52:50 -04002342
2343 vtime = atomic64_read(&iocg->vtime);
2344 cost = adjust_inuse_and_calc_cost(iocg, vtime, abs_cost, &now);
Tejun Heoe1518f62019-09-04 12:45:53 -07002345
Tejun Heo7caa4712019-08-28 15:05:58 -07002346 /* update cursor if backmerging into the request at the cursor */
2347 if (blk_rq_pos(rq) < bio_end &&
2348 blk_rq_pos(rq) + blk_rq_sectors(rq) == iocg->cursor)
2349 iocg->cursor = bio_end;
2350
Tejun Heoe1518f62019-09-04 12:45:53 -07002351 /*
Tejun Heo0b80f982020-05-04 19:27:54 -04002352 * Charge if there's enough vtime budget and the existing request has
2353 * cost assigned.
Tejun Heoe1518f62019-09-04 12:45:53 -07002354 */
2355 if (rq->bio && rq->bio->bi_iocost_cost &&
Tejun Heo0b80f982020-05-04 19:27:54 -04002356 time_before_eq64(atomic64_read(&iocg->vtime) + cost, now.vnow)) {
Tejun Heo97eb1972020-09-01 14:52:43 -04002357 iocg_commit_bio(iocg, bio, abs_cost, cost);
Tejun Heo0b80f982020-05-04 19:27:54 -04002358 return;
2359 }
2360
2361 /*
2362 * Otherwise, account it as debt if @iocg is online, which it should
2363 * be for the vast majority of cases. See debt handling in
2364 * ioc_rqos_throttle() for details.
2365 */
2366 spin_lock_irqsave(&iocg->waitq.lock, flags);
2367 if (likely(!list_empty(&iocg->active_list))) {
2368 iocg->abs_vdebt += abs_cost;
Jens Axboe873f1c82020-05-09 16:13:58 -06002369 iocg_kick_delay(iocg, &now);
Tejun Heo0b80f982020-05-04 19:27:54 -04002370 } else {
Tejun Heo97eb1972020-09-01 14:52:43 -04002371 iocg_commit_bio(iocg, bio, abs_cost, cost);
Tejun Heo0b80f982020-05-04 19:27:54 -04002372 }
2373 spin_unlock_irqrestore(&iocg->waitq.lock, flags);
Tejun Heo7caa4712019-08-28 15:05:58 -07002374}
2375
2376static void ioc_rqos_done_bio(struct rq_qos *rqos, struct bio *bio)
2377{
2378 struct ioc_gq *iocg = blkg_to_iocg(bio->bi_blkg);
2379
2380 if (iocg && bio->bi_iocost_cost)
2381 atomic64_add(bio->bi_iocost_cost, &iocg->done_vtime);
2382}
2383
2384static void ioc_rqos_done(struct rq_qos *rqos, struct request *rq)
2385{
2386 struct ioc *ioc = rqos_to_ioc(rqos);
Tejun Heo5e124f72020-09-01 14:52:33 -04002387 struct ioc_pcpu_stat *ccs;
Tejun Heocd006502020-04-13 12:27:56 -04002388 u64 on_q_ns, rq_wait_ns, size_nsec;
Tejun Heo7caa4712019-08-28 15:05:58 -07002389 int pidx, rw;
2390
2391 if (!ioc->enabled || !rq->alloc_time_ns || !rq->start_time_ns)
2392 return;
2393
2394 switch (req_op(rq) & REQ_OP_MASK) {
2395 case REQ_OP_READ:
2396 pidx = QOS_RLAT;
2397 rw = READ;
2398 break;
2399 case REQ_OP_WRITE:
2400 pidx = QOS_WLAT;
2401 rw = WRITE;
2402 break;
2403 default:
2404 return;
2405 }
2406
2407 on_q_ns = ktime_get_ns() - rq->alloc_time_ns;
2408 rq_wait_ns = rq->start_time_ns - rq->alloc_time_ns;
Tejun Heocd006502020-04-13 12:27:56 -04002409 size_nsec = div64_u64(calc_size_vtime_cost(rq, ioc), VTIME_PER_NSEC);
Tejun Heo7caa4712019-08-28 15:05:58 -07002410
Tejun Heo5e124f72020-09-01 14:52:33 -04002411 ccs = get_cpu_ptr(ioc->pcpu_stat);
2412
Tejun Heocd006502020-04-13 12:27:56 -04002413 if (on_q_ns <= size_nsec ||
2414 on_q_ns - size_nsec <= ioc->params.qos[pidx] * NSEC_PER_USEC)
Tejun Heo5e124f72020-09-01 14:52:33 -04002415 local_inc(&ccs->missed[rw].nr_met);
Tejun Heo7caa4712019-08-28 15:05:58 -07002416 else
Tejun Heo5e124f72020-09-01 14:52:33 -04002417 local_inc(&ccs->missed[rw].nr_missed);
Tejun Heo7caa4712019-08-28 15:05:58 -07002418
Tejun Heo5e124f72020-09-01 14:52:33 -04002419 local64_add(rq_wait_ns, &ccs->rq_wait_ns);
2420
2421 put_cpu_ptr(ccs);
Tejun Heo7caa4712019-08-28 15:05:58 -07002422}
2423
2424static void ioc_rqos_queue_depth_changed(struct rq_qos *rqos)
2425{
2426 struct ioc *ioc = rqos_to_ioc(rqos);
2427
2428 spin_lock_irq(&ioc->lock);
2429 ioc_refresh_params(ioc, false);
2430 spin_unlock_irq(&ioc->lock);
2431}
2432
2433static void ioc_rqos_exit(struct rq_qos *rqos)
2434{
2435 struct ioc *ioc = rqos_to_ioc(rqos);
2436
2437 blkcg_deactivate_policy(rqos->q, &blkcg_policy_iocost);
2438
2439 spin_lock_irq(&ioc->lock);
2440 ioc->running = IOC_STOP;
2441 spin_unlock_irq(&ioc->lock);
2442
2443 del_timer_sync(&ioc->timer);
2444 free_percpu(ioc->pcpu_stat);
2445 kfree(ioc);
2446}
2447
2448static struct rq_qos_ops ioc_rqos_ops = {
2449 .throttle = ioc_rqos_throttle,
2450 .merge = ioc_rqos_merge,
2451 .done_bio = ioc_rqos_done_bio,
2452 .done = ioc_rqos_done,
2453 .queue_depth_changed = ioc_rqos_queue_depth_changed,
2454 .exit = ioc_rqos_exit,
2455};
2456
2457static int blk_iocost_init(struct request_queue *q)
2458{
2459 struct ioc *ioc;
2460 struct rq_qos *rqos;
Tejun Heo5e124f72020-09-01 14:52:33 -04002461 int i, cpu, ret;
Tejun Heo7caa4712019-08-28 15:05:58 -07002462
2463 ioc = kzalloc(sizeof(*ioc), GFP_KERNEL);
2464 if (!ioc)
2465 return -ENOMEM;
2466
2467 ioc->pcpu_stat = alloc_percpu(struct ioc_pcpu_stat);
2468 if (!ioc->pcpu_stat) {
2469 kfree(ioc);
2470 return -ENOMEM;
2471 }
2472
Tejun Heo5e124f72020-09-01 14:52:33 -04002473 for_each_possible_cpu(cpu) {
2474 struct ioc_pcpu_stat *ccs = per_cpu_ptr(ioc->pcpu_stat, cpu);
2475
2476 for (i = 0; i < ARRAY_SIZE(ccs->missed); i++) {
2477 local_set(&ccs->missed[i].nr_met, 0);
2478 local_set(&ccs->missed[i].nr_missed, 0);
2479 }
2480 local64_set(&ccs->rq_wait_ns, 0);
2481 }
2482
Tejun Heo7caa4712019-08-28 15:05:58 -07002483 rqos = &ioc->rqos;
2484 rqos->id = RQ_QOS_COST;
2485 rqos->ops = &ioc_rqos_ops;
2486 rqos->q = q;
2487
2488 spin_lock_init(&ioc->lock);
2489 timer_setup(&ioc->timer, ioc_timer_fn, 0);
2490 INIT_LIST_HEAD(&ioc->active_iocgs);
2491
2492 ioc->running = IOC_IDLE;
2493 atomic64_set(&ioc->vtime_rate, VTIME_PER_USEC);
Ahmed S. Darwish67b7b642020-07-20 17:55:26 +02002494 seqcount_spinlock_init(&ioc->period_seqcount, &ioc->lock);
Tejun Heo7caa4712019-08-28 15:05:58 -07002495 ioc->period_at = ktime_to_us(ktime_get());
2496 atomic64_set(&ioc->cur_period, 0);
2497 atomic_set(&ioc->hweight_gen, 0);
2498
2499 spin_lock_irq(&ioc->lock);
2500 ioc->autop_idx = AUTOP_INVALID;
2501 ioc_refresh_params(ioc, true);
2502 spin_unlock_irq(&ioc->lock);
2503
2504 rq_qos_add(q, rqos);
2505 ret = blkcg_activate_policy(q, &blkcg_policy_iocost);
2506 if (ret) {
2507 rq_qos_del(q, rqos);
Tejun Heo3532e722019-08-29 08:53:06 -07002508 free_percpu(ioc->pcpu_stat);
Tejun Heo7caa4712019-08-28 15:05:58 -07002509 kfree(ioc);
2510 return ret;
2511 }
2512 return 0;
2513}
2514
2515static struct blkcg_policy_data *ioc_cpd_alloc(gfp_t gfp)
2516{
2517 struct ioc_cgrp *iocc;
2518
2519 iocc = kzalloc(sizeof(struct ioc_cgrp), gfp);
Tejun Heoe916ad22019-08-30 06:10:58 -07002520 if (!iocc)
2521 return NULL;
Tejun Heo7caa4712019-08-28 15:05:58 -07002522
Tejun Heobd0adb92020-09-01 14:52:39 -04002523 iocc->dfl_weight = CGROUP_WEIGHT_DFL * WEIGHT_ONE;
Tejun Heo7caa4712019-08-28 15:05:58 -07002524 return &iocc->cpd;
2525}
2526
2527static void ioc_cpd_free(struct blkcg_policy_data *cpd)
2528{
2529 kfree(container_of(cpd, struct ioc_cgrp, cpd));
2530}
2531
2532static struct blkg_policy_data *ioc_pd_alloc(gfp_t gfp, struct request_queue *q,
2533 struct blkcg *blkcg)
2534{
2535 int levels = blkcg->css.cgroup->level + 1;
2536 struct ioc_gq *iocg;
2537
Gustavo A. R. Silvaf61d6e22020-06-19 18:08:30 -05002538 iocg = kzalloc_node(struct_size(iocg, ancestors, levels), gfp, q->node);
Tejun Heo7caa4712019-08-28 15:05:58 -07002539 if (!iocg)
2540 return NULL;
2541
Tejun Heo97eb1972020-09-01 14:52:43 -04002542 iocg->pcpu_stat = alloc_percpu_gfp(struct iocg_pcpu_stat, gfp);
2543 if (!iocg->pcpu_stat) {
2544 kfree(iocg);
2545 return NULL;
2546 }
2547
Tejun Heo7caa4712019-08-28 15:05:58 -07002548 return &iocg->pd;
2549}
2550
2551static void ioc_pd_init(struct blkg_policy_data *pd)
2552{
2553 struct ioc_gq *iocg = pd_to_iocg(pd);
2554 struct blkcg_gq *blkg = pd_to_blkg(&iocg->pd);
2555 struct ioc *ioc = q_to_ioc(blkg->q);
2556 struct ioc_now now;
2557 struct blkcg_gq *tblkg;
2558 unsigned long flags;
2559
2560 ioc_now(ioc, &now);
2561
2562 iocg->ioc = ioc;
2563 atomic64_set(&iocg->vtime, now.vnow);
2564 atomic64_set(&iocg->done_vtime, now.vnow);
2565 atomic64_set(&iocg->active_period, atomic64_read(&ioc->cur_period));
2566 INIT_LIST_HEAD(&iocg->active_list);
Tejun Heo97eb1972020-09-01 14:52:43 -04002567 INIT_LIST_HEAD(&iocg->walk_list);
Tejun Heo8692d2d2020-09-01 14:52:45 -04002568 INIT_LIST_HEAD(&iocg->surplus_list);
Tejun Heofe20cdb52020-09-01 14:52:38 -04002569 iocg->hweight_active = WEIGHT_ONE;
2570 iocg->hweight_inuse = WEIGHT_ONE;
Tejun Heo7caa4712019-08-28 15:05:58 -07002571
2572 init_waitqueue_head(&iocg->waitq);
2573 hrtimer_init(&iocg->waitq_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
2574 iocg->waitq_timer.function = iocg_waitq_timer_fn;
2575 hrtimer_init(&iocg->delay_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
2576 iocg->delay_timer.function = iocg_delay_timer_fn;
2577
2578 iocg->level = blkg->blkcg->css.cgroup->level;
2579
2580 for (tblkg = blkg; tblkg; tblkg = tblkg->parent) {
2581 struct ioc_gq *tiocg = blkg_to_iocg(tblkg);
2582 iocg->ancestors[tiocg->level] = tiocg;
2583 }
2584
2585 spin_lock_irqsave(&ioc->lock, flags);
Tejun Heob0853ab2020-09-01 14:52:50 -04002586 weight_updated(iocg, &now);
Tejun Heo7caa4712019-08-28 15:05:58 -07002587 spin_unlock_irqrestore(&ioc->lock, flags);
2588}
2589
2590static void ioc_pd_free(struct blkg_policy_data *pd)
2591{
2592 struct ioc_gq *iocg = pd_to_iocg(pd);
2593 struct ioc *ioc = iocg->ioc;
Tejun Heo5aeac7c2020-09-01 14:52:31 -04002594 unsigned long flags;
Tejun Heo7caa4712019-08-28 15:05:58 -07002595
2596 if (ioc) {
Tejun Heo5aeac7c2020-09-01 14:52:31 -04002597 spin_lock_irqsave(&ioc->lock, flags);
Tejun Heo97eb1972020-09-01 14:52:43 -04002598
Tejun Heo7caa4712019-08-28 15:05:58 -07002599 if (!list_empty(&iocg->active_list)) {
Tejun Heob0853ab2020-09-01 14:52:50 -04002600 struct ioc_now now;
2601
2602 ioc_now(ioc, &now);
2603 propagate_weights(iocg, 0, 0, false, &now);
Tejun Heo7caa4712019-08-28 15:05:58 -07002604 list_del_init(&iocg->active_list);
2605 }
Tejun Heo97eb1972020-09-01 14:52:43 -04002606
2607 WARN_ON_ONCE(!list_empty(&iocg->walk_list));
Tejun Heo8692d2d2020-09-01 14:52:45 -04002608 WARN_ON_ONCE(!list_empty(&iocg->surplus_list));
Tejun Heo97eb1972020-09-01 14:52:43 -04002609
Tejun Heo5aeac7c2020-09-01 14:52:31 -04002610 spin_unlock_irqrestore(&ioc->lock, flags);
Tejun Heoe036c4c2019-09-10 09:15:25 -07002611
2612 hrtimer_cancel(&iocg->waitq_timer);
2613 hrtimer_cancel(&iocg->delay_timer);
Tejun Heo7caa4712019-08-28 15:05:58 -07002614 }
Tejun Heo97eb1972020-09-01 14:52:43 -04002615 free_percpu(iocg->pcpu_stat);
Tejun Heo7caa4712019-08-28 15:05:58 -07002616 kfree(iocg);
2617}
2618
Tejun Heo97eb1972020-09-01 14:52:43 -04002619static size_t ioc_pd_stat(struct blkg_policy_data *pd, char *buf, size_t size)
2620{
2621 struct ioc_gq *iocg = pd_to_iocg(pd);
2622 struct ioc *ioc = iocg->ioc;
2623 size_t pos = 0;
2624
2625 if (!ioc->enabled)
2626 return 0;
2627
2628 if (iocg->level == 0) {
2629 unsigned vp10k = DIV64_U64_ROUND_CLOSEST(
2630 atomic64_read(&ioc->vtime_rate) * 10000,
2631 VTIME_PER_USEC);
2632 pos += scnprintf(buf + pos, size - pos, " cost.vrate=%u.%02u",
2633 vp10k / 100, vp10k % 100);
2634 }
2635
2636 pos += scnprintf(buf + pos, size - pos, " cost.usage=%llu",
2637 iocg->last_stat.usage_us);
2638
2639 return pos;
2640}
2641
Tejun Heo7caa4712019-08-28 15:05:58 -07002642static u64 ioc_weight_prfill(struct seq_file *sf, struct blkg_policy_data *pd,
2643 int off)
2644{
2645 const char *dname = blkg_dev_name(pd->blkg);
2646 struct ioc_gq *iocg = pd_to_iocg(pd);
2647
2648 if (dname && iocg->cfg_weight)
Tejun Heobd0adb92020-09-01 14:52:39 -04002649 seq_printf(sf, "%s %u\n", dname, iocg->cfg_weight / WEIGHT_ONE);
Tejun Heo7caa4712019-08-28 15:05:58 -07002650 return 0;
2651}
2652
2653
2654static int ioc_weight_show(struct seq_file *sf, void *v)
2655{
2656 struct blkcg *blkcg = css_to_blkcg(seq_css(sf));
2657 struct ioc_cgrp *iocc = blkcg_to_iocc(blkcg);
2658
Tejun Heobd0adb92020-09-01 14:52:39 -04002659 seq_printf(sf, "default %u\n", iocc->dfl_weight / WEIGHT_ONE);
Tejun Heo7caa4712019-08-28 15:05:58 -07002660 blkcg_print_blkgs(sf, blkcg, ioc_weight_prfill,
2661 &blkcg_policy_iocost, seq_cft(sf)->private, false);
2662 return 0;
2663}
2664
2665static ssize_t ioc_weight_write(struct kernfs_open_file *of, char *buf,
2666 size_t nbytes, loff_t off)
2667{
2668 struct blkcg *blkcg = css_to_blkcg(of_css(of));
2669 struct ioc_cgrp *iocc = blkcg_to_iocc(blkcg);
2670 struct blkg_conf_ctx ctx;
Tejun Heob0853ab2020-09-01 14:52:50 -04002671 struct ioc_now now;
Tejun Heo7caa4712019-08-28 15:05:58 -07002672 struct ioc_gq *iocg;
2673 u32 v;
2674 int ret;
2675
2676 if (!strchr(buf, ':')) {
2677 struct blkcg_gq *blkg;
2678
2679 if (!sscanf(buf, "default %u", &v) && !sscanf(buf, "%u", &v))
2680 return -EINVAL;
2681
2682 if (v < CGROUP_WEIGHT_MIN || v > CGROUP_WEIGHT_MAX)
2683 return -EINVAL;
2684
2685 spin_lock(&blkcg->lock);
Tejun Heobd0adb92020-09-01 14:52:39 -04002686 iocc->dfl_weight = v * WEIGHT_ONE;
Tejun Heo7caa4712019-08-28 15:05:58 -07002687 hlist_for_each_entry(blkg, &blkcg->blkg_list, blkcg_node) {
2688 struct ioc_gq *iocg = blkg_to_iocg(blkg);
2689
2690 if (iocg) {
2691 spin_lock_irq(&iocg->ioc->lock);
Tejun Heob0853ab2020-09-01 14:52:50 -04002692 ioc_now(iocg->ioc, &now);
2693 weight_updated(iocg, &now);
Tejun Heo7caa4712019-08-28 15:05:58 -07002694 spin_unlock_irq(&iocg->ioc->lock);
2695 }
2696 }
2697 spin_unlock(&blkcg->lock);
2698
2699 return nbytes;
2700 }
2701
2702 ret = blkg_conf_prep(blkcg, &blkcg_policy_iocost, buf, &ctx);
2703 if (ret)
2704 return ret;
2705
2706 iocg = blkg_to_iocg(ctx.blkg);
2707
2708 if (!strncmp(ctx.body, "default", 7)) {
2709 v = 0;
2710 } else {
2711 if (!sscanf(ctx.body, "%u", &v))
2712 goto einval;
2713 if (v < CGROUP_WEIGHT_MIN || v > CGROUP_WEIGHT_MAX)
2714 goto einval;
2715 }
2716
Dan Carpenter41591a52019-10-31 13:53:41 +03002717 spin_lock(&iocg->ioc->lock);
Tejun Heobd0adb92020-09-01 14:52:39 -04002718 iocg->cfg_weight = v * WEIGHT_ONE;
Tejun Heob0853ab2020-09-01 14:52:50 -04002719 ioc_now(iocg->ioc, &now);
2720 weight_updated(iocg, &now);
Dan Carpenter41591a52019-10-31 13:53:41 +03002721 spin_unlock(&iocg->ioc->lock);
Tejun Heo7caa4712019-08-28 15:05:58 -07002722
2723 blkg_conf_finish(&ctx);
2724 return nbytes;
2725
2726einval:
2727 blkg_conf_finish(&ctx);
2728 return -EINVAL;
2729}
2730
2731static u64 ioc_qos_prfill(struct seq_file *sf, struct blkg_policy_data *pd,
2732 int off)
2733{
2734 const char *dname = blkg_dev_name(pd->blkg);
2735 struct ioc *ioc = pd_to_iocg(pd)->ioc;
2736
2737 if (!dname)
2738 return 0;
2739
2740 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",
2741 dname, ioc->enabled, ioc->user_qos_params ? "user" : "auto",
2742 ioc->params.qos[QOS_RPPM] / 10000,
2743 ioc->params.qos[QOS_RPPM] % 10000 / 100,
2744 ioc->params.qos[QOS_RLAT],
2745 ioc->params.qos[QOS_WPPM] / 10000,
2746 ioc->params.qos[QOS_WPPM] % 10000 / 100,
2747 ioc->params.qos[QOS_WLAT],
2748 ioc->params.qos[QOS_MIN] / 10000,
2749 ioc->params.qos[QOS_MIN] % 10000 / 100,
2750 ioc->params.qos[QOS_MAX] / 10000,
2751 ioc->params.qos[QOS_MAX] % 10000 / 100);
2752 return 0;
2753}
2754
2755static int ioc_qos_show(struct seq_file *sf, void *v)
2756{
2757 struct blkcg *blkcg = css_to_blkcg(seq_css(sf));
2758
2759 blkcg_print_blkgs(sf, blkcg, ioc_qos_prfill,
2760 &blkcg_policy_iocost, seq_cft(sf)->private, false);
2761 return 0;
2762}
2763
2764static const match_table_t qos_ctrl_tokens = {
2765 { QOS_ENABLE, "enable=%u" },
2766 { QOS_CTRL, "ctrl=%s" },
2767 { NR_QOS_CTRL_PARAMS, NULL },
2768};
2769
2770static const match_table_t qos_tokens = {
2771 { QOS_RPPM, "rpct=%s" },
2772 { QOS_RLAT, "rlat=%u" },
2773 { QOS_WPPM, "wpct=%s" },
2774 { QOS_WLAT, "wlat=%u" },
2775 { QOS_MIN, "min=%s" },
2776 { QOS_MAX, "max=%s" },
2777 { NR_QOS_PARAMS, NULL },
2778};
2779
2780static ssize_t ioc_qos_write(struct kernfs_open_file *of, char *input,
2781 size_t nbytes, loff_t off)
2782{
2783 struct gendisk *disk;
2784 struct ioc *ioc;
2785 u32 qos[NR_QOS_PARAMS];
2786 bool enable, user;
2787 char *p;
2788 int ret;
2789
2790 disk = blkcg_conf_get_disk(&input);
2791 if (IS_ERR(disk))
2792 return PTR_ERR(disk);
2793
2794 ioc = q_to_ioc(disk->queue);
2795 if (!ioc) {
2796 ret = blk_iocost_init(disk->queue);
2797 if (ret)
2798 goto err;
2799 ioc = q_to_ioc(disk->queue);
2800 }
2801
2802 spin_lock_irq(&ioc->lock);
2803 memcpy(qos, ioc->params.qos, sizeof(qos));
2804 enable = ioc->enabled;
2805 user = ioc->user_qos_params;
2806 spin_unlock_irq(&ioc->lock);
2807
2808 while ((p = strsep(&input, " \t\n"))) {
2809 substring_t args[MAX_OPT_ARGS];
2810 char buf[32];
2811 int tok;
2812 s64 v;
2813
2814 if (!*p)
2815 continue;
2816
2817 switch (match_token(p, qos_ctrl_tokens, args)) {
2818 case QOS_ENABLE:
2819 match_u64(&args[0], &v);
2820 enable = v;
2821 continue;
2822 case QOS_CTRL:
2823 match_strlcpy(buf, &args[0], sizeof(buf));
2824 if (!strcmp(buf, "auto"))
2825 user = false;
2826 else if (!strcmp(buf, "user"))
2827 user = true;
2828 else
2829 goto einval;
2830 continue;
2831 }
2832
2833 tok = match_token(p, qos_tokens, args);
2834 switch (tok) {
2835 case QOS_RPPM:
2836 case QOS_WPPM:
2837 if (match_strlcpy(buf, &args[0], sizeof(buf)) >=
2838 sizeof(buf))
2839 goto einval;
2840 if (cgroup_parse_float(buf, 2, &v))
2841 goto einval;
2842 if (v < 0 || v > 10000)
2843 goto einval;
2844 qos[tok] = v * 100;
2845 break;
2846 case QOS_RLAT:
2847 case QOS_WLAT:
2848 if (match_u64(&args[0], &v))
2849 goto einval;
2850 qos[tok] = v;
2851 break;
2852 case QOS_MIN:
2853 case QOS_MAX:
2854 if (match_strlcpy(buf, &args[0], sizeof(buf)) >=
2855 sizeof(buf))
2856 goto einval;
2857 if (cgroup_parse_float(buf, 2, &v))
2858 goto einval;
2859 if (v < 0)
2860 goto einval;
2861 qos[tok] = clamp_t(s64, v * 100,
2862 VRATE_MIN_PPM, VRATE_MAX_PPM);
2863 break;
2864 default:
2865 goto einval;
2866 }
2867 user = true;
2868 }
2869
2870 if (qos[QOS_MIN] > qos[QOS_MAX])
2871 goto einval;
2872
2873 spin_lock_irq(&ioc->lock);
2874
2875 if (enable) {
Tejun Heocd006502020-04-13 12:27:56 -04002876 blk_stat_enable_accounting(ioc->rqos.q);
Tejun Heo7caa4712019-08-28 15:05:58 -07002877 blk_queue_flag_set(QUEUE_FLAG_RQ_ALLOC_TIME, ioc->rqos.q);
2878 ioc->enabled = true;
2879 } else {
2880 blk_queue_flag_clear(QUEUE_FLAG_RQ_ALLOC_TIME, ioc->rqos.q);
2881 ioc->enabled = false;
2882 }
2883
2884 if (user) {
2885 memcpy(ioc->params.qos, qos, sizeof(qos));
2886 ioc->user_qos_params = true;
2887 } else {
2888 ioc->user_qos_params = false;
2889 }
2890
2891 ioc_refresh_params(ioc, true);
2892 spin_unlock_irq(&ioc->lock);
2893
2894 put_disk_and_module(disk);
2895 return nbytes;
2896einval:
2897 ret = -EINVAL;
2898err:
2899 put_disk_and_module(disk);
2900 return ret;
2901}
2902
2903static u64 ioc_cost_model_prfill(struct seq_file *sf,
2904 struct blkg_policy_data *pd, int off)
2905{
2906 const char *dname = blkg_dev_name(pd->blkg);
2907 struct ioc *ioc = pd_to_iocg(pd)->ioc;
2908 u64 *u = ioc->params.i_lcoefs;
2909
2910 if (!dname)
2911 return 0;
2912
2913 seq_printf(sf, "%s ctrl=%s model=linear "
2914 "rbps=%llu rseqiops=%llu rrandiops=%llu "
2915 "wbps=%llu wseqiops=%llu wrandiops=%llu\n",
2916 dname, ioc->user_cost_model ? "user" : "auto",
2917 u[I_LCOEF_RBPS], u[I_LCOEF_RSEQIOPS], u[I_LCOEF_RRANDIOPS],
2918 u[I_LCOEF_WBPS], u[I_LCOEF_WSEQIOPS], u[I_LCOEF_WRANDIOPS]);
2919 return 0;
2920}
2921
2922static int ioc_cost_model_show(struct seq_file *sf, void *v)
2923{
2924 struct blkcg *blkcg = css_to_blkcg(seq_css(sf));
2925
2926 blkcg_print_blkgs(sf, blkcg, ioc_cost_model_prfill,
2927 &blkcg_policy_iocost, seq_cft(sf)->private, false);
2928 return 0;
2929}
2930
2931static const match_table_t cost_ctrl_tokens = {
2932 { COST_CTRL, "ctrl=%s" },
2933 { COST_MODEL, "model=%s" },
2934 { NR_COST_CTRL_PARAMS, NULL },
2935};
2936
2937static const match_table_t i_lcoef_tokens = {
2938 { I_LCOEF_RBPS, "rbps=%u" },
2939 { I_LCOEF_RSEQIOPS, "rseqiops=%u" },
2940 { I_LCOEF_RRANDIOPS, "rrandiops=%u" },
2941 { I_LCOEF_WBPS, "wbps=%u" },
2942 { I_LCOEF_WSEQIOPS, "wseqiops=%u" },
2943 { I_LCOEF_WRANDIOPS, "wrandiops=%u" },
2944 { NR_I_LCOEFS, NULL },
2945};
2946
2947static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
2948 size_t nbytes, loff_t off)
2949{
2950 struct gendisk *disk;
2951 struct ioc *ioc;
2952 u64 u[NR_I_LCOEFS];
2953 bool user;
2954 char *p;
2955 int ret;
2956
2957 disk = blkcg_conf_get_disk(&input);
2958 if (IS_ERR(disk))
2959 return PTR_ERR(disk);
2960
2961 ioc = q_to_ioc(disk->queue);
2962 if (!ioc) {
2963 ret = blk_iocost_init(disk->queue);
2964 if (ret)
2965 goto err;
2966 ioc = q_to_ioc(disk->queue);
2967 }
2968
2969 spin_lock_irq(&ioc->lock);
2970 memcpy(u, ioc->params.i_lcoefs, sizeof(u));
2971 user = ioc->user_cost_model;
2972 spin_unlock_irq(&ioc->lock);
2973
2974 while ((p = strsep(&input, " \t\n"))) {
2975 substring_t args[MAX_OPT_ARGS];
2976 char buf[32];
2977 int tok;
2978 u64 v;
2979
2980 if (!*p)
2981 continue;
2982
2983 switch (match_token(p, cost_ctrl_tokens, args)) {
2984 case COST_CTRL:
2985 match_strlcpy(buf, &args[0], sizeof(buf));
2986 if (!strcmp(buf, "auto"))
2987 user = false;
2988 else if (!strcmp(buf, "user"))
2989 user = true;
2990 else
2991 goto einval;
2992 continue;
2993 case COST_MODEL:
2994 match_strlcpy(buf, &args[0], sizeof(buf));
2995 if (strcmp(buf, "linear"))
2996 goto einval;
2997 continue;
2998 }
2999
3000 tok = match_token(p, i_lcoef_tokens, args);
3001 if (tok == NR_I_LCOEFS)
3002 goto einval;
3003 if (match_u64(&args[0], &v))
3004 goto einval;
3005 u[tok] = v;
3006 user = true;
3007 }
3008
3009 spin_lock_irq(&ioc->lock);
3010 if (user) {
3011 memcpy(ioc->params.i_lcoefs, u, sizeof(u));
3012 ioc->user_cost_model = true;
3013 } else {
3014 ioc->user_cost_model = false;
3015 }
3016 ioc_refresh_params(ioc, true);
3017 spin_unlock_irq(&ioc->lock);
3018
3019 put_disk_and_module(disk);
3020 return nbytes;
3021
3022einval:
3023 ret = -EINVAL;
3024err:
3025 put_disk_and_module(disk);
3026 return ret;
3027}
3028
3029static struct cftype ioc_files[] = {
3030 {
3031 .name = "weight",
3032 .flags = CFTYPE_NOT_ON_ROOT,
3033 .seq_show = ioc_weight_show,
3034 .write = ioc_weight_write,
3035 },
3036 {
3037 .name = "cost.qos",
3038 .flags = CFTYPE_ONLY_ON_ROOT,
3039 .seq_show = ioc_qos_show,
3040 .write = ioc_qos_write,
3041 },
3042 {
3043 .name = "cost.model",
3044 .flags = CFTYPE_ONLY_ON_ROOT,
3045 .seq_show = ioc_cost_model_show,
3046 .write = ioc_cost_model_write,
3047 },
3048 {}
3049};
3050
3051static struct blkcg_policy blkcg_policy_iocost = {
3052 .dfl_cftypes = ioc_files,
3053 .cpd_alloc_fn = ioc_cpd_alloc,
3054 .cpd_free_fn = ioc_cpd_free,
3055 .pd_alloc_fn = ioc_pd_alloc,
3056 .pd_init_fn = ioc_pd_init,
3057 .pd_free_fn = ioc_pd_free,
Tejun Heo97eb1972020-09-01 14:52:43 -04003058 .pd_stat_fn = ioc_pd_stat,
Tejun Heo7caa4712019-08-28 15:05:58 -07003059};
3060
3061static int __init ioc_init(void)
3062{
3063 return blkcg_policy_register(&blkcg_policy_iocost);
3064}
3065
3066static void __exit ioc_exit(void)
3067{
3068 return blkcg_policy_unregister(&blkcg_policy_iocost);
3069}
3070
3071module_init(ioc_init);
3072module_exit(ioc_exit);