xref: /linux/block/blk-iocost.c (revision 4b99990cdf9560e8a071640baf19f312e6ae02f4)
1 /* 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  * parameters 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
71  * upto 1 (WEIGHT_ONE).
72  *
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 if 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, solely 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.
152  *
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 output looks like the following.
159  *
160  *  sdb RUN   per=300ms cur_per=234.218:v203.695 busy= +1 vrate= 62.12%
161  *                 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
164  *
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
173  */
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 <asm/local.h>
182 #include <asm/local64.h>
183 #include "blk-rq-qos.h"
184 #include "blk-stat.h"
185 #include "blk-wbt.h"
186 #include "blk-cgroup.h"
187 
188 #ifdef CONFIG_TRACEPOINTS
189 
190 /* copied from TRACE_CGROUP_PATH, see cgroup-internal.h */
191 #define TRACE_IOCG_PATH_LEN 1024
192 static DEFINE_SPINLOCK(trace_iocg_path_lock);
193 static 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 
212 enum {
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 	/*
220 	 * iocg->vtime is targeted at 50% behind the device vtime, which
221 	 * serves as its IO credit buffer.  Surplus weight adjustment is
222 	 * immediately canceled if the vtime margin runs below 10%.
223 	 */
224 	MARGIN_MIN_PCT		= 10,
225 	MARGIN_LOW_PCT		= 20,
226 	MARGIN_TARGET_PCT	= 50,
227 
228 	INUSE_ADJ_STEP_PCT	= 25,
229 
230 	/* Have some play in timer operations */
231 	TIMER_SLACK_PCT		= 1,
232 
233 	/* 1/64k is granular enough and can easily be handled w/ u32 */
234 	WEIGHT_ONE		= 1 << 16,
235 };
236 
237 enum {
238 	/*
239 	 * As vtime is used to calculate the cost of each IO, it needs to
240 	 * be fairly high precision.  For example, it should be able to
241 	 * represent the cost of a single page worth of discard with
242 	 * suffificient accuracy.  At the same time, it should be able to
243 	 * represent reasonably long enough durations to be useful and
244 	 * convenient during operation.
245 	 *
246 	 * 1s worth of vtime is 2^37.  This gives us both sub-nanosecond
247 	 * granularity and days of wrap-around time even at extreme vrates.
248 	 */
249 	VTIME_PER_SEC_SHIFT	= 37,
250 	VTIME_PER_SEC		= 1LLU << VTIME_PER_SEC_SHIFT,
251 	VTIME_PER_USEC		= VTIME_PER_SEC / USEC_PER_SEC,
252 	VTIME_PER_NSEC		= VTIME_PER_SEC / NSEC_PER_SEC,
253 
254 	/* bound vrate adjustments within two orders of magnitude */
255 	VRATE_MIN_PPM		= 10000,	/* 1% */
256 	VRATE_MAX_PPM		= 100000000,	/* 10000% */
257 
258 	VRATE_MIN		= VTIME_PER_USEC * VRATE_MIN_PPM / MILLION,
259 	VRATE_CLAMP_ADJ_PCT	= 4,
260 
261 	/* switch iff the conditions are met for longer than this */
262 	AUTOP_CYCLE_NSEC	= 10LLU * NSEC_PER_SEC,
263 };
264 
265 enum {
266 	/* if IOs end up waiting for requests, issue less */
267 	RQ_WAIT_BUSY_PCT	= 5,
268 
269 	/* unbusy hysterisis */
270 	UNBUSY_THR_PCT		= 75,
271 
272 	/*
273 	 * The effect of delay is indirect and non-linear and a huge amount of
274 	 * future debt can accumulate abruptly while unthrottled. Linearly scale
275 	 * up delay as debt is going up and then let it decay exponentially.
276 	 * This gives us quick ramp ups while delay is accumulating and long
277 	 * tails which can help reducing the frequency of debt explosions on
278 	 * unthrottle. The parameters are experimentally determined.
279 	 *
280 	 * The delay mechanism provides adequate protection and behavior in many
281 	 * cases. However, this is far from ideal and falls shorts on both
282 	 * fronts. The debtors are often throttled too harshly costing a
283 	 * significant level of fairness and possibly total work while the
284 	 * protection against their impacts on the system can be choppy and
285 	 * unreliable.
286 	 *
287 	 * The shortcoming primarily stems from the fact that, unlike for page
288 	 * cache, the kernel doesn't have well-defined back-pressure propagation
289 	 * mechanism and policies for anonymous memory. Fully addressing this
290 	 * issue will likely require substantial improvements in the area.
291 	 */
292 	MIN_DELAY_THR_PCT	= 500,
293 	MAX_DELAY_THR_PCT	= 25000,
294 	MIN_DELAY		= 250,
295 	MAX_DELAY		= 250 * USEC_PER_MSEC,
296 
297 	/* halve debts if avg usage over 100ms is under 50% */
298 	DFGV_USAGE_PCT		= 50,
299 	DFGV_PERIOD		= 100 * USEC_PER_MSEC,
300 
301 	/* don't let cmds which take a very long time pin lagging for too long */
302 	MAX_LAGGING_PERIODS	= 10,
303 
304 	/*
305 	 * Count IO size in 4k pages.  The 12bit shift helps keeping
306 	 * size-proportional components of cost calculation in closer
307 	 * numbers of digits to per-IO cost components.
308 	 */
309 	IOC_PAGE_SHIFT		= 12,
310 	IOC_PAGE_SIZE		= 1 << IOC_PAGE_SHIFT,
311 	IOC_SECT_TO_PAGE_SHIFT	= IOC_PAGE_SHIFT - SECTOR_SHIFT,
312 
313 	/* if apart further than 16M, consider randio for linear model */
314 	LCOEF_RANDIO_PAGES	= 4096,
315 };
316 
317 enum ioc_running {
318 	IOC_IDLE,
319 	IOC_RUNNING,
320 	IOC_STOP,
321 };
322 
323 /* io.cost.qos controls including per-dev enable of the whole controller */
324 enum {
325 	QOS_ENABLE,
326 	QOS_CTRL,
327 	NR_QOS_CTRL_PARAMS,
328 };
329 
330 /* io.cost.qos params */
331 enum {
332 	QOS_RPPM,
333 	QOS_RLAT,
334 	QOS_WPPM,
335 	QOS_WLAT,
336 	QOS_MIN,
337 	QOS_MAX,
338 	NR_QOS_PARAMS,
339 };
340 
341 /* io.cost.model controls */
342 enum {
343 	COST_CTRL,
344 	COST_MODEL,
345 	NR_COST_CTRL_PARAMS,
346 };
347 
348 /* builtin linear cost model coefficients */
349 enum {
350 	I_LCOEF_RBPS,
351 	I_LCOEF_RSEQIOPS,
352 	I_LCOEF_RRANDIOPS,
353 	I_LCOEF_WBPS,
354 	I_LCOEF_WSEQIOPS,
355 	I_LCOEF_WRANDIOPS,
356 	NR_I_LCOEFS,
357 };
358 
359 enum {
360 	LCOEF_RPAGE,
361 	LCOEF_RSEQIO,
362 	LCOEF_RRANDIO,
363 	LCOEF_WPAGE,
364 	LCOEF_WSEQIO,
365 	LCOEF_WRANDIO,
366 	NR_LCOEFS,
367 };
368 
369 enum {
370 	AUTOP_INVALID,
371 	AUTOP_HDD,
372 	AUTOP_SSD_QD1,
373 	AUTOP_SSD_DFL,
374 	AUTOP_SSD_FAST,
375 };
376 
377 struct ioc_params {
378 	u32				qos[NR_QOS_PARAMS];
379 	u64				i_lcoefs[NR_I_LCOEFS];
380 	u64				lcoefs[NR_LCOEFS];
381 	u32				too_fast_vrate_pct;
382 	u32				too_slow_vrate_pct;
383 };
384 
385 struct ioc_margins {
386 	s64				min;
387 	s64				low;
388 	s64				target;
389 };
390 
391 struct ioc_missed {
392 	local_t				nr_met;
393 	local_t				nr_missed;
394 	u32				last_met;
395 	u32				last_missed;
396 };
397 
398 struct ioc_pcpu_stat {
399 	struct ioc_missed		missed[2];
400 
401 	local64_t			rq_wait_ns;
402 	u64				last_rq_wait_ns;
403 };
404 
405 /* per device */
406 struct ioc {
407 	struct rq_qos			rqos;
408 
409 	bool				enabled;
410 
411 	struct ioc_params		params;
412 	struct ioc_margins		margins;
413 	u32				period_us;
414 	u32				timer_slack_ns;
415 	u64				vrate_min;
416 	u64				vrate_max;
417 
418 	spinlock_t			lock;
419 	struct timer_list		timer;
420 	struct list_head		active_iocgs;	/* active cgroups */
421 	struct ioc_pcpu_stat __percpu	*pcpu_stat;
422 
423 	enum ioc_running		running;
424 	atomic64_t			vtime_rate;
425 	u64				vtime_base_rate;
426 	s64				vtime_err;
427 
428 	seqcount_spinlock_t		period_seqcount;
429 	u64				period_at;	/* wallclock starttime */
430 	u64				period_at_vtime; /* vtime starttime */
431 
432 	atomic64_t			cur_period;	/* inc'd each period */
433 	int				busy_level;	/* saturation history */
434 
435 	bool				weights_updated;
436 	atomic_t			hweight_gen;	/* for lazy hweights */
437 
438 	/* debt forgivness */
439 	u64				dfgv_period_at;
440 	u64				dfgv_period_rem;
441 	u64				dfgv_usage_us_sum;
442 
443 	u64				autop_too_fast_at;
444 	u64				autop_too_slow_at;
445 	int				autop_idx;
446 	bool				user_qos_params:1;
447 	bool				user_cost_model:1;
448 };
449 
450 struct iocg_pcpu_stat {
451 	local64_t			abs_vusage;
452 };
453 
454 struct iocg_stat {
455 	u64				usage_us;
456 	u64				wait_us;
457 	u64				indebt_us;
458 	u64				indelay_us;
459 };
460 
461 /* per device-cgroup pair */
462 struct ioc_gq {
463 	struct blkg_policy_data		pd;
464 	struct ioc			*ioc;
465 
466 	/*
467 	 * A iocg can get its weight from two sources - an explicit
468 	 * per-device-cgroup configuration or the default weight of the
469 	 * cgroup.  `cfg_weight` is the explicit per-device-cgroup
470 	 * configuration.  `weight` is the effective considering both
471 	 * sources.
472 	 *
473 	 * When an idle cgroup becomes active its `active` goes from 0 to
474 	 * `weight`.  `inuse` is the surplus adjusted active weight.
475 	 * `active` and `inuse` are used to calculate `hweight_active` and
476 	 * `hweight_inuse`.
477 	 *
478 	 * `last_inuse` remembers `inuse` while an iocg is idle to persist
479 	 * surplus adjustments.
480 	 *
481 	 * `inuse` may be adjusted dynamically during period. `saved_*` are used
482 	 * to determine and track adjustments.
483 	 */
484 	u32				cfg_weight;
485 	u32				weight;
486 	u32				active;
487 	u32				inuse;
488 
489 	u32				last_inuse;
490 	s64				saved_margin;
491 
492 	sector_t			cursor;		/* to detect randio */
493 
494 	/*
495 	 * `vtime` is this iocg's vtime cursor which progresses as IOs are
496 	 * issued.  If lagging behind device vtime, the delta represents
497 	 * the currently available IO budget.  If running ahead, the
498 	 * overage.
499 	 *
500 	 * `vtime_done` is the same but progressed on completion rather
501 	 * than issue.  The delta behind `vtime` represents the cost of
502 	 * currently in-flight IOs.
503 	 */
504 	atomic64_t			vtime;
505 	atomic64_t			done_vtime;
506 	u64				abs_vdebt;
507 
508 	/* current delay in effect and when it started */
509 	u64				delay;
510 	u64				delay_at;
511 
512 	/*
513 	 * The period this iocg was last active in.  Used for deactivation
514 	 * and invalidating `vtime`.
515 	 */
516 	atomic64_t			active_period;
517 	struct list_head		active_list;
518 
519 	/* see __propagate_weights() and current_hweight() for details */
520 	u64				child_active_sum;
521 	u64				child_inuse_sum;
522 	u64				child_adjusted_sum;
523 	int				hweight_gen;
524 	u32				hweight_active;
525 	u32				hweight_inuse;
526 	u32				hweight_donating;
527 	u32				hweight_after_donation;
528 
529 	struct list_head		walk_list;
530 	struct list_head		surplus_list;
531 
532 	struct wait_queue_head		waitq;
533 	struct hrtimer			waitq_timer;
534 
535 	/* timestamp at the latest activation */
536 	u64				activated_at;
537 
538 	/* statistics */
539 	struct iocg_pcpu_stat __percpu	*pcpu_stat;
540 	struct iocg_stat		stat;
541 	struct iocg_stat		last_stat;
542 	u64				last_stat_abs_vusage;
543 	u64				usage_delta_us;
544 	u64				wait_since;
545 	u64				indebt_since;
546 	u64				indelay_since;
547 
548 	/* this iocg's depth in the hierarchy and ancestors including self */
549 	int				level;
550 	struct ioc_gq			*ancestors[];
551 };
552 
553 /* per cgroup */
554 struct ioc_cgrp {
555 	struct blkcg_policy_data	cpd;
556 	unsigned int			dfl_weight;
557 };
558 
559 struct ioc_now {
560 	u64				now_ns;
561 	u64				now;
562 	u64				vnow;
563 };
564 
565 struct iocg_wait {
566 	struct wait_queue_entry		wait;
567 	struct bio			*bio;
568 	u64				abs_cost;
569 	bool				committed;
570 };
571 
572 struct iocg_wake_ctx {
573 	struct ioc_gq			*iocg;
574 	u32				hw_inuse;
575 	s64				vbudget;
576 };
577 
578 static const struct ioc_params autop[] = {
579 	[AUTOP_HDD] = {
580 		.qos				= {
581 			[QOS_RLAT]		=        250000, /* 250ms */
582 			[QOS_WLAT]		=        250000,
583 			[QOS_MIN]		= VRATE_MIN_PPM,
584 			[QOS_MAX]		= VRATE_MAX_PPM,
585 		},
586 		.i_lcoefs			= {
587 			[I_LCOEF_RBPS]		=     174019176,
588 			[I_LCOEF_RSEQIOPS]	=         41708,
589 			[I_LCOEF_RRANDIOPS]	=           370,
590 			[I_LCOEF_WBPS]		=     178075866,
591 			[I_LCOEF_WSEQIOPS]	=         42705,
592 			[I_LCOEF_WRANDIOPS]	=           378,
593 		},
594 	},
595 	[AUTOP_SSD_QD1] = {
596 		.qos				= {
597 			[QOS_RLAT]		=         25000, /* 25ms */
598 			[QOS_WLAT]		=         25000,
599 			[QOS_MIN]		= VRATE_MIN_PPM,
600 			[QOS_MAX]		= VRATE_MAX_PPM,
601 		},
602 		.i_lcoefs			= {
603 			[I_LCOEF_RBPS]		=     245855193,
604 			[I_LCOEF_RSEQIOPS]	=         61575,
605 			[I_LCOEF_RRANDIOPS]	=          6946,
606 			[I_LCOEF_WBPS]		=     141365009,
607 			[I_LCOEF_WSEQIOPS]	=         33716,
608 			[I_LCOEF_WRANDIOPS]	=         26796,
609 		},
610 	},
611 	[AUTOP_SSD_DFL] = {
612 		.qos				= {
613 			[QOS_RLAT]		=         25000, /* 25ms */
614 			[QOS_WLAT]		=         25000,
615 			[QOS_MIN]		= VRATE_MIN_PPM,
616 			[QOS_MAX]		= VRATE_MAX_PPM,
617 		},
618 		.i_lcoefs			= {
619 			[I_LCOEF_RBPS]		=     488636629,
620 			[I_LCOEF_RSEQIOPS]	=          8932,
621 			[I_LCOEF_RRANDIOPS]	=          8518,
622 			[I_LCOEF_WBPS]		=     427891549,
623 			[I_LCOEF_WSEQIOPS]	=         28755,
624 			[I_LCOEF_WRANDIOPS]	=         21940,
625 		},
626 		.too_fast_vrate_pct		=           500,
627 	},
628 	[AUTOP_SSD_FAST] = {
629 		.qos				= {
630 			[QOS_RLAT]		=          5000, /* 5ms */
631 			[QOS_WLAT]		=          5000,
632 			[QOS_MIN]		= VRATE_MIN_PPM,
633 			[QOS_MAX]		= VRATE_MAX_PPM,
634 		},
635 		.i_lcoefs			= {
636 			[I_LCOEF_RBPS]		=    3102524156LLU,
637 			[I_LCOEF_RSEQIOPS]	=        724816,
638 			[I_LCOEF_RRANDIOPS]	=        778122,
639 			[I_LCOEF_WBPS]		=    1742780862LLU,
640 			[I_LCOEF_WSEQIOPS]	=        425702,
641 			[I_LCOEF_WRANDIOPS]	=	 443193,
642 		},
643 		.too_slow_vrate_pct		=            10,
644 	},
645 };
646 
647 /*
648  * vrate adjust percentages indexed by ioc->busy_level.  We adjust up on
649  * vtime credit shortage and down on device saturation.
650  */
651 static const u32 vrate_adj_pct[] =
652 	{ 0, 0, 0, 0,
653 	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
654 	  2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
655 	  4, 4, 4, 4, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8, 16 };
656 
657 static struct blkcg_policy blkcg_policy_iocost;
658 
659 /* accessors and helpers */
660 static struct ioc *rqos_to_ioc(struct rq_qos *rqos)
661 {
662 	return container_of(rqos, struct ioc, rqos);
663 }
664 
665 static struct ioc *q_to_ioc(struct request_queue *q)
666 {
667 	return rqos_to_ioc(rq_qos_id(q, RQ_QOS_COST));
668 }
669 
670 static const char __maybe_unused *ioc_name(struct ioc *ioc)
671 {
672 	struct gendisk *disk = ioc->rqos.disk;
673 
674 	if (!disk)
675 		return "<unknown>";
676 	return disk->disk_name;
677 }
678 
679 static struct ioc_gq *pd_to_iocg(struct blkg_policy_data *pd)
680 {
681 	return pd ? container_of(pd, struct ioc_gq, pd) : NULL;
682 }
683 
684 static struct ioc_gq *blkg_to_iocg(struct blkcg_gq *blkg)
685 {
686 	return pd_to_iocg(blkg_to_pd(blkg, &blkcg_policy_iocost));
687 }
688 
689 static struct blkcg_gq *iocg_to_blkg(struct ioc_gq *iocg)
690 {
691 	return pd_to_blkg(&iocg->pd);
692 }
693 
694 static struct ioc_cgrp *blkcg_to_iocc(struct blkcg *blkcg)
695 {
696 	return container_of(blkcg_to_cpd(blkcg, &blkcg_policy_iocost),
697 			    struct ioc_cgrp, cpd);
698 }
699 
700 /*
701  * Scale @abs_cost to the inverse of @hw_inuse.  The lower the hierarchical
702  * weight, the more expensive each IO.  Must round up.
703  */
704 static u64 abs_cost_to_cost(u64 abs_cost, u32 hw_inuse)
705 {
706 	return DIV64_U64_ROUND_UP(abs_cost * WEIGHT_ONE, hw_inuse);
707 }
708 
709 /*
710  * The inverse of abs_cost_to_cost().  Must round up.
711  */
712 static u64 cost_to_abs_cost(u64 cost, u32 hw_inuse)
713 {
714 	return DIV64_U64_ROUND_UP(cost * hw_inuse, WEIGHT_ONE);
715 }
716 
717 static void iocg_commit_bio(struct ioc_gq *iocg, struct bio *bio,
718 			    u64 abs_cost, u64 cost)
719 {
720 	struct iocg_pcpu_stat *gcs;
721 
722 	bio->bi_iocost_cost = cost;
723 	atomic64_add(cost, &iocg->vtime);
724 
725 	gcs = get_cpu_ptr(iocg->pcpu_stat);
726 	local64_add(abs_cost, &gcs->abs_vusage);
727 	put_cpu_ptr(gcs);
728 }
729 
730 #define CREATE_TRACE_POINTS
731 #include <trace/events/iocost.h>
732 
733 static void ioc_refresh_margins(struct ioc *ioc)
734 {
735 	struct ioc_margins *margins = &ioc->margins;
736 	u32 period_us = ioc->period_us;
737 	u64 vrate = ioc->vtime_base_rate;
738 
739 	margins->min = (period_us * MARGIN_MIN_PCT / 100) * vrate;
740 	margins->low = (period_us * MARGIN_LOW_PCT / 100) * vrate;
741 	margins->target = (period_us * MARGIN_TARGET_PCT / 100) * vrate;
742 }
743 
744 /* latency Qos params changed, update period_us and all the dependent params */
745 static void ioc_refresh_period_us(struct ioc *ioc)
746 {
747 	u32 ppm, lat, multi, period_us;
748 
749 	lockdep_assert_held(&ioc->lock);
750 
751 	/* pick the higher latency target */
752 	if (ioc->params.qos[QOS_RLAT] >= ioc->params.qos[QOS_WLAT]) {
753 		ppm = ioc->params.qos[QOS_RPPM];
754 		lat = ioc->params.qos[QOS_RLAT];
755 	} else {
756 		ppm = ioc->params.qos[QOS_WPPM];
757 		lat = ioc->params.qos[QOS_WLAT];
758 	}
759 
760 	/*
761 	 * We want the period to be long enough to contain a healthy number
762 	 * of IOs while short enough for granular control.  Define it as a
763 	 * multiple of the latency target.  Ideally, the multiplier should
764 	 * be scaled according to the percentile so that it would nominally
765 	 * contain a certain number of requests.  Let's be simpler and
766 	 * scale it linearly so that it's 2x >= pct(90) and 10x at pct(50).
767 	 */
768 	if (ppm)
769 		multi = max_t(u32, (MILLION - ppm) / 50000, 2);
770 	else
771 		multi = 2;
772 	period_us = multi * lat;
773 	period_us = clamp_t(u32, period_us, MIN_PERIOD, MAX_PERIOD);
774 
775 	/* calculate dependent params */
776 	ioc->period_us = period_us;
777 	ioc->timer_slack_ns = div64_u64(
778 		(u64)period_us * NSEC_PER_USEC * TIMER_SLACK_PCT,
779 		100);
780 	ioc_refresh_margins(ioc);
781 }
782 
783 /*
784  *  ioc->rqos.disk isn't initialized when this function is called from
785  *  the init path.
786  */
787 static int ioc_autop_idx(struct ioc *ioc, struct gendisk *disk)
788 {
789 	int idx = ioc->autop_idx;
790 	const struct ioc_params *p = &autop[idx];
791 	u32 vrate_pct;
792 	u64 now_ns;
793 
794 	/* rotational? */
795 	if (blk_queue_rot(disk->queue))
796 		return AUTOP_HDD;
797 
798 	/* handle SATA SSDs w/ broken NCQ */
799 	if (blk_queue_depth(disk->queue) == 1)
800 		return AUTOP_SSD_QD1;
801 
802 	/* use one of the normal ssd sets */
803 	if (idx < AUTOP_SSD_DFL)
804 		return AUTOP_SSD_DFL;
805 
806 	/* if user is overriding anything, maintain what was there */
807 	if (ioc->user_qos_params || ioc->user_cost_model)
808 		return idx;
809 
810 	/* step up/down based on the vrate */
811 	vrate_pct = div64_u64(ioc->vtime_base_rate * 100, VTIME_PER_USEC);
812 	now_ns = blk_time_get_ns();
813 
814 	if (p->too_fast_vrate_pct && p->too_fast_vrate_pct <= vrate_pct) {
815 		if (!ioc->autop_too_fast_at)
816 			ioc->autop_too_fast_at = now_ns;
817 		if (now_ns - ioc->autop_too_fast_at >= AUTOP_CYCLE_NSEC)
818 			return idx + 1;
819 	} else {
820 		ioc->autop_too_fast_at = 0;
821 	}
822 
823 	if (p->too_slow_vrate_pct && p->too_slow_vrate_pct >= vrate_pct) {
824 		if (!ioc->autop_too_slow_at)
825 			ioc->autop_too_slow_at = now_ns;
826 		if (now_ns - ioc->autop_too_slow_at >= AUTOP_CYCLE_NSEC)
827 			return idx - 1;
828 	} else {
829 		ioc->autop_too_slow_at = 0;
830 	}
831 
832 	return idx;
833 }
834 
835 /*
836  * Take the followings as input
837  *
838  *  @bps	maximum sequential throughput
839  *  @seqiops	maximum sequential 4k iops
840  *  @randiops	maximum random 4k iops
841  *
842  * and calculate the linear model cost coefficients.
843  *
844  *  *@page	per-page cost		1s / (@bps / 4096)
845  *  *@seqio	base cost of a seq IO	max((1s / @seqiops) - *@page, 0)
846  *  @randiops	base cost of a rand IO	max((1s / @randiops) - *@page, 0)
847  */
848 static void calc_lcoefs(u64 bps, u64 seqiops, u64 randiops,
849 			u64 *page, u64 *seqio, u64 *randio)
850 {
851 	u64 v;
852 
853 	*page = *seqio = *randio = 0;
854 
855 	if (bps) {
856 		u64 bps_pages = DIV_ROUND_UP_ULL(bps, IOC_PAGE_SIZE);
857 
858 		if (bps_pages)
859 			*page = DIV64_U64_ROUND_UP(VTIME_PER_SEC, bps_pages);
860 		else
861 			*page = 1;
862 	}
863 
864 	if (seqiops) {
865 		v = DIV64_U64_ROUND_UP(VTIME_PER_SEC, seqiops);
866 		if (v > *page)
867 			*seqio = v - *page;
868 	}
869 
870 	if (randiops) {
871 		v = DIV64_U64_ROUND_UP(VTIME_PER_SEC, randiops);
872 		if (v > *page)
873 			*randio = v - *page;
874 	}
875 }
876 
877 static void ioc_refresh_lcoefs(struct ioc *ioc)
878 {
879 	u64 *u = ioc->params.i_lcoefs;
880 	u64 *c = ioc->params.lcoefs;
881 
882 	calc_lcoefs(u[I_LCOEF_RBPS], u[I_LCOEF_RSEQIOPS], u[I_LCOEF_RRANDIOPS],
883 		    &c[LCOEF_RPAGE], &c[LCOEF_RSEQIO], &c[LCOEF_RRANDIO]);
884 	calc_lcoefs(u[I_LCOEF_WBPS], u[I_LCOEF_WSEQIOPS], u[I_LCOEF_WRANDIOPS],
885 		    &c[LCOEF_WPAGE], &c[LCOEF_WSEQIO], &c[LCOEF_WRANDIO]);
886 }
887 
888 /*
889  * struct gendisk is required as an argument because ioc->rqos.disk
890  * is not properly initialized when called from the init path.
891  */
892 static bool ioc_refresh_params_disk(struct ioc *ioc, bool force,
893 				    struct gendisk *disk)
894 {
895 	const struct ioc_params *p;
896 	int idx;
897 
898 	lockdep_assert_held(&ioc->lock);
899 
900 	idx = ioc_autop_idx(ioc, disk);
901 	p = &autop[idx];
902 
903 	if (idx == ioc->autop_idx && !force)
904 		return false;
905 
906 	if (idx != ioc->autop_idx) {
907 		atomic64_set(&ioc->vtime_rate, VTIME_PER_USEC);
908 		ioc->vtime_base_rate = VTIME_PER_USEC;
909 	}
910 
911 	ioc->autop_idx = idx;
912 	ioc->autop_too_fast_at = 0;
913 	ioc->autop_too_slow_at = 0;
914 
915 	if (!ioc->user_qos_params)
916 		memcpy(ioc->params.qos, p->qos, sizeof(p->qos));
917 	if (!ioc->user_cost_model)
918 		memcpy(ioc->params.i_lcoefs, p->i_lcoefs, sizeof(p->i_lcoefs));
919 
920 	ioc_refresh_period_us(ioc);
921 	ioc_refresh_lcoefs(ioc);
922 
923 	ioc->vrate_min = DIV64_U64_ROUND_UP((u64)ioc->params.qos[QOS_MIN] *
924 					    VTIME_PER_USEC, MILLION);
925 	ioc->vrate_max = DIV64_U64_ROUND_UP((u64)ioc->params.qos[QOS_MAX] *
926 					    VTIME_PER_USEC, MILLION);
927 
928 	return true;
929 }
930 
931 static bool ioc_refresh_params(struct ioc *ioc, bool force)
932 {
933 	return ioc_refresh_params_disk(ioc, force, ioc->rqos.disk);
934 }
935 
936 /*
937  * When an iocg accumulates too much vtime or gets deactivated, we throw away
938  * some vtime, which lowers the overall device utilization. As the exact amount
939  * which is being thrown away is known, we can compensate by accelerating the
940  * vrate accordingly so that the extra vtime generated in the current period
941  * matches what got lost.
942  */
943 static void ioc_refresh_vrate(struct ioc *ioc, struct ioc_now *now)
944 {
945 	s64 pleft = ioc->period_at + ioc->period_us - now->now;
946 	s64 vperiod = ioc->period_us * ioc->vtime_base_rate;
947 	s64 vcomp, vcomp_min, vcomp_max;
948 
949 	lockdep_assert_held(&ioc->lock);
950 
951 	/* we need some time left in this period */
952 	if (pleft <= 0)
953 		goto done;
954 
955 	/*
956 	 * Calculate how much vrate should be adjusted to offset the error.
957 	 * Limit the amount of adjustment and deduct the adjusted amount from
958 	 * the error.
959 	 */
960 	vcomp = -div64_s64(ioc->vtime_err, pleft);
961 	vcomp_min = -(ioc->vtime_base_rate >> 1);
962 	vcomp_max = ioc->vtime_base_rate;
963 	vcomp = clamp(vcomp, vcomp_min, vcomp_max);
964 
965 	ioc->vtime_err += vcomp * pleft;
966 
967 	atomic64_set(&ioc->vtime_rate, ioc->vtime_base_rate + vcomp);
968 done:
969 	/* bound how much error can accumulate */
970 	ioc->vtime_err = clamp(ioc->vtime_err, -vperiod, vperiod);
971 }
972 
973 static void ioc_adjust_base_vrate(struct ioc *ioc, u32 rq_wait_pct,
974 				  int nr_lagging, int nr_shortages,
975 				  int prev_busy_level, u32 *missed_ppm)
976 {
977 	u64 vrate = ioc->vtime_base_rate;
978 	u64 vrate_min = ioc->vrate_min, vrate_max = ioc->vrate_max;
979 
980 	if (!ioc->busy_level || (ioc->busy_level < 0 && nr_lagging)) {
981 		if (ioc->busy_level != prev_busy_level || nr_lagging)
982 			trace_iocost_ioc_vrate_adj(ioc, vrate,
983 						   missed_ppm, rq_wait_pct,
984 						   nr_lagging, nr_shortages);
985 
986 		return;
987 	}
988 
989 	/*
990 	 * If vrate is out of bounds, apply clamp gradually as the
991 	 * bounds can change abruptly.  Otherwise, apply busy_level
992 	 * based adjustment.
993 	 */
994 	if (vrate < vrate_min) {
995 		vrate = div64_u64(vrate * (100 + VRATE_CLAMP_ADJ_PCT), 100);
996 		vrate = min(vrate, vrate_min);
997 	} else if (vrate > vrate_max) {
998 		vrate = div64_u64(vrate * (100 - VRATE_CLAMP_ADJ_PCT), 100);
999 		vrate = max(vrate, vrate_max);
1000 	} else {
1001 		int idx = min_t(int, abs(ioc->busy_level),
1002 				ARRAY_SIZE(vrate_adj_pct) - 1);
1003 		u32 adj_pct = vrate_adj_pct[idx];
1004 
1005 		if (ioc->busy_level > 0)
1006 			adj_pct = 100 - adj_pct;
1007 		else
1008 			adj_pct = 100 + adj_pct;
1009 
1010 		vrate = clamp(DIV64_U64_ROUND_UP(vrate * adj_pct, 100),
1011 			      vrate_min, vrate_max);
1012 	}
1013 
1014 	trace_iocost_ioc_vrate_adj(ioc, vrate, missed_ppm, rq_wait_pct,
1015 				   nr_lagging, nr_shortages);
1016 
1017 	ioc->vtime_base_rate = vrate;
1018 	ioc_refresh_margins(ioc);
1019 }
1020 
1021 /* take a snapshot of the current [v]time and vrate */
1022 static void ioc_now(struct ioc *ioc, struct ioc_now *now)
1023 {
1024 	unsigned seq;
1025 	u64 vrate;
1026 
1027 	now->now_ns = blk_time_get_ns();
1028 	now->now = ktime_to_us(now->now_ns);
1029 	vrate = atomic64_read(&ioc->vtime_rate);
1030 
1031 	/*
1032 	 * The current vtime is
1033 	 *
1034 	 *   vtime at period start + (wallclock time since the start) * vrate
1035 	 *
1036 	 * As a consistent snapshot of `period_at_vtime` and `period_at` is
1037 	 * needed, they're seqcount protected.
1038 	 */
1039 	do {
1040 		seq = read_seqcount_begin(&ioc->period_seqcount);
1041 		now->vnow = ioc->period_at_vtime +
1042 			(now->now - ioc->period_at) * vrate;
1043 	} while (read_seqcount_retry(&ioc->period_seqcount, seq));
1044 }
1045 
1046 static void ioc_start_period(struct ioc *ioc, struct ioc_now *now)
1047 {
1048 	WARN_ON_ONCE(ioc->running != IOC_RUNNING);
1049 
1050 	write_seqcount_begin(&ioc->period_seqcount);
1051 	ioc->period_at = now->now;
1052 	ioc->period_at_vtime = now->vnow;
1053 	write_seqcount_end(&ioc->period_seqcount);
1054 
1055 	ioc->timer.expires = jiffies + usecs_to_jiffies(ioc->period_us);
1056 	add_timer(&ioc->timer);
1057 }
1058 
1059 /*
1060  * Update @iocg's `active` and `inuse` to @active and @inuse, update level
1061  * weight sums and propagate upwards accordingly. If @save, the current margin
1062  * is saved to be used as reference for later inuse in-period adjustments.
1063  */
1064 static void __propagate_weights(struct ioc_gq *iocg, u32 active, u32 inuse,
1065 				bool save, struct ioc_now *now)
1066 {
1067 	struct ioc *ioc = iocg->ioc;
1068 	int lvl;
1069 
1070 	lockdep_assert_held(&ioc->lock);
1071 
1072 	/*
1073 	 * For an active leaf node, its inuse shouldn't be zero or exceed
1074 	 * @active. An active internal node's inuse is solely determined by the
1075 	 * inuse to active ratio of its children regardless of @inuse.
1076 	 */
1077 	if (list_empty(&iocg->active_list) && iocg->child_active_sum) {
1078 		inuse = DIV64_U64_ROUND_UP(active * iocg->child_inuse_sum,
1079 					   iocg->child_active_sum);
1080 	} else {
1081 		/*
1082 		 * It may be tempting to turn this into a clamp expression with
1083 		 * a lower limit of 1 but active may be 0, which cannot be used
1084 		 * as an upper limit in that situation. This expression allows
1085 		 * active to clamp inuse unless it is 0, in which case inuse
1086 		 * becomes 1.
1087 		 */
1088 		inuse = min(inuse, active) ?: 1;
1089 	}
1090 
1091 	iocg->last_inuse = iocg->inuse;
1092 	if (save)
1093 		iocg->saved_margin = now->vnow - atomic64_read(&iocg->vtime);
1094 
1095 	if (active == iocg->active && inuse == iocg->inuse)
1096 		return;
1097 
1098 	for (lvl = iocg->level - 1; lvl >= 0; lvl--) {
1099 		struct ioc_gq *parent = iocg->ancestors[lvl];
1100 		struct ioc_gq *child = iocg->ancestors[lvl + 1];
1101 		u32 parent_active = 0, parent_inuse = 0;
1102 
1103 		/* update the level sums */
1104 		parent->child_active_sum += (s32)(active - child->active);
1105 		parent->child_inuse_sum += (s32)(inuse - child->inuse);
1106 		/* apply the updates */
1107 		child->active = active;
1108 		child->inuse = inuse;
1109 
1110 		/*
1111 		 * The delta between inuse and active sums indicates that
1112 		 * much of weight is being given away.  Parent's inuse
1113 		 * and active should reflect the ratio.
1114 		 */
1115 		if (parent->child_active_sum) {
1116 			parent_active = parent->weight;
1117 			parent_inuse = DIV64_U64_ROUND_UP(
1118 				parent_active * parent->child_inuse_sum,
1119 				parent->child_active_sum);
1120 		}
1121 
1122 		/* do we need to keep walking up? */
1123 		if (parent_active == parent->active &&
1124 		    parent_inuse == parent->inuse)
1125 			break;
1126 
1127 		active = parent_active;
1128 		inuse = parent_inuse;
1129 	}
1130 
1131 	ioc->weights_updated = true;
1132 }
1133 
1134 static void commit_weights(struct ioc *ioc)
1135 {
1136 	lockdep_assert_held(&ioc->lock);
1137 
1138 	if (ioc->weights_updated) {
1139 		/* paired with rmb in current_hweight(), see there */
1140 		smp_wmb();
1141 		atomic_inc(&ioc->hweight_gen);
1142 		ioc->weights_updated = false;
1143 	}
1144 }
1145 
1146 static void propagate_weights(struct ioc_gq *iocg, u32 active, u32 inuse,
1147 			      bool save, struct ioc_now *now)
1148 {
1149 	__propagate_weights(iocg, active, inuse, save, now);
1150 	commit_weights(iocg->ioc);
1151 }
1152 
1153 static void current_hweight(struct ioc_gq *iocg, u32 *hw_activep, u32 *hw_inusep)
1154 {
1155 	struct ioc *ioc = iocg->ioc;
1156 	int lvl;
1157 	u32 hwa, hwi;
1158 	int ioc_gen;
1159 
1160 	/* hot path - if uptodate, use cached */
1161 	ioc_gen = atomic_read(&ioc->hweight_gen);
1162 	if (ioc_gen == iocg->hweight_gen)
1163 		goto out;
1164 
1165 	/*
1166 	 * Paired with wmb in commit_weights(). If we saw the updated
1167 	 * hweight_gen, all the weight updates from __propagate_weights() are
1168 	 * visible too.
1169 	 *
1170 	 * We can race with weight updates during calculation and get it
1171 	 * wrong.  However, hweight_gen would have changed and a future
1172 	 * reader will recalculate and we're guaranteed to discard the
1173 	 * wrong result soon.
1174 	 */
1175 	smp_rmb();
1176 
1177 	hwa = hwi = WEIGHT_ONE;
1178 	for (lvl = 0; lvl <= iocg->level - 1; lvl++) {
1179 		struct ioc_gq *parent = iocg->ancestors[lvl];
1180 		struct ioc_gq *child = iocg->ancestors[lvl + 1];
1181 		u64 active_sum = READ_ONCE(parent->child_active_sum);
1182 		u64 inuse_sum = READ_ONCE(parent->child_inuse_sum);
1183 		u32 active = READ_ONCE(child->active);
1184 		u32 inuse = READ_ONCE(child->inuse);
1185 
1186 		/* we can race with deactivations and either may read as zero */
1187 		if (!active_sum || !inuse_sum)
1188 			continue;
1189 
1190 		active_sum = max_t(u64, active, active_sum);
1191 		hwa = div64_u64((u64)hwa * active, active_sum);
1192 
1193 		inuse_sum = max_t(u64, inuse, inuse_sum);
1194 		hwi = div64_u64((u64)hwi * inuse, inuse_sum);
1195 	}
1196 
1197 	iocg->hweight_active = max_t(u32, hwa, 1);
1198 	iocg->hweight_inuse = max_t(u32, hwi, 1);
1199 	iocg->hweight_gen = ioc_gen;
1200 out:
1201 	if (hw_activep)
1202 		*hw_activep = iocg->hweight_active;
1203 	if (hw_inusep)
1204 		*hw_inusep = iocg->hweight_inuse;
1205 }
1206 
1207 /*
1208  * Calculate the hweight_inuse @iocg would get with max @inuse assuming all the
1209  * other weights stay unchanged.
1210  */
1211 static u32 current_hweight_max(struct ioc_gq *iocg)
1212 {
1213 	u32 hwm = WEIGHT_ONE;
1214 	u32 inuse = iocg->active;
1215 	u64 child_inuse_sum;
1216 	int lvl;
1217 
1218 	lockdep_assert_held(&iocg->ioc->lock);
1219 
1220 	for (lvl = iocg->level - 1; lvl >= 0; lvl--) {
1221 		struct ioc_gq *parent = iocg->ancestors[lvl];
1222 		struct ioc_gq *child = iocg->ancestors[lvl + 1];
1223 
1224 		child_inuse_sum = parent->child_inuse_sum + inuse - child->inuse;
1225 		hwm = div64_u64((u64)hwm * inuse, child_inuse_sum);
1226 		inuse = DIV64_U64_ROUND_UP(parent->active * child_inuse_sum,
1227 					   parent->child_active_sum);
1228 	}
1229 
1230 	return max_t(u32, hwm, 1);
1231 }
1232 
1233 static void weight_updated(struct ioc_gq *iocg, struct ioc_now *now)
1234 {
1235 	struct ioc *ioc = iocg->ioc;
1236 	struct blkcg_gq *blkg = iocg_to_blkg(iocg);
1237 	struct ioc_cgrp *iocc = blkcg_to_iocc(blkg->blkcg);
1238 	u32 weight;
1239 
1240 	lockdep_assert_held(&ioc->lock);
1241 
1242 	weight = iocg->cfg_weight ?: iocc->dfl_weight;
1243 	if (weight != iocg->weight && iocg->active)
1244 		propagate_weights(iocg, weight, iocg->inuse, true, now);
1245 	iocg->weight = weight;
1246 }
1247 
1248 static bool iocg_activate(struct ioc_gq *iocg, struct ioc_now *now)
1249 {
1250 	struct ioc *ioc = iocg->ioc;
1251 	u64 __maybe_unused last_period, cur_period;
1252 	u64 vtime, vtarget;
1253 	int i;
1254 
1255 	/*
1256 	 * If seem to be already active, just update the stamp to tell the
1257 	 * timer that we're still active.  We don't mind occassional races.
1258 	 */
1259 	if (!list_empty(&iocg->active_list)) {
1260 		ioc_now(ioc, now);
1261 		cur_period = atomic64_read(&ioc->cur_period);
1262 		if (atomic64_read(&iocg->active_period) != cur_period)
1263 			atomic64_set(&iocg->active_period, cur_period);
1264 		return true;
1265 	}
1266 
1267 	/* racy check on internal node IOs, treat as root level IOs */
1268 	if (iocg->child_active_sum)
1269 		return false;
1270 
1271 	spin_lock_irq(&ioc->lock);
1272 
1273 	ioc_now(ioc, now);
1274 
1275 	/* update period */
1276 	cur_period = atomic64_read(&ioc->cur_period);
1277 	last_period = atomic64_read(&iocg->active_period);
1278 	atomic64_set(&iocg->active_period, cur_period);
1279 
1280 	/* already activated or breaking leaf-only constraint? */
1281 	if (!list_empty(&iocg->active_list))
1282 		goto succeed_unlock;
1283 	for (i = iocg->level - 1; i > 0; i--)
1284 		if (!list_empty(&iocg->ancestors[i]->active_list))
1285 			goto fail_unlock;
1286 
1287 	if (iocg->child_active_sum)
1288 		goto fail_unlock;
1289 
1290 	/*
1291 	 * Always start with the target budget. On deactivation, we throw away
1292 	 * anything above it.
1293 	 */
1294 	vtarget = now->vnow - ioc->margins.target;
1295 	vtime = atomic64_read(&iocg->vtime);
1296 
1297 	atomic64_add(vtarget - vtime, &iocg->vtime);
1298 	atomic64_add(vtarget - vtime, &iocg->done_vtime);
1299 	vtime = vtarget;
1300 
1301 	/*
1302 	 * Activate, propagate weight and start period timer if not
1303 	 * running.  Reset hweight_gen to avoid accidental match from
1304 	 * wrapping.
1305 	 */
1306 	iocg->hweight_gen = atomic_read(&ioc->hweight_gen) - 1;
1307 	list_add(&iocg->active_list, &ioc->active_iocgs);
1308 
1309 	propagate_weights(iocg, iocg->weight,
1310 			  iocg->last_inuse ?: iocg->weight, true, now);
1311 
1312 	TRACE_IOCG_PATH(iocg_activate, iocg, now,
1313 			last_period, cur_period, vtime);
1314 
1315 	iocg->activated_at = now->now;
1316 
1317 	if (ioc->running == IOC_IDLE) {
1318 		ioc->running = IOC_RUNNING;
1319 		ioc->dfgv_period_at = now->now;
1320 		ioc->dfgv_period_rem = 0;
1321 		ioc_start_period(ioc, now);
1322 	}
1323 
1324 succeed_unlock:
1325 	spin_unlock_irq(&ioc->lock);
1326 	return true;
1327 
1328 fail_unlock:
1329 	spin_unlock_irq(&ioc->lock);
1330 	return false;
1331 }
1332 
1333 static bool iocg_kick_delay(struct ioc_gq *iocg, struct ioc_now *now)
1334 {
1335 	struct ioc *ioc = iocg->ioc;
1336 	struct blkcg_gq *blkg = iocg_to_blkg(iocg);
1337 	u64 tdelta, delay, new_delay, shift;
1338 	s64 vover, vover_pct;
1339 	u32 hwa;
1340 
1341 	lockdep_assert_held(&iocg->waitq.lock);
1342 
1343 	/*
1344 	 * If the delay is set by another CPU, we may be in the past. No need to
1345 	 * change anything if so. This avoids decay calculation underflow.
1346 	 */
1347 	if (time_before64(now->now, iocg->delay_at))
1348 		return false;
1349 
1350 	/* calculate the current delay in effect - 1/2 every second */
1351 	tdelta = now->now - iocg->delay_at;
1352 	shift = div64_u64(tdelta, USEC_PER_SEC);
1353 	if (iocg->delay && shift < BITS_PER_LONG)
1354 		delay = iocg->delay >> shift;
1355 	else
1356 		delay = 0;
1357 
1358 	/* calculate the new delay from the debt amount */
1359 	current_hweight(iocg, &hwa, NULL);
1360 	vover = atomic64_read(&iocg->vtime) +
1361 		abs_cost_to_cost(iocg->abs_vdebt, hwa) - now->vnow;
1362 	vover_pct = div64_s64(100 * vover,
1363 			      ioc->period_us * ioc->vtime_base_rate);
1364 
1365 	if (vover_pct <= MIN_DELAY_THR_PCT)
1366 		new_delay = 0;
1367 	else if (vover_pct >= MAX_DELAY_THR_PCT)
1368 		new_delay = MAX_DELAY;
1369 	else
1370 		new_delay = MIN_DELAY +
1371 			div_u64((MAX_DELAY - MIN_DELAY) *
1372 				(vover_pct - MIN_DELAY_THR_PCT),
1373 				MAX_DELAY_THR_PCT - MIN_DELAY_THR_PCT);
1374 
1375 	/* pick the higher one and apply */
1376 	if (new_delay > delay) {
1377 		iocg->delay = new_delay;
1378 		iocg->delay_at = now->now;
1379 		delay = new_delay;
1380 	}
1381 
1382 	if (delay >= MIN_DELAY) {
1383 		if (!iocg->indelay_since)
1384 			iocg->indelay_since = now->now;
1385 		blkcg_set_delay(blkg, delay * NSEC_PER_USEC);
1386 		return true;
1387 	} else {
1388 		if (iocg->indelay_since) {
1389 			iocg->stat.indelay_us += now->now - iocg->indelay_since;
1390 			iocg->indelay_since = 0;
1391 		}
1392 		iocg->delay = 0;
1393 		blkcg_clear_delay(blkg);
1394 		return false;
1395 	}
1396 }
1397 
1398 static void iocg_incur_debt(struct ioc_gq *iocg, u64 abs_cost,
1399 			    struct ioc_now *now)
1400 {
1401 	struct iocg_pcpu_stat *gcs;
1402 
1403 	lockdep_assert_held(&iocg->ioc->lock);
1404 	lockdep_assert_held(&iocg->waitq.lock);
1405 	WARN_ON_ONCE(list_empty(&iocg->active_list));
1406 
1407 	/*
1408 	 * Once in debt, debt handling owns inuse. @iocg stays at the minimum
1409 	 * inuse donating all of it share to others until its debt is paid off.
1410 	 */
1411 	if (!iocg->abs_vdebt && abs_cost) {
1412 		iocg->indebt_since = now->now;
1413 		propagate_weights(iocg, iocg->active, 0, false, now);
1414 	}
1415 
1416 	iocg->abs_vdebt += abs_cost;
1417 
1418 	gcs = get_cpu_ptr(iocg->pcpu_stat);
1419 	local64_add(abs_cost, &gcs->abs_vusage);
1420 	put_cpu_ptr(gcs);
1421 }
1422 
1423 static void iocg_pay_debt(struct ioc_gq *iocg, u64 abs_vpay,
1424 			  struct ioc_now *now)
1425 {
1426 	lockdep_assert_held(&iocg->ioc->lock);
1427 	lockdep_assert_held(&iocg->waitq.lock);
1428 
1429 	/*
1430 	 * make sure that nobody messed with @iocg. Check iocg->pd.online
1431 	 * to avoid warn when removing blkcg or disk.
1432 	 */
1433 	WARN_ON_ONCE(list_empty(&iocg->active_list) && iocg->pd.online);
1434 	WARN_ON_ONCE(iocg->inuse > 1);
1435 
1436 	iocg->abs_vdebt -= min(abs_vpay, iocg->abs_vdebt);
1437 
1438 	/* if debt is paid in full, restore inuse */
1439 	if (!iocg->abs_vdebt) {
1440 		iocg->stat.indebt_us += now->now - iocg->indebt_since;
1441 		iocg->indebt_since = 0;
1442 
1443 		propagate_weights(iocg, iocg->active, iocg->last_inuse,
1444 				  false, now);
1445 	}
1446 }
1447 
1448 static int iocg_wake_fn(struct wait_queue_entry *wq_entry, unsigned mode,
1449 			int flags, void *key)
1450 {
1451 	struct iocg_wait *wait = container_of(wq_entry, struct iocg_wait, wait);
1452 	struct iocg_wake_ctx *ctx = key;
1453 	u64 cost = abs_cost_to_cost(wait->abs_cost, ctx->hw_inuse);
1454 
1455 	ctx->vbudget -= cost;
1456 
1457 	if (ctx->vbudget < 0)
1458 		return -1;
1459 
1460 	iocg_commit_bio(ctx->iocg, wait->bio, wait->abs_cost, cost);
1461 	wait->committed = true;
1462 
1463 	/*
1464 	 * autoremove_wake_function() removes the wait entry only when it
1465 	 * actually changed the task state. We want the wait always removed.
1466 	 * Remove explicitly and use default_wake_function(). Note that the
1467 	 * order of operations is important as finish_wait() tests whether
1468 	 * @wq_entry is removed without grabbing the lock.
1469 	 */
1470 	default_wake_function(wq_entry, mode, flags, key);
1471 	list_del_init_careful(&wq_entry->entry);
1472 	return 0;
1473 }
1474 
1475 /*
1476  * Calculate the accumulated budget, pay debt if @pay_debt and wake up waiters
1477  * accordingly. When @pay_debt is %true, the caller must be holding ioc->lock in
1478  * addition to iocg->waitq.lock.
1479  */
1480 static void iocg_kick_waitq(struct ioc_gq *iocg, bool pay_debt,
1481 			    struct ioc_now *now)
1482 {
1483 	struct ioc *ioc = iocg->ioc;
1484 	struct iocg_wake_ctx ctx = { .iocg = iocg };
1485 	u64 vshortage, expires, oexpires;
1486 	s64 vbudget;
1487 	u32 hwa;
1488 
1489 	lockdep_assert_held(&iocg->waitq.lock);
1490 
1491 	current_hweight(iocg, &hwa, NULL);
1492 	vbudget = now->vnow - atomic64_read(&iocg->vtime);
1493 
1494 	/* pay off debt */
1495 	if (pay_debt && iocg->abs_vdebt && vbudget > 0) {
1496 		u64 abs_vbudget = cost_to_abs_cost(vbudget, hwa);
1497 		u64 abs_vpay = min_t(u64, abs_vbudget, iocg->abs_vdebt);
1498 		u64 vpay = abs_cost_to_cost(abs_vpay, hwa);
1499 
1500 		lockdep_assert_held(&ioc->lock);
1501 
1502 		atomic64_add(vpay, &iocg->vtime);
1503 		atomic64_add(vpay, &iocg->done_vtime);
1504 		iocg_pay_debt(iocg, abs_vpay, now);
1505 		vbudget -= vpay;
1506 	}
1507 
1508 	if (iocg->abs_vdebt || iocg->delay)
1509 		iocg_kick_delay(iocg, now);
1510 
1511 	/*
1512 	 * Debt can still be outstanding if we haven't paid all yet or the
1513 	 * caller raced and called without @pay_debt. Shouldn't wake up waiters
1514 	 * under debt. Make sure @vbudget reflects the outstanding amount and is
1515 	 * not positive.
1516 	 */
1517 	if (iocg->abs_vdebt) {
1518 		s64 vdebt = abs_cost_to_cost(iocg->abs_vdebt, hwa);
1519 		vbudget = min_t(s64, 0, vbudget - vdebt);
1520 	}
1521 
1522 	/*
1523 	 * Wake up the ones which are due and see how much vtime we'll need for
1524 	 * the next one. As paying off debt restores hw_inuse, it must be read
1525 	 * after the above debt payment.
1526 	 */
1527 	ctx.vbudget = vbudget;
1528 	current_hweight(iocg, NULL, &ctx.hw_inuse);
1529 
1530 	__wake_up_locked_key(&iocg->waitq, TASK_NORMAL, &ctx);
1531 
1532 	if (!waitqueue_active(&iocg->waitq)) {
1533 		if (iocg->wait_since) {
1534 			iocg->stat.wait_us += now->now - iocg->wait_since;
1535 			iocg->wait_since = 0;
1536 		}
1537 		return;
1538 	}
1539 
1540 	if (!iocg->wait_since)
1541 		iocg->wait_since = now->now;
1542 
1543 	if (WARN_ON_ONCE(ctx.vbudget >= 0))
1544 		return;
1545 
1546 	/* determine next wakeup, add a timer margin to guarantee chunking */
1547 	vshortage = -ctx.vbudget;
1548 	expires = now->now_ns +
1549 		DIV64_U64_ROUND_UP(vshortage, ioc->vtime_base_rate) *
1550 		NSEC_PER_USEC;
1551 	expires += ioc->timer_slack_ns;
1552 
1553 	/* if already active and close enough, don't bother */
1554 	oexpires = ktime_to_ns(hrtimer_get_softexpires(&iocg->waitq_timer));
1555 	if (hrtimer_is_queued(&iocg->waitq_timer) &&
1556 	    abs(oexpires - expires) <= ioc->timer_slack_ns)
1557 		return;
1558 
1559 	hrtimer_start_range_ns(&iocg->waitq_timer, ns_to_ktime(expires),
1560 			       ioc->timer_slack_ns, HRTIMER_MODE_ABS);
1561 }
1562 
1563 static enum hrtimer_restart iocg_waitq_timer_fn(struct hrtimer *timer)
1564 {
1565 	struct ioc_gq *iocg = container_of(timer, struct ioc_gq, waitq_timer);
1566 	bool pay_debt = READ_ONCE(iocg->abs_vdebt);
1567 	struct ioc_now now;
1568 	unsigned long flags;
1569 
1570 	ioc_now(iocg->ioc, &now);
1571 
1572 	if (pay_debt) {
1573 		spin_lock_irqsave(&iocg->ioc->lock, flags);
1574 		spin_lock(&iocg->waitq.lock);
1575 		iocg_kick_waitq(iocg, pay_debt, &now);
1576 		spin_unlock(&iocg->waitq.lock);
1577 		spin_unlock_irqrestore(&iocg->ioc->lock, flags);
1578 	} else {
1579 		spin_lock_irqsave(&iocg->waitq.lock, flags);
1580 		iocg_kick_waitq(iocg, pay_debt, &now);
1581 		spin_unlock_irqrestore(&iocg->waitq.lock, flags);
1582 	}
1583 
1584 	return HRTIMER_NORESTART;
1585 }
1586 
1587 static void ioc_lat_stat(struct ioc *ioc, u32 *missed_ppm_ar, u32 *rq_wait_pct_p,
1588 			 u32 *nr_done)
1589 {
1590 	u32 nr_met[2] = { };
1591 	u32 nr_missed[2] = { };
1592 	u64 rq_wait_ns = 0;
1593 	int cpu, rw;
1594 
1595 	for_each_online_cpu(cpu) {
1596 		struct ioc_pcpu_stat *stat = per_cpu_ptr(ioc->pcpu_stat, cpu);
1597 		u64 this_rq_wait_ns;
1598 
1599 		for (rw = READ; rw <= WRITE; rw++) {
1600 			u32 this_met = local_read(&stat->missed[rw].nr_met);
1601 			u32 this_missed = local_read(&stat->missed[rw].nr_missed);
1602 
1603 			nr_met[rw] += this_met - stat->missed[rw].last_met;
1604 			nr_missed[rw] += this_missed - stat->missed[rw].last_missed;
1605 			stat->missed[rw].last_met = this_met;
1606 			stat->missed[rw].last_missed = this_missed;
1607 		}
1608 
1609 		this_rq_wait_ns = local64_read(&stat->rq_wait_ns);
1610 		rq_wait_ns += this_rq_wait_ns - stat->last_rq_wait_ns;
1611 		stat->last_rq_wait_ns = this_rq_wait_ns;
1612 	}
1613 
1614 	for (rw = READ; rw <= WRITE; rw++) {
1615 		if (nr_met[rw] + nr_missed[rw])
1616 			missed_ppm_ar[rw] =
1617 				DIV64_U64_ROUND_UP((u64)nr_missed[rw] * MILLION,
1618 						   nr_met[rw] + nr_missed[rw]);
1619 		else
1620 			missed_ppm_ar[rw] = 0;
1621 	}
1622 
1623 	*rq_wait_pct_p = div64_u64(rq_wait_ns * 100,
1624 				   ioc->period_us * NSEC_PER_USEC);
1625 
1626 	*nr_done = nr_met[READ] + nr_met[WRITE] + nr_missed[READ] + nr_missed[WRITE];
1627 }
1628 
1629 /* was iocg idle this period? */
1630 static bool iocg_is_idle(struct ioc_gq *iocg)
1631 {
1632 	struct ioc *ioc = iocg->ioc;
1633 
1634 	/* did something get issued this period? */
1635 	if (atomic64_read(&iocg->active_period) ==
1636 	    atomic64_read(&ioc->cur_period))
1637 		return false;
1638 
1639 	/* is something in flight? */
1640 	if (atomic64_read(&iocg->done_vtime) != atomic64_read(&iocg->vtime))
1641 		return false;
1642 
1643 	return true;
1644 }
1645 
1646 /*
1647  * Call this function on the target leaf @iocg's to build pre-order traversal
1648  * list of all the ancestors in @inner_walk. The inner nodes are linked through
1649  * ->walk_list and the caller is responsible for dissolving the list after use.
1650  */
1651 static void iocg_build_inner_walk(struct ioc_gq *iocg,
1652 				  struct list_head *inner_walk)
1653 {
1654 	int lvl;
1655 
1656 	WARN_ON_ONCE(!list_empty(&iocg->walk_list));
1657 
1658 	/* find the first ancestor which hasn't been visited yet */
1659 	for (lvl = iocg->level - 1; lvl >= 0; lvl--) {
1660 		if (!list_empty(&iocg->ancestors[lvl]->walk_list))
1661 			break;
1662 	}
1663 
1664 	/* walk down and visit the inner nodes to get pre-order traversal */
1665 	while (++lvl <= iocg->level - 1) {
1666 		struct ioc_gq *inner = iocg->ancestors[lvl];
1667 
1668 		/* record traversal order */
1669 		list_add_tail(&inner->walk_list, inner_walk);
1670 	}
1671 }
1672 
1673 /* propagate the deltas to the parent */
1674 static void iocg_flush_stat_upward(struct ioc_gq *iocg)
1675 {
1676 	if (iocg->level > 0) {
1677 		struct iocg_stat *parent_stat =
1678 			&iocg->ancestors[iocg->level - 1]->stat;
1679 
1680 		parent_stat->usage_us +=
1681 			iocg->stat.usage_us - iocg->last_stat.usage_us;
1682 		parent_stat->wait_us +=
1683 			iocg->stat.wait_us - iocg->last_stat.wait_us;
1684 		parent_stat->indebt_us +=
1685 			iocg->stat.indebt_us - iocg->last_stat.indebt_us;
1686 		parent_stat->indelay_us +=
1687 			iocg->stat.indelay_us - iocg->last_stat.indelay_us;
1688 	}
1689 
1690 	iocg->last_stat = iocg->stat;
1691 }
1692 
1693 /* collect per-cpu counters and propagate the deltas to the parent */
1694 static void iocg_flush_stat_leaf(struct ioc_gq *iocg, struct ioc_now *now)
1695 {
1696 	struct ioc *ioc = iocg->ioc;
1697 	u64 abs_vusage = 0;
1698 	u64 vusage_delta;
1699 	int cpu;
1700 
1701 	lockdep_assert_held(&iocg->ioc->lock);
1702 
1703 	/* collect per-cpu counters */
1704 	for_each_possible_cpu(cpu) {
1705 		abs_vusage += local64_read(
1706 				per_cpu_ptr(&iocg->pcpu_stat->abs_vusage, cpu));
1707 	}
1708 	vusage_delta = abs_vusage - iocg->last_stat_abs_vusage;
1709 	iocg->last_stat_abs_vusage = abs_vusage;
1710 
1711 	iocg->usage_delta_us = div64_u64(vusage_delta, ioc->vtime_base_rate);
1712 	iocg->stat.usage_us += iocg->usage_delta_us;
1713 
1714 	iocg_flush_stat_upward(iocg);
1715 }
1716 
1717 /* get stat counters ready for reading on all active iocgs */
1718 static void iocg_flush_stat(struct list_head *target_iocgs, struct ioc_now *now)
1719 {
1720 	LIST_HEAD(inner_walk);
1721 	struct ioc_gq *iocg, *tiocg;
1722 
1723 	/* flush leaves and build inner node walk list */
1724 	list_for_each_entry(iocg, target_iocgs, active_list) {
1725 		iocg_flush_stat_leaf(iocg, now);
1726 		iocg_build_inner_walk(iocg, &inner_walk);
1727 	}
1728 
1729 	/* keep flushing upwards by walking the inner list backwards */
1730 	list_for_each_entry_safe_reverse(iocg, tiocg, &inner_walk, walk_list) {
1731 		iocg_flush_stat_upward(iocg);
1732 		list_del_init(&iocg->walk_list);
1733 	}
1734 }
1735 
1736 /*
1737  * Determine what @iocg's hweight_inuse should be after donating unused
1738  * capacity. @hwm is the upper bound and used to signal no donation. This
1739  * function also throws away @iocg's excess budget.
1740  */
1741 static u32 hweight_after_donation(struct ioc_gq *iocg, u32 old_hwi, u32 hwm,
1742 				  u32 usage, struct ioc_now *now)
1743 {
1744 	struct ioc *ioc = iocg->ioc;
1745 	u64 vtime = atomic64_read(&iocg->vtime);
1746 	s64 excess, delta, target, new_hwi;
1747 
1748 	/* debt handling owns inuse for debtors */
1749 	if (iocg->abs_vdebt)
1750 		return 1;
1751 
1752 	/* see whether minimum margin requirement is met */
1753 	if (waitqueue_active(&iocg->waitq) ||
1754 	    time_after64(vtime, now->vnow - ioc->margins.min))
1755 		return hwm;
1756 
1757 	/* throw away excess above target */
1758 	excess = now->vnow - vtime - ioc->margins.target;
1759 	if (excess > 0) {
1760 		atomic64_add(excess, &iocg->vtime);
1761 		atomic64_add(excess, &iocg->done_vtime);
1762 		vtime += excess;
1763 		ioc->vtime_err -= div64_u64(excess * old_hwi, WEIGHT_ONE);
1764 	}
1765 
1766 	/*
1767 	 * Let's say the distance between iocg's and device's vtimes as a
1768 	 * fraction of period duration is delta. Assuming that the iocg will
1769 	 * consume the usage determined above, we want to determine new_hwi so
1770 	 * that delta equals MARGIN_TARGET at the end of the next period.
1771 	 *
1772 	 * We need to execute usage worth of IOs while spending the sum of the
1773 	 * new budget (1 - MARGIN_TARGET) and the leftover from the last period
1774 	 * (delta):
1775 	 *
1776 	 *   usage = (1 - MARGIN_TARGET + delta) * new_hwi
1777 	 *
1778 	 * Therefore, the new_hwi is:
1779 	 *
1780 	 *   new_hwi = usage / (1 - MARGIN_TARGET + delta)
1781 	 */
1782 	delta = div64_s64(WEIGHT_ONE * (now->vnow - vtime),
1783 			  now->vnow - ioc->period_at_vtime);
1784 	target = WEIGHT_ONE * MARGIN_TARGET_PCT / 100;
1785 	new_hwi = div64_s64(WEIGHT_ONE * usage, WEIGHT_ONE - target + delta);
1786 
1787 	return clamp_t(s64, new_hwi, 1, hwm);
1788 }
1789 
1790 /*
1791  * For work-conservation, an iocg which isn't using all of its share should
1792  * donate the leftover to other iocgs. There are two ways to achieve this - 1.
1793  * bumping up vrate accordingly 2. lowering the donating iocg's inuse weight.
1794  *
1795  * #1 is mathematically simpler but has the drawback of requiring synchronous
1796  * global hweight_inuse updates when idle iocg's get activated or inuse weights
1797  * change due to donation snapbacks as it has the possibility of grossly
1798  * overshooting what's allowed by the model and vrate.
1799  *
1800  * #2 is inherently safe with local operations. The donating iocg can easily
1801  * snap back to higher weights when needed without worrying about impacts on
1802  * other nodes as the impacts will be inherently correct. This also makes idle
1803  * iocg activations safe. The only effect activations have is decreasing
1804  * hweight_inuse of others, the right solution to which is for those iocgs to
1805  * snap back to higher weights.
1806  *
1807  * So, we go with #2. The challenge is calculating how each donating iocg's
1808  * inuse should be adjusted to achieve the target donation amounts. This is done
1809  * using Andy's method described in the following pdf.
1810  *
1811  *   https://drive.google.com/file/d/1PsJwxPFtjUnwOY1QJ5AeICCcsL7BM3bo
1812  *
1813  * Given the weights and target after-donation hweight_inuse values, Andy's
1814  * method determines how the proportional distribution should look like at each
1815  * sibling level to maintain the relative relationship between all non-donating
1816  * pairs. To roughly summarize, it divides the tree into donating and
1817  * non-donating parts, calculates global donation rate which is used to
1818  * determine the target hweight_inuse for each node, and then derives per-level
1819  * proportions.
1820  *
1821  * The following pdf shows that global distribution calculated this way can be
1822  * achieved by scaling inuse weights of donating leaves and propagating the
1823  * adjustments upwards proportionally.
1824  *
1825  *   https://drive.google.com/file/d/1vONz1-fzVO7oY5DXXsLjSxEtYYQbOvsE
1826  *
1827  * Combining the above two, we can determine how each leaf iocg's inuse should
1828  * be adjusted to achieve the target donation.
1829  *
1830  *   https://drive.google.com/file/d/1WcrltBOSPN0qXVdBgnKm4mdp9FhuEFQN
1831  *
1832  * The inline comments use symbols from the last pdf.
1833  *
1834  *   b is the sum of the absolute budgets in the subtree. 1 for the root node.
1835  *   f is the sum of the absolute budgets of non-donating nodes in the subtree.
1836  *   t is the sum of the absolute budgets of donating nodes in the subtree.
1837  *   w is the weight of the node. w = w_f + w_t
1838  *   w_f is the non-donating portion of w. w_f = w * f / b
1839  *   w_b is the donating portion of w. w_t = w * t / b
1840  *   s is the sum of all sibling weights. s = Sum(w) for siblings
1841  *   s_f and s_t are the non-donating and donating portions of s.
1842  *
1843  * Subscript p denotes the parent's counterpart and ' the adjusted value - e.g.
1844  * w_pt is the donating portion of the parent's weight and w'_pt the same value
1845  * after adjustments. Subscript r denotes the root node's values.
1846  */
1847 static void transfer_surpluses(struct list_head *surpluses, struct ioc_now *now)
1848 {
1849 	LIST_HEAD(over_hwa);
1850 	LIST_HEAD(inner_walk);
1851 	struct ioc_gq *iocg, *tiocg, *root_iocg;
1852 	u32 after_sum, over_sum, over_target, gamma;
1853 
1854 	/*
1855 	 * It's pretty unlikely but possible for the total sum of
1856 	 * hweight_after_donation's to be higher than WEIGHT_ONE, which will
1857 	 * confuse the following calculations. If such condition is detected,
1858 	 * scale down everyone over its full share equally to keep the sum below
1859 	 * WEIGHT_ONE.
1860 	 */
1861 	after_sum = 0;
1862 	over_sum = 0;
1863 	list_for_each_entry(iocg, surpluses, surplus_list) {
1864 		u32 hwa;
1865 
1866 		current_hweight(iocg, &hwa, NULL);
1867 		after_sum += iocg->hweight_after_donation;
1868 
1869 		if (iocg->hweight_after_donation > hwa) {
1870 			over_sum += iocg->hweight_after_donation;
1871 			list_add(&iocg->walk_list, &over_hwa);
1872 		}
1873 	}
1874 
1875 	if (after_sum >= WEIGHT_ONE) {
1876 		/*
1877 		 * The delta should be deducted from the over_sum, calculate
1878 		 * target over_sum value.
1879 		 */
1880 		u32 over_delta = after_sum - (WEIGHT_ONE - 1);
1881 		WARN_ON_ONCE(over_sum <= over_delta);
1882 		over_target = over_sum - over_delta;
1883 	} else {
1884 		over_target = 0;
1885 	}
1886 
1887 	list_for_each_entry_safe(iocg, tiocg, &over_hwa, walk_list) {
1888 		if (over_target)
1889 			iocg->hweight_after_donation =
1890 				div_u64((u64)iocg->hweight_after_donation *
1891 					over_target, over_sum);
1892 		list_del_init(&iocg->walk_list);
1893 	}
1894 
1895 	/*
1896 	 * Build pre-order inner node walk list and prepare for donation
1897 	 * adjustment calculations.
1898 	 */
1899 	list_for_each_entry(iocg, surpluses, surplus_list) {
1900 		iocg_build_inner_walk(iocg, &inner_walk);
1901 	}
1902 
1903 	root_iocg = list_first_entry(&inner_walk, struct ioc_gq, walk_list);
1904 	WARN_ON_ONCE(root_iocg->level > 0);
1905 
1906 	list_for_each_entry(iocg, &inner_walk, walk_list) {
1907 		iocg->child_adjusted_sum = 0;
1908 		iocg->hweight_donating = 0;
1909 		iocg->hweight_after_donation = 0;
1910 	}
1911 
1912 	/*
1913 	 * Propagate the donating budget (b_t) and after donation budget (b'_t)
1914 	 * up the hierarchy.
1915 	 */
1916 	list_for_each_entry(iocg, surpluses, surplus_list) {
1917 		struct ioc_gq *parent = iocg->ancestors[iocg->level - 1];
1918 
1919 		parent->hweight_donating += iocg->hweight_donating;
1920 		parent->hweight_after_donation += iocg->hweight_after_donation;
1921 	}
1922 
1923 	list_for_each_entry_reverse(iocg, &inner_walk, walk_list) {
1924 		if (iocg->level > 0) {
1925 			struct ioc_gq *parent = iocg->ancestors[iocg->level - 1];
1926 
1927 			parent->hweight_donating += iocg->hweight_donating;
1928 			parent->hweight_after_donation += iocg->hweight_after_donation;
1929 		}
1930 	}
1931 
1932 	/*
1933 	 * Calculate inner hwa's (b) and make sure the donation values are
1934 	 * within the accepted ranges as we're doing low res calculations with
1935 	 * roundups.
1936 	 */
1937 	list_for_each_entry(iocg, &inner_walk, walk_list) {
1938 		if (iocg->level) {
1939 			struct ioc_gq *parent = iocg->ancestors[iocg->level - 1];
1940 
1941 			iocg->hweight_active = DIV64_U64_ROUND_UP(
1942 				(u64)parent->hweight_active * iocg->active,
1943 				parent->child_active_sum);
1944 
1945 		}
1946 
1947 		iocg->hweight_donating = min(iocg->hweight_donating,
1948 					     iocg->hweight_active);
1949 		iocg->hweight_after_donation = min(iocg->hweight_after_donation,
1950 						   iocg->hweight_donating - 1);
1951 		if (WARN_ON_ONCE(iocg->hweight_active <= 1 ||
1952 				 iocg->hweight_donating <= 1 ||
1953 				 iocg->hweight_after_donation == 0)) {
1954 			pr_warn("iocg: invalid donation weights in ");
1955 			pr_cont_cgroup_path(iocg_to_blkg(iocg)->blkcg->css.cgroup);
1956 			pr_cont(": active=%u donating=%u after=%u\n",
1957 				iocg->hweight_active, iocg->hweight_donating,
1958 				iocg->hweight_after_donation);
1959 		}
1960 	}
1961 
1962 	/*
1963 	 * Calculate the global donation rate (gamma) - the rate to adjust
1964 	 * non-donating budgets by.
1965 	 *
1966 	 * No need to use 64bit multiplication here as the first operand is
1967 	 * guaranteed to be smaller than WEIGHT_ONE (1<<16).
1968 	 *
1969 	 * We know that there are beneficiary nodes and the sum of the donating
1970 	 * hweights can't be whole; however, due to the round-ups during hweight
1971 	 * calculations, root_iocg->hweight_donating might still end up equal to
1972 	 * or greater than whole. Limit the range when calculating the divider.
1973 	 *
1974 	 * gamma = (1 - t_r') / (1 - t_r)
1975 	 */
1976 	gamma = DIV_ROUND_UP(
1977 		(WEIGHT_ONE - root_iocg->hweight_after_donation) * WEIGHT_ONE,
1978 		WEIGHT_ONE - min_t(u32, root_iocg->hweight_donating, WEIGHT_ONE - 1));
1979 
1980 	/*
1981 	 * Calculate adjusted hwi, child_adjusted_sum and inuse for the inner
1982 	 * nodes.
1983 	 */
1984 	list_for_each_entry(iocg, &inner_walk, walk_list) {
1985 		struct ioc_gq *parent;
1986 		u32 inuse, wpt, wptp;
1987 		u64 st, sf;
1988 
1989 		if (iocg->level == 0) {
1990 			/* adjusted weight sum for 1st level: s' = s * b_pf / b'_pf */
1991 			iocg->child_adjusted_sum = DIV64_U64_ROUND_UP(
1992 				iocg->child_active_sum * (WEIGHT_ONE - iocg->hweight_donating),
1993 				WEIGHT_ONE - iocg->hweight_after_donation);
1994 			continue;
1995 		}
1996 
1997 		parent = iocg->ancestors[iocg->level - 1];
1998 
1999 		/* b' = gamma * b_f + b_t' */
2000 		iocg->hweight_inuse = DIV64_U64_ROUND_UP(
2001 			(u64)gamma * (iocg->hweight_active - iocg->hweight_donating),
2002 			WEIGHT_ONE) + iocg->hweight_after_donation;
2003 
2004 		/* w' = s' * b' / b'_p */
2005 		inuse = DIV64_U64_ROUND_UP(
2006 			(u64)parent->child_adjusted_sum * iocg->hweight_inuse,
2007 			parent->hweight_inuse);
2008 
2009 		/* adjusted weight sum for children: s' = s_f + s_t * w'_pt / w_pt */
2010 		st = DIV64_U64_ROUND_UP(
2011 			iocg->child_active_sum * iocg->hweight_donating,
2012 			iocg->hweight_active);
2013 		sf = iocg->child_active_sum - st;
2014 		wpt = DIV64_U64_ROUND_UP(
2015 			(u64)iocg->active * iocg->hweight_donating,
2016 			iocg->hweight_active);
2017 		wptp = DIV64_U64_ROUND_UP(
2018 			(u64)inuse * iocg->hweight_after_donation,
2019 			iocg->hweight_inuse);
2020 
2021 		iocg->child_adjusted_sum = sf + DIV64_U64_ROUND_UP(st * wptp, wpt);
2022 	}
2023 
2024 	/*
2025 	 * All inner nodes now have ->hweight_inuse and ->child_adjusted_sum and
2026 	 * we can finally determine leaf adjustments.
2027 	 */
2028 	list_for_each_entry(iocg, surpluses, surplus_list) {
2029 		struct ioc_gq *parent = iocg->ancestors[iocg->level - 1];
2030 		u32 inuse;
2031 
2032 		/*
2033 		 * In-debt iocgs participated in the donation calculation with
2034 		 * the minimum target hweight_inuse. Configuring inuse
2035 		 * accordingly would work fine but debt handling expects
2036 		 * @iocg->inuse stay at the minimum and we don't wanna
2037 		 * interfere.
2038 		 */
2039 		if (iocg->abs_vdebt) {
2040 			WARN_ON_ONCE(iocg->inuse > 1);
2041 			continue;
2042 		}
2043 
2044 		/* w' = s' * b' / b'_p, note that b' == b'_t for donating leaves */
2045 		inuse = DIV64_U64_ROUND_UP(
2046 			parent->child_adjusted_sum * iocg->hweight_after_donation,
2047 			parent->hweight_inuse);
2048 
2049 		TRACE_IOCG_PATH(inuse_transfer, iocg, now,
2050 				iocg->inuse, inuse,
2051 				iocg->hweight_inuse,
2052 				iocg->hweight_after_donation);
2053 
2054 		__propagate_weights(iocg, iocg->active, inuse, true, now);
2055 	}
2056 
2057 	/* walk list should be dissolved after use */
2058 	list_for_each_entry_safe(iocg, tiocg, &inner_walk, walk_list)
2059 		list_del_init(&iocg->walk_list);
2060 }
2061 
2062 /*
2063  * A low weight iocg can amass a large amount of debt, for example, when
2064  * anonymous memory gets reclaimed aggressively. If the system has a lot of
2065  * memory paired with a slow IO device, the debt can span multiple seconds or
2066  * more. If there are no other subsequent IO issuers, the in-debt iocg may end
2067  * up blocked paying its debt while the IO device is idle.
2068  *
2069  * The following protects against such cases. If the device has been
2070  * sufficiently idle for a while, the debts are halved and delays are
2071  * recalculated.
2072  */
2073 static void ioc_forgive_debts(struct ioc *ioc, u64 usage_us_sum, int nr_debtors,
2074 			      struct ioc_now *now)
2075 {
2076 	struct ioc_gq *iocg;
2077 	u64 dur, usage_pct, nr_cycles, nr_cycles_shift;
2078 
2079 	/* if no debtor, reset the cycle */
2080 	if (!nr_debtors) {
2081 		ioc->dfgv_period_at = now->now;
2082 		ioc->dfgv_period_rem = 0;
2083 		ioc->dfgv_usage_us_sum = 0;
2084 		return;
2085 	}
2086 
2087 	/*
2088 	 * Debtors can pass through a lot of writes choking the device and we
2089 	 * don't want to be forgiving debts while the device is struggling from
2090 	 * write bursts. If we're missing latency targets, consider the device
2091 	 * fully utilized.
2092 	 */
2093 	if (ioc->busy_level > 0)
2094 		usage_us_sum = max_t(u64, usage_us_sum, ioc->period_us);
2095 
2096 	ioc->dfgv_usage_us_sum += usage_us_sum;
2097 	if (time_before64(now->now, ioc->dfgv_period_at + DFGV_PERIOD))
2098 		return;
2099 
2100 	/*
2101 	 * At least DFGV_PERIOD has passed since the last period. Calculate the
2102 	 * average usage and reset the period counters.
2103 	 */
2104 	dur = now->now - ioc->dfgv_period_at;
2105 	usage_pct = div64_u64(100 * ioc->dfgv_usage_us_sum, dur);
2106 
2107 	ioc->dfgv_period_at = now->now;
2108 	ioc->dfgv_usage_us_sum = 0;
2109 
2110 	/* if was too busy, reset everything */
2111 	if (usage_pct > DFGV_USAGE_PCT) {
2112 		ioc->dfgv_period_rem = 0;
2113 		return;
2114 	}
2115 
2116 	/*
2117 	 * Usage is lower than threshold. Let's forgive some debts. Debt
2118 	 * forgiveness runs off of the usual ioc timer but its period usually
2119 	 * doesn't match ioc's. Compensate the difference by performing the
2120 	 * reduction as many times as would fit in the duration since the last
2121 	 * run and carrying over the left-over duration in @ioc->dfgv_period_rem
2122 	 * - if ioc period is 75% of DFGV_PERIOD, one out of three consecutive
2123 	 * reductions is doubled.
2124 	 */
2125 	nr_cycles = dur + ioc->dfgv_period_rem;
2126 	ioc->dfgv_period_rem = do_div(nr_cycles, DFGV_PERIOD);
2127 
2128 	list_for_each_entry(iocg, &ioc->active_iocgs, active_list) {
2129 		u64 __maybe_unused old_debt, __maybe_unused old_delay;
2130 
2131 		if (!iocg->abs_vdebt && !iocg->delay)
2132 			continue;
2133 
2134 		spin_lock(&iocg->waitq.lock);
2135 
2136 		old_debt = iocg->abs_vdebt;
2137 		old_delay = iocg->delay;
2138 
2139 		nr_cycles_shift = min_t(u64, nr_cycles, BITS_PER_LONG - 1);
2140 		if (iocg->abs_vdebt)
2141 			iocg->abs_vdebt = iocg->abs_vdebt >> nr_cycles_shift ?: 1;
2142 
2143 		if (iocg->delay)
2144 			iocg->delay = iocg->delay >> nr_cycles_shift ?: 1;
2145 
2146 		iocg_kick_waitq(iocg, true, now);
2147 
2148 		TRACE_IOCG_PATH(iocg_forgive_debt, iocg, now, usage_pct,
2149 				old_debt, iocg->abs_vdebt,
2150 				old_delay, iocg->delay);
2151 
2152 		spin_unlock(&iocg->waitq.lock);
2153 	}
2154 }
2155 
2156 /*
2157  * Check the active iocgs' state to avoid oversleeping and deactive
2158  * idle iocgs.
2159  *
2160  * Since waiters determine the sleep durations based on the vrate
2161  * they saw at the time of sleep, if vrate has increased, some
2162  * waiters could be sleeping for too long. Wake up tardy waiters
2163  * which should have woken up in the last period and expire idle
2164  * iocgs.
2165  */
2166 static int ioc_check_iocgs(struct ioc *ioc, struct ioc_now *now)
2167 {
2168 	int nr_debtors = 0;
2169 	struct ioc_gq *iocg, *tiocg;
2170 
2171 	list_for_each_entry_safe(iocg, tiocg, &ioc->active_iocgs, active_list) {
2172 		if (!waitqueue_active(&iocg->waitq) && !iocg->abs_vdebt &&
2173 		    !iocg->delay && !iocg_is_idle(iocg))
2174 			continue;
2175 
2176 		spin_lock(&iocg->waitq.lock);
2177 
2178 		/* flush wait and indebt stat deltas */
2179 		if (iocg->wait_since) {
2180 			iocg->stat.wait_us += now->now - iocg->wait_since;
2181 			iocg->wait_since = now->now;
2182 		}
2183 		if (iocg->indebt_since) {
2184 			iocg->stat.indebt_us +=
2185 				now->now - iocg->indebt_since;
2186 			iocg->indebt_since = now->now;
2187 		}
2188 		if (iocg->indelay_since) {
2189 			iocg->stat.indelay_us +=
2190 				now->now - iocg->indelay_since;
2191 			iocg->indelay_since = now->now;
2192 		}
2193 
2194 		if (waitqueue_active(&iocg->waitq) || iocg->abs_vdebt ||
2195 		    iocg->delay) {
2196 			/* might be oversleeping vtime / hweight changes, kick */
2197 			iocg_kick_waitq(iocg, true, now);
2198 			if (iocg->abs_vdebt || iocg->delay)
2199 				nr_debtors++;
2200 		} else if (iocg_is_idle(iocg)) {
2201 			/* no waiter and idle, deactivate */
2202 			u64 vtime = atomic64_read(&iocg->vtime);
2203 			s64 excess;
2204 
2205 			/*
2206 			 * @iocg has been inactive for a full duration and will
2207 			 * have a high budget. Account anything above target as
2208 			 * error and throw away. On reactivation, it'll start
2209 			 * with the target budget.
2210 			 */
2211 			excess = now->vnow - vtime - ioc->margins.target;
2212 			if (excess > 0) {
2213 				u32 old_hwi;
2214 
2215 				current_hweight(iocg, NULL, &old_hwi);
2216 				ioc->vtime_err -= div64_u64(excess * old_hwi,
2217 							    WEIGHT_ONE);
2218 			}
2219 
2220 			TRACE_IOCG_PATH(iocg_idle, iocg, now,
2221 					atomic64_read(&iocg->active_period),
2222 					atomic64_read(&ioc->cur_period), vtime);
2223 			__propagate_weights(iocg, 0, 0, false, now);
2224 			list_del_init(&iocg->active_list);
2225 		}
2226 
2227 		spin_unlock(&iocg->waitq.lock);
2228 	}
2229 
2230 	commit_weights(ioc);
2231 	return nr_debtors;
2232 }
2233 
2234 static void ioc_timer_fn(struct timer_list *timer)
2235 {
2236 	struct ioc *ioc = container_of(timer, struct ioc, timer);
2237 	struct ioc_gq *iocg, *tiocg;
2238 	struct ioc_now now;
2239 	LIST_HEAD(surpluses);
2240 	int nr_debtors, nr_shortages = 0, nr_lagging = 0;
2241 	u64 usage_us_sum = 0;
2242 	u32 ppm_rthr;
2243 	u32 ppm_wthr;
2244 	u32 missed_ppm[2], rq_wait_pct, nr_done;
2245 	u64 period_vtime;
2246 	int prev_busy_level;
2247 
2248 	/* how were the latencies during the period? */
2249 	ioc_lat_stat(ioc, missed_ppm, &rq_wait_pct, &nr_done);
2250 
2251 	/* take care of active iocgs */
2252 	spin_lock_irq(&ioc->lock);
2253 
2254 	ppm_rthr = MILLION - ioc->params.qos[QOS_RPPM];
2255 	ppm_wthr = MILLION - ioc->params.qos[QOS_WPPM];
2256 	ioc_now(ioc, &now);
2257 
2258 	period_vtime = now.vnow - ioc->period_at_vtime;
2259 	if (WARN_ON_ONCE(!period_vtime)) {
2260 		spin_unlock_irq(&ioc->lock);
2261 		return;
2262 	}
2263 
2264 	nr_debtors = ioc_check_iocgs(ioc, &now);
2265 
2266 	/*
2267 	 * Wait and indebt stat are flushed above and the donation calculation
2268 	 * below needs updated usage stat. Let's bring stat up-to-date.
2269 	 */
2270 	iocg_flush_stat(&ioc->active_iocgs, &now);
2271 
2272 	/* calc usage and see whether some weights need to be moved around */
2273 	list_for_each_entry(iocg, &ioc->active_iocgs, active_list) {
2274 		u64 vdone, vtime, usage_us;
2275 		u32 hw_active, hw_inuse;
2276 
2277 		/*
2278 		 * Collect unused and wind vtime closer to vnow to prevent
2279 		 * iocgs from accumulating a large amount of budget.
2280 		 */
2281 		vdone = atomic64_read(&iocg->done_vtime);
2282 		vtime = atomic64_read(&iocg->vtime);
2283 		current_hweight(iocg, &hw_active, &hw_inuse);
2284 
2285 		/*
2286 		 * Latency QoS detection doesn't account for IOs which are
2287 		 * in-flight for longer than a period.  Detect them by
2288 		 * comparing vdone against period start.  If lagging behind
2289 		 * IOs from past periods, don't increase vrate.
2290 		 */
2291 		if ((ppm_rthr != MILLION || ppm_wthr != MILLION) &&
2292 		    !atomic_read(&iocg_to_blkg(iocg)->use_delay) &&
2293 		    time_after64(vtime, vdone) &&
2294 		    time_after64(vtime, now.vnow -
2295 				 MAX_LAGGING_PERIODS * period_vtime) &&
2296 		    time_before64(vdone, now.vnow - period_vtime))
2297 			nr_lagging++;
2298 
2299 		/*
2300 		 * Determine absolute usage factoring in in-flight IOs to avoid
2301 		 * high-latency completions appearing as idle.
2302 		 */
2303 		usage_us = iocg->usage_delta_us;
2304 		usage_us_sum += usage_us;
2305 
2306 		/* see whether there's surplus vtime */
2307 		WARN_ON_ONCE(!list_empty(&iocg->surplus_list));
2308 		if (hw_inuse < hw_active ||
2309 		    (!waitqueue_active(&iocg->waitq) &&
2310 		     time_before64(vtime, now.vnow - ioc->margins.low))) {
2311 			u32 hwa, old_hwi, hwm, new_hwi, usage;
2312 			u64 usage_dur;
2313 
2314 			if (vdone != vtime) {
2315 				u64 inflight_us = DIV64_U64_ROUND_UP(
2316 					cost_to_abs_cost(vtime - vdone, hw_inuse),
2317 					ioc->vtime_base_rate);
2318 
2319 				usage_us = max(usage_us, inflight_us);
2320 			}
2321 
2322 			/* convert to hweight based usage ratio */
2323 			if (time_after64(iocg->activated_at, ioc->period_at))
2324 				usage_dur = max_t(u64, now.now - iocg->activated_at, 1);
2325 			else
2326 				usage_dur = max_t(u64, now.now - ioc->period_at, 1);
2327 
2328 			usage = clamp(DIV64_U64_ROUND_UP(usage_us * WEIGHT_ONE, usage_dur),
2329 				      1, WEIGHT_ONE);
2330 
2331 			/*
2332 			 * Already donating or accumulated enough to start.
2333 			 * Determine the donation amount.
2334 			 */
2335 			current_hweight(iocg, &hwa, &old_hwi);
2336 			hwm = current_hweight_max(iocg);
2337 			new_hwi = hweight_after_donation(iocg, old_hwi, hwm,
2338 							 usage, &now);
2339 			/*
2340 			 * Donation calculation assumes hweight_after_donation
2341 			 * to be positive, a condition that a donor w/ hwa < 2
2342 			 * can't meet. Don't bother with donation if hwa is
2343 			 * below 2. It's not gonna make a meaningful difference
2344 			 * anyway.
2345 			 */
2346 			if (new_hwi < hwm && hwa >= 2) {
2347 				iocg->hweight_donating = hwa;
2348 				iocg->hweight_after_donation = new_hwi;
2349 				list_add(&iocg->surplus_list, &surpluses);
2350 			} else if (!iocg->abs_vdebt) {
2351 				/*
2352 				 * @iocg doesn't have enough to donate. Reset
2353 				 * its inuse to active.
2354 				 *
2355 				 * Don't reset debtors as their inuse's are
2356 				 * owned by debt handling. This shouldn't affect
2357 				 * donation calculuation in any meaningful way
2358 				 * as @iocg doesn't have a meaningful amount of
2359 				 * share anyway.
2360 				 */
2361 				TRACE_IOCG_PATH(inuse_shortage, iocg, &now,
2362 						iocg->inuse, iocg->active,
2363 						iocg->hweight_inuse, new_hwi);
2364 
2365 				__propagate_weights(iocg, iocg->active,
2366 						    iocg->active, true, &now);
2367 				nr_shortages++;
2368 			}
2369 		} else {
2370 			/* genuinely short on vtime */
2371 			nr_shortages++;
2372 		}
2373 	}
2374 
2375 	if (!list_empty(&surpluses) && nr_shortages)
2376 		transfer_surpluses(&surpluses, &now);
2377 
2378 	commit_weights(ioc);
2379 
2380 	/* surplus list should be dissolved after use */
2381 	list_for_each_entry_safe(iocg, tiocg, &surpluses, surplus_list)
2382 		list_del_init(&iocg->surplus_list);
2383 
2384 	/*
2385 	 * If q is getting clogged or we're missing too much, we're issuing
2386 	 * too much IO and should lower vtime rate.  If we're not missing
2387 	 * and experiencing shortages but not surpluses, we're too stingy
2388 	 * and should increase vtime rate.
2389 	 */
2390 	prev_busy_level = ioc->busy_level;
2391 	if (!nr_done && nr_lagging) {
2392 		/*
2393 		 * When there are lagging IOs but no completions, we don't
2394 		 * know if the IO latency will meet the QoS targets. The
2395 		 * disk might be saturated or not. We should not reset
2396 		 * busy_level to 0 (which would prevent vrate from scaling
2397 		 * up or down), but rather to keep it unchanged.
2398 		 */
2399 	} else if (rq_wait_pct > RQ_WAIT_BUSY_PCT ||
2400 		   missed_ppm[READ] > ppm_rthr ||
2401 		   missed_ppm[WRITE] > ppm_wthr) {
2402 		/* clearly missing QoS targets, slow down vrate */
2403 		ioc->busy_level = max(ioc->busy_level, 0);
2404 		ioc->busy_level++;
2405 	} else if (rq_wait_pct <= RQ_WAIT_BUSY_PCT * UNBUSY_THR_PCT / 100 &&
2406 		   missed_ppm[READ] <= ppm_rthr * UNBUSY_THR_PCT / 100 &&
2407 		   missed_ppm[WRITE] <= ppm_wthr * UNBUSY_THR_PCT / 100) {
2408 		/* QoS targets are being met with >25% margin */
2409 		if (nr_shortages) {
2410 			/*
2411 			 * We're throttling while the device has spare
2412 			 * capacity.  If vrate was being slowed down, stop.
2413 			 */
2414 			ioc->busy_level = min(ioc->busy_level, 0);
2415 
2416 			/*
2417 			 * If there are IOs spanning multiple periods, wait
2418 			 * them out before pushing the device harder.
2419 			 */
2420 			if (!nr_lagging)
2421 				ioc->busy_level--;
2422 		} else {
2423 			/*
2424 			 * Nobody is being throttled and the users aren't
2425 			 * issuing enough IOs to saturate the device.  We
2426 			 * simply don't know how close the device is to
2427 			 * saturation.  Coast.
2428 			 */
2429 			ioc->busy_level = 0;
2430 		}
2431 	} else {
2432 		/* inside the hysterisis margin, we're good */
2433 		ioc->busy_level = 0;
2434 	}
2435 
2436 	ioc->busy_level = clamp(ioc->busy_level, -1000, 1000);
2437 
2438 	ioc_adjust_base_vrate(ioc, rq_wait_pct, nr_lagging, nr_shortages,
2439 			      prev_busy_level, missed_ppm);
2440 
2441 	ioc_refresh_params(ioc, false);
2442 
2443 	ioc_forgive_debts(ioc, usage_us_sum, nr_debtors, &now);
2444 
2445 	/*
2446 	 * This period is done.  Move onto the next one.  If nothing's
2447 	 * going on with the device, stop the timer.
2448 	 */
2449 	atomic64_inc(&ioc->cur_period);
2450 
2451 	if (ioc->running != IOC_STOP) {
2452 		if (!list_empty(&ioc->active_iocgs)) {
2453 			ioc_start_period(ioc, &now);
2454 		} else {
2455 			ioc->busy_level = 0;
2456 			ioc->vtime_err = 0;
2457 			ioc->running = IOC_IDLE;
2458 		}
2459 
2460 		ioc_refresh_vrate(ioc, &now);
2461 	}
2462 
2463 	spin_unlock_irq(&ioc->lock);
2464 }
2465 
2466 static u64 adjust_inuse_and_calc_cost(struct ioc_gq *iocg, u64 vtime,
2467 				      u64 abs_cost, struct ioc_now *now)
2468 {
2469 	struct ioc *ioc = iocg->ioc;
2470 	struct ioc_margins *margins = &ioc->margins;
2471 	u32 __maybe_unused old_inuse = iocg->inuse, __maybe_unused old_hwi;
2472 	u32 hwi, adj_step;
2473 	s64 margin;
2474 	u64 cost, new_inuse;
2475 	unsigned long flags;
2476 
2477 	current_hweight(iocg, NULL, &hwi);
2478 	old_hwi = hwi;
2479 	cost = abs_cost_to_cost(abs_cost, hwi);
2480 	margin = now->vnow - vtime - cost;
2481 
2482 	/* debt handling owns inuse for debtors */
2483 	if (iocg->abs_vdebt)
2484 		return cost;
2485 
2486 	/*
2487 	 * We only increase inuse during period and do so if the margin has
2488 	 * deteriorated since the previous adjustment.
2489 	 */
2490 	if (margin >= iocg->saved_margin || margin >= margins->low ||
2491 	    iocg->inuse == iocg->active)
2492 		return cost;
2493 
2494 	spin_lock_irqsave(&ioc->lock, flags);
2495 
2496 	/* we own inuse only when @iocg is in the normal active state */
2497 	if (iocg->abs_vdebt || list_empty(&iocg->active_list)) {
2498 		spin_unlock_irqrestore(&ioc->lock, flags);
2499 		return cost;
2500 	}
2501 
2502 	/*
2503 	 * Bump up inuse till @abs_cost fits in the existing budget.
2504 	 * adj_step must be determined after acquiring ioc->lock - we might
2505 	 * have raced and lost to another thread for activation and could
2506 	 * be reading 0 iocg->active before ioc->lock which will lead to
2507 	 * infinite loop.
2508 	 */
2509 	new_inuse = iocg->inuse;
2510 	adj_step = DIV_ROUND_UP(iocg->active * INUSE_ADJ_STEP_PCT, 100);
2511 	do {
2512 		new_inuse = new_inuse + adj_step;
2513 		propagate_weights(iocg, iocg->active, new_inuse, true, now);
2514 		current_hweight(iocg, NULL, &hwi);
2515 		cost = abs_cost_to_cost(abs_cost, hwi);
2516 	} while (time_after64(vtime + cost, now->vnow) &&
2517 		 iocg->inuse != iocg->active);
2518 
2519 	spin_unlock_irqrestore(&ioc->lock, flags);
2520 
2521 	TRACE_IOCG_PATH(inuse_adjust, iocg, now,
2522 			old_inuse, iocg->inuse, old_hwi, hwi);
2523 
2524 	return cost;
2525 }
2526 
2527 static void calc_vtime_cost_builtin(struct bio *bio, struct ioc_gq *iocg,
2528 				    bool is_merge, u64 *costp)
2529 {
2530 	struct ioc *ioc = iocg->ioc;
2531 	u64 coef_seqio, coef_randio, coef_page;
2532 	u64 pages = max_t(u64, bio_sectors(bio) >> IOC_SECT_TO_PAGE_SHIFT, 1);
2533 	u64 seek_pages = 0;
2534 	u64 cost = 0;
2535 
2536 	/* Can't calculate cost for empty bio */
2537 	if (!bio->bi_iter.bi_size)
2538 		goto out;
2539 
2540 	switch (bio_op(bio)) {
2541 	case REQ_OP_READ:
2542 		coef_seqio	= ioc->params.lcoefs[LCOEF_RSEQIO];
2543 		coef_randio	= ioc->params.lcoefs[LCOEF_RRANDIO];
2544 		coef_page	= ioc->params.lcoefs[LCOEF_RPAGE];
2545 		break;
2546 	case REQ_OP_WRITE:
2547 		coef_seqio	= ioc->params.lcoefs[LCOEF_WSEQIO];
2548 		coef_randio	= ioc->params.lcoefs[LCOEF_WRANDIO];
2549 		coef_page	= ioc->params.lcoefs[LCOEF_WPAGE];
2550 		break;
2551 	default:
2552 		goto out;
2553 	}
2554 
2555 	if (iocg->cursor) {
2556 		seek_pages = abs(bio->bi_iter.bi_sector - iocg->cursor);
2557 		seek_pages >>= IOC_SECT_TO_PAGE_SHIFT;
2558 	}
2559 
2560 	if (!is_merge) {
2561 		if (seek_pages > LCOEF_RANDIO_PAGES) {
2562 			cost += coef_randio;
2563 		} else {
2564 			cost += coef_seqio;
2565 		}
2566 	}
2567 	cost += pages * coef_page;
2568 out:
2569 	*costp = cost;
2570 }
2571 
2572 static u64 calc_vtime_cost(struct bio *bio, struct ioc_gq *iocg, bool is_merge)
2573 {
2574 	u64 cost;
2575 
2576 	calc_vtime_cost_builtin(bio, iocg, is_merge, &cost);
2577 	return cost;
2578 }
2579 
2580 static void calc_size_vtime_cost_builtin(struct request *rq, struct ioc *ioc,
2581 					 u64 *costp)
2582 {
2583 	unsigned int pages = blk_rq_stats_sectors(rq) >> IOC_SECT_TO_PAGE_SHIFT;
2584 
2585 	switch (req_op(rq)) {
2586 	case REQ_OP_READ:
2587 		*costp = pages * ioc->params.lcoefs[LCOEF_RPAGE];
2588 		break;
2589 	case REQ_OP_WRITE:
2590 		*costp = pages * ioc->params.lcoefs[LCOEF_WPAGE];
2591 		break;
2592 	default:
2593 		*costp = 0;
2594 	}
2595 }
2596 
2597 static u64 calc_size_vtime_cost(struct request *rq, struct ioc *ioc)
2598 {
2599 	u64 cost;
2600 
2601 	calc_size_vtime_cost_builtin(rq, ioc, &cost);
2602 	return cost;
2603 }
2604 
2605 enum over_budget_action {
2606 	action_retry,
2607 	action_commit,
2608 	action_wait,
2609 	action_return,
2610 };
2611 
2612 static enum over_budget_action
2613 iocg_handle_over_budget(struct rq_qos *rqos, struct ioc_gq *iocg,
2614 			struct bio *bio, struct ioc_now *now,
2615 			struct iocg_wait *wait, bool use_debt, bool ioc_locked,
2616 			u64 abs_cost, u64 cost)
2617 {
2618 	lockdep_assert_held(&iocg->waitq.lock);
2619 
2620 	/*
2621 	 * @iocg must stay activated for debt and waitq handling. Deactivation
2622 	 * is synchronized against both ioc->lock and waitq.lock and we won't
2623 	 * get deactivated as long as we're waiting or have debt, so we're good
2624 	 * if we're activated here. In the unlikely cases that we aren't, just
2625 	 * issue the IO.
2626 	 */
2627 	if (unlikely(list_empty(&iocg->active_list)))
2628 		return action_commit;
2629 
2630 	/*
2631 	 * We're over budget. If @bio has to be issued regardless, remember
2632 	 * the abs_cost instead of advancing vtime. iocg_kick_waitq() will pay
2633 	 * off the debt before waking more IOs.
2634 	 *
2635 	 * This way, the debt is continuously paid off each period with the
2636 	 * actual budget available to the cgroup. If we just wound vtime, we
2637 	 * would incorrectly use the current hw_inuse for the entire amount
2638 	 * which, for example, can lead to the cgroup staying blocked for a
2639 	 * long time even with substantially raised hw_inuse.
2640 	 *
2641 	 * An iocg with vdebt should stay online so that the timer can keep
2642 	 * deducting its vdebt and [de]activate use_delay mechanism
2643 	 * accordingly. We don't want to race against the timer trying to
2644 	 * clear them and leave @iocg inactive w/ dangling use_delay heavily
2645 	 * penalizing the cgroup and its descendants.
2646 	 */
2647 	if (use_debt) {
2648 		iocg_incur_debt(iocg, abs_cost, now);
2649 		if (iocg_kick_delay(iocg, now))
2650 			blkcg_schedule_throttle(rqos->disk,
2651 						(bio->bi_opf & REQ_SWAP) ==
2652 							REQ_SWAP);
2653 		return action_return;
2654 	}
2655 
2656 	/* guarantee that iocgs w/ waiters have maximum inuse */
2657 	if (!iocg->abs_vdebt && iocg->inuse != iocg->active) {
2658 		if (!ioc_locked)
2659 			return action_retry;
2660 		lockdep_assert_held(&iocg->ioc->lock);
2661 		propagate_weights(iocg, iocg->active, iocg->active, true, now);
2662 	}
2663 
2664 	/*
2665 	 * Append self to the waitq and schedule the wakeup timer if we're
2666 	 * the first waiter.  The timer duration is calculated based on the
2667 	 * current vrate.  vtime and hweight changes can make it too short
2668 	 * or too long.  Each wait entry records the absolute cost it's
2669 	 * waiting for to allow re-evaluation using a custom wait entry.
2670 	 *
2671 	 * If too short, the timer simply reschedules itself.  If too long,
2672 	 * the period timer will notice and trigger wakeups.
2673 	 *
2674 	 * All waiters are on iocg->waitq and the wait states are
2675 	 * synchronized using waitq.lock.
2676 	 */
2677 	init_wait_func(&wait->wait, iocg_wake_fn);
2678 	wait->bio = bio;
2679 	wait->abs_cost = abs_cost;
2680 	wait->committed = false; /* will be set true by waker */
2681 
2682 	__add_wait_queue_entry_tail(&iocg->waitq, &wait->wait);
2683 	iocg_kick_waitq(iocg, ioc_locked, now);
2684 	return action_wait;
2685 }
2686 
2687 static void ioc_rqos_throttle(struct rq_qos *rqos, struct bio *bio)
2688 {
2689 	struct blkcg_gq *blkg = bio->bi_blkg;
2690 	struct ioc *ioc = rqos_to_ioc(rqos);
2691 	struct ioc_gq *iocg = blkg_to_iocg(blkg);
2692 	struct ioc_now now;
2693 	struct iocg_wait wait;
2694 	u64 abs_cost, cost, vtime;
2695 	bool use_debt, ioc_locked;
2696 	enum over_budget_action action;
2697 	unsigned long flags;
2698 
2699 	/* bypass IOs if disabled, still initializing, or for root cgroup */
2700 	if (!ioc->enabled || !iocg || !iocg->level)
2701 		return;
2702 
2703 	/* calculate the absolute vtime cost */
2704 	abs_cost = calc_vtime_cost(bio, iocg, false);
2705 	if (!abs_cost)
2706 		return;
2707 
2708 	if (!iocg_activate(iocg, &now))
2709 		return;
2710 
2711 	iocg->cursor = bio_end_sector(bio);
2712 	vtime = atomic64_read(&iocg->vtime);
2713 	cost = adjust_inuse_and_calc_cost(iocg, vtime, abs_cost, &now);
2714 
2715 	/*
2716 	 * If no one's waiting and within budget, issue right away.  The
2717 	 * tests are racy but the races aren't systemic - we only miss once
2718 	 * in a while which is fine.
2719 	 */
2720 	if (!waitqueue_active(&iocg->waitq) && !iocg->abs_vdebt &&
2721 	    time_before_eq64(vtime + cost, now.vnow)) {
2722 		iocg_commit_bio(iocg, bio, abs_cost, cost);
2723 		return;
2724 	}
2725 
2726 	/*
2727 	 * We're over budget. This can be handled in two ways. IOs which may
2728 	 * cause priority inversions are punted to @ioc->aux_iocg and charged as
2729 	 * debt. Otherwise, the issuer is blocked on @iocg->waitq. Debt handling
2730 	 * requires @ioc->lock, waitq handling @iocg->waitq.lock. Determine
2731 	 * whether debt handling is needed and acquire locks accordingly.
2732 	 */
2733 	use_debt = bio_issue_as_root_blkg(bio) || fatal_signal_pending(current);
2734 	ioc_locked = use_debt || READ_ONCE(iocg->abs_vdebt);
2735 retry_lock:
2736 	if (ioc_locked) {
2737 		spin_lock_irqsave(&iocg->ioc->lock, flags);
2738 		spin_lock(&iocg->waitq.lock);
2739 		action = iocg_handle_over_budget(rqos, iocg, bio, &now, &wait,
2740 						 use_debt, ioc_locked, abs_cost,
2741 						 cost);
2742 		spin_unlock(&iocg->waitq.lock);
2743 		spin_unlock_irqrestore(&iocg->ioc->lock, flags);
2744 	} else {
2745 		spin_lock_irqsave(&iocg->waitq.lock, flags);
2746 		action = iocg_handle_over_budget(rqos, iocg, bio, &now, &wait,
2747 						 use_debt, ioc_locked, abs_cost,
2748 						 cost);
2749 		spin_unlock_irqrestore(&iocg->waitq.lock, flags);
2750 	}
2751 	switch (action) {
2752 	case action_retry:
2753 		ioc_locked = true;
2754 		goto retry_lock;
2755 	case action_commit:
2756 		iocg_commit_bio(iocg, bio, abs_cost, cost);
2757 		return;
2758 	case action_return:
2759 		return;
2760 	case action_wait:
2761 		break;
2762 	}
2763 
2764 	while (true) {
2765 		set_current_state(TASK_UNINTERRUPTIBLE);
2766 		if (wait.committed)
2767 			break;
2768 		io_schedule();
2769 	}
2770 
2771 	/* waker already committed us, proceed */
2772 	finish_wait(&iocg->waitq, &wait.wait);
2773 }
2774 
2775 static void ioc_rqos_merge(struct rq_qos *rqos, struct request *rq,
2776 			   struct bio *bio)
2777 {
2778 	struct ioc_gq *iocg = blkg_to_iocg(bio->bi_blkg);
2779 	struct ioc *ioc = rqos_to_ioc(rqos);
2780 	sector_t bio_end = bio_end_sector(bio);
2781 	struct ioc_now now;
2782 	u64 vtime, abs_cost, cost;
2783 	unsigned long flags;
2784 
2785 	/* bypass if disabled, still initializing, or for root cgroup */
2786 	if (!ioc->enabled || !iocg || !iocg->level)
2787 		return;
2788 
2789 	abs_cost = calc_vtime_cost(bio, iocg, true);
2790 	if (!abs_cost)
2791 		return;
2792 
2793 	ioc_now(ioc, &now);
2794 
2795 	vtime = atomic64_read(&iocg->vtime);
2796 	cost = adjust_inuse_and_calc_cost(iocg, vtime, abs_cost, &now);
2797 
2798 	/* update cursor if backmerging into the request at the cursor */
2799 	if (blk_rq_pos(rq) < bio_end &&
2800 	    blk_rq_pos(rq) + blk_rq_sectors(rq) == iocg->cursor)
2801 		iocg->cursor = bio_end;
2802 
2803 	/*
2804 	 * Charge if there's enough vtime budget and the existing request has
2805 	 * cost assigned.
2806 	 */
2807 	if (rq->bio && rq->bio->bi_iocost_cost &&
2808 	    time_before_eq64(atomic64_read(&iocg->vtime) + cost, now.vnow)) {
2809 		iocg_commit_bio(iocg, bio, abs_cost, cost);
2810 		return;
2811 	}
2812 
2813 	/*
2814 	 * Otherwise, account it as debt if @iocg is online, which it should
2815 	 * be for the vast majority of cases. See debt handling in
2816 	 * ioc_rqos_throttle() for details.
2817 	 */
2818 	spin_lock_irqsave(&ioc->lock, flags);
2819 	spin_lock(&iocg->waitq.lock);
2820 
2821 	if (likely(!list_empty(&iocg->active_list))) {
2822 		iocg_incur_debt(iocg, abs_cost, &now);
2823 		if (iocg_kick_delay(iocg, &now))
2824 			blkcg_schedule_throttle(rqos->disk,
2825 					(bio->bi_opf & REQ_SWAP) == REQ_SWAP);
2826 	} else {
2827 		iocg_commit_bio(iocg, bio, abs_cost, cost);
2828 	}
2829 
2830 	spin_unlock(&iocg->waitq.lock);
2831 	spin_unlock_irqrestore(&ioc->lock, flags);
2832 }
2833 
2834 static void ioc_rqos_done_bio(struct rq_qos *rqos, struct bio *bio)
2835 {
2836 	struct ioc_gq *iocg = blkg_to_iocg(bio->bi_blkg);
2837 
2838 	if (iocg && bio->bi_iocost_cost)
2839 		atomic64_add(bio->bi_iocost_cost, &iocg->done_vtime);
2840 }
2841 
2842 static void ioc_rqos_done(struct rq_qos *rqos, struct request *rq)
2843 {
2844 	struct ioc *ioc = rqos_to_ioc(rqos);
2845 	struct ioc_pcpu_stat *ccs;
2846 	u64 on_q_ns, rq_wait_ns, size_nsec;
2847 	int pidx, rw;
2848 
2849 	if (!ioc->enabled || !rq->alloc_time_ns || !rq->start_time_ns)
2850 		return;
2851 
2852 	switch (req_op(rq)) {
2853 	case REQ_OP_READ:
2854 		pidx = QOS_RLAT;
2855 		rw = READ;
2856 		break;
2857 	case REQ_OP_WRITE:
2858 		pidx = QOS_WLAT;
2859 		rw = WRITE;
2860 		break;
2861 	default:
2862 		return;
2863 	}
2864 
2865 	on_q_ns = blk_time_get_ns() - rq->alloc_time_ns;
2866 	rq_wait_ns = rq->start_time_ns - rq->alloc_time_ns;
2867 	size_nsec = div64_u64(calc_size_vtime_cost(rq, ioc), VTIME_PER_NSEC);
2868 
2869 	ccs = get_cpu_ptr(ioc->pcpu_stat);
2870 
2871 	if (on_q_ns <= size_nsec ||
2872 	    on_q_ns - size_nsec <= ioc->params.qos[pidx] * NSEC_PER_USEC)
2873 		local_inc(&ccs->missed[rw].nr_met);
2874 	else
2875 		local_inc(&ccs->missed[rw].nr_missed);
2876 
2877 	local64_add(rq_wait_ns, &ccs->rq_wait_ns);
2878 
2879 	put_cpu_ptr(ccs);
2880 }
2881 
2882 static void ioc_rqos_queue_depth_changed(struct rq_qos *rqos)
2883 {
2884 	struct ioc *ioc = rqos_to_ioc(rqos);
2885 
2886 	spin_lock_irq(&ioc->lock);
2887 	ioc_refresh_params(ioc, false);
2888 	spin_unlock_irq(&ioc->lock);
2889 }
2890 
2891 static void ioc_rqos_exit(struct rq_qos *rqos)
2892 {
2893 	struct ioc *ioc = rqos_to_ioc(rqos);
2894 
2895 	blkcg_deactivate_policy(rqos->disk, &blkcg_policy_iocost);
2896 
2897 	spin_lock_irq(&ioc->lock);
2898 	ioc->running = IOC_STOP;
2899 	spin_unlock_irq(&ioc->lock);
2900 
2901 	timer_shutdown_sync(&ioc->timer);
2902 	free_percpu(ioc->pcpu_stat);
2903 	kfree(ioc);
2904 }
2905 
2906 static const struct rq_qos_ops ioc_rqos_ops = {
2907 	.throttle = ioc_rqos_throttle,
2908 	.merge = ioc_rqos_merge,
2909 	.done_bio = ioc_rqos_done_bio,
2910 	.done = ioc_rqos_done,
2911 	.queue_depth_changed = ioc_rqos_queue_depth_changed,
2912 	.exit = ioc_rqos_exit,
2913 };
2914 
2915 static int blk_iocost_init(struct gendisk *disk)
2916 {
2917 	struct ioc *ioc;
2918 	int i, cpu, ret;
2919 
2920 	ioc = kzalloc_obj(*ioc);
2921 	if (!ioc)
2922 		return -ENOMEM;
2923 
2924 	ioc->pcpu_stat = alloc_percpu(struct ioc_pcpu_stat);
2925 	if (!ioc->pcpu_stat) {
2926 		kfree(ioc);
2927 		return -ENOMEM;
2928 	}
2929 
2930 	for_each_possible_cpu(cpu) {
2931 		struct ioc_pcpu_stat *ccs = per_cpu_ptr(ioc->pcpu_stat, cpu);
2932 
2933 		for (i = 0; i < ARRAY_SIZE(ccs->missed); i++) {
2934 			local_set(&ccs->missed[i].nr_met, 0);
2935 			local_set(&ccs->missed[i].nr_missed, 0);
2936 		}
2937 		local64_set(&ccs->rq_wait_ns, 0);
2938 	}
2939 
2940 	spin_lock_init(&ioc->lock);
2941 	timer_setup(&ioc->timer, ioc_timer_fn, 0);
2942 	INIT_LIST_HEAD(&ioc->active_iocgs);
2943 
2944 	ioc->running = IOC_IDLE;
2945 	ioc->vtime_base_rate = VTIME_PER_USEC;
2946 	atomic64_set(&ioc->vtime_rate, VTIME_PER_USEC);
2947 	seqcount_spinlock_init(&ioc->period_seqcount, &ioc->lock);
2948 	ioc->period_at = ktime_to_us(blk_time_get());
2949 	atomic64_set(&ioc->cur_period, 0);
2950 	atomic_set(&ioc->hweight_gen, 0);
2951 
2952 	spin_lock_irq(&ioc->lock);
2953 	ioc->autop_idx = AUTOP_INVALID;
2954 	ioc_refresh_params_disk(ioc, true, disk);
2955 	spin_unlock_irq(&ioc->lock);
2956 
2957 	/*
2958 	 * rqos must be added before activation to allow ioc_pd_init() to
2959 	 * lookup the ioc from q. This means that the rqos methods may get
2960 	 * called before policy activation completion, can't assume that the
2961 	 * target bio has an iocg associated and need to test for NULL iocg.
2962 	 */
2963 	ret = rq_qos_add(&ioc->rqos, disk, RQ_QOS_COST, &ioc_rqos_ops);
2964 	if (ret)
2965 		goto err_free_ioc;
2966 
2967 	ret = blkcg_activate_policy(disk, &blkcg_policy_iocost);
2968 	if (ret)
2969 		goto err_del_qos;
2970 	return 0;
2971 
2972 err_del_qos:
2973 	rq_qos_del(&ioc->rqos);
2974 err_free_ioc:
2975 	free_percpu(ioc->pcpu_stat);
2976 	kfree(ioc);
2977 	return ret;
2978 }
2979 
2980 static struct blkcg_policy_data *ioc_cpd_alloc(gfp_t gfp)
2981 {
2982 	struct ioc_cgrp *iocc;
2983 
2984 	iocc = kzalloc_obj(struct ioc_cgrp, gfp);
2985 	if (!iocc)
2986 		return NULL;
2987 
2988 	iocc->dfl_weight = CGROUP_WEIGHT_DFL * WEIGHT_ONE;
2989 	return &iocc->cpd;
2990 }
2991 
2992 static void ioc_cpd_free(struct blkcg_policy_data *cpd)
2993 {
2994 	kfree(container_of(cpd, struct ioc_cgrp, cpd));
2995 }
2996 
2997 static struct blkg_policy_data *ioc_pd_alloc(struct gendisk *disk,
2998 		struct blkcg *blkcg, gfp_t gfp)
2999 {
3000 	int levels = blkcg->css.cgroup->level + 1;
3001 	struct ioc_gq *iocg;
3002 
3003 	iocg = kzalloc_node(struct_size(iocg, ancestors, levels), gfp,
3004 			    disk->node_id);
3005 	if (!iocg)
3006 		return NULL;
3007 
3008 	iocg->pcpu_stat = alloc_percpu_gfp(struct iocg_pcpu_stat, gfp);
3009 	if (!iocg->pcpu_stat) {
3010 		kfree(iocg);
3011 		return NULL;
3012 	}
3013 
3014 	return &iocg->pd;
3015 }
3016 
3017 static void ioc_pd_init(struct blkg_policy_data *pd)
3018 {
3019 	struct ioc_gq *iocg = pd_to_iocg(pd);
3020 	struct blkcg_gq *blkg = pd_to_blkg(&iocg->pd);
3021 	struct ioc *ioc = q_to_ioc(blkg->q);
3022 	struct ioc_now now;
3023 	struct blkcg_gq *tblkg;
3024 	unsigned long flags;
3025 
3026 	ioc_now(ioc, &now);
3027 
3028 	iocg->ioc = ioc;
3029 	atomic64_set(&iocg->vtime, now.vnow);
3030 	atomic64_set(&iocg->done_vtime, now.vnow);
3031 	atomic64_set(&iocg->active_period, atomic64_read(&ioc->cur_period));
3032 	INIT_LIST_HEAD(&iocg->active_list);
3033 	INIT_LIST_HEAD(&iocg->walk_list);
3034 	INIT_LIST_HEAD(&iocg->surplus_list);
3035 	iocg->hweight_active = WEIGHT_ONE;
3036 	iocg->hweight_inuse = WEIGHT_ONE;
3037 
3038 	init_waitqueue_head(&iocg->waitq);
3039 	hrtimer_setup(&iocg->waitq_timer, iocg_waitq_timer_fn, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
3040 
3041 	iocg->level = blkg->blkcg->css.cgroup->level;
3042 
3043 	for (tblkg = blkg; tblkg; tblkg = tblkg->parent) {
3044 		struct ioc_gq *tiocg = blkg_to_iocg(tblkg);
3045 		iocg->ancestors[tiocg->level] = tiocg;
3046 	}
3047 
3048 	spin_lock_irqsave(&ioc->lock, flags);
3049 	weight_updated(iocg, &now);
3050 	spin_unlock_irqrestore(&ioc->lock, flags);
3051 }
3052 
3053 static void ioc_pd_free(struct blkg_policy_data *pd)
3054 {
3055 	struct ioc_gq *iocg = pd_to_iocg(pd);
3056 	struct ioc *ioc = iocg->ioc;
3057 	unsigned long flags;
3058 
3059 	if (ioc) {
3060 		spin_lock_irqsave(&ioc->lock, flags);
3061 
3062 		if (!list_empty(&iocg->active_list)) {
3063 			struct ioc_now now;
3064 
3065 			ioc_now(ioc, &now);
3066 			propagate_weights(iocg, 0, 0, false, &now);
3067 			list_del_init(&iocg->active_list);
3068 		}
3069 
3070 		WARN_ON_ONCE(!list_empty(&iocg->walk_list));
3071 		WARN_ON_ONCE(!list_empty(&iocg->surplus_list));
3072 
3073 		spin_unlock_irqrestore(&ioc->lock, flags);
3074 
3075 		hrtimer_cancel(&iocg->waitq_timer);
3076 	}
3077 	free_percpu(iocg->pcpu_stat);
3078 	kfree(iocg);
3079 }
3080 
3081 static void ioc_pd_stat(struct blkg_policy_data *pd, struct seq_file *s)
3082 {
3083 	struct ioc_gq *iocg = pd_to_iocg(pd);
3084 	struct ioc *ioc = iocg->ioc;
3085 
3086 	if (!ioc->enabled)
3087 		return;
3088 
3089 	if (iocg->level == 0) {
3090 		unsigned vp10k = DIV64_U64_ROUND_CLOSEST(
3091 			ioc->vtime_base_rate * 10000,
3092 			VTIME_PER_USEC);
3093 		seq_printf(s, " cost.vrate=%u.%02u", vp10k / 100, vp10k % 100);
3094 	}
3095 
3096 	seq_printf(s, " cost.usage=%llu", iocg->last_stat.usage_us);
3097 
3098 	if (blkcg_debug_stats)
3099 		seq_printf(s, " cost.wait=%llu cost.indebt=%llu cost.indelay=%llu",
3100 			iocg->last_stat.wait_us,
3101 			iocg->last_stat.indebt_us,
3102 			iocg->last_stat.indelay_us);
3103 }
3104 
3105 static u64 ioc_weight_prfill(struct seq_file *sf, struct blkg_policy_data *pd,
3106 			     int off)
3107 {
3108 	const char *dname = blkg_dev_name(pd->blkg);
3109 	struct ioc_gq *iocg = pd_to_iocg(pd);
3110 
3111 	if (dname && iocg->cfg_weight)
3112 		seq_printf(sf, "%s %u\n", dname, iocg->cfg_weight / WEIGHT_ONE);
3113 	return 0;
3114 }
3115 
3116 
3117 static int ioc_weight_show(struct seq_file *sf, void *v)
3118 {
3119 	struct blkcg *blkcg = css_to_blkcg(seq_css(sf));
3120 	struct ioc_cgrp *iocc = blkcg_to_iocc(blkcg);
3121 
3122 	seq_printf(sf, "default %u\n", iocc->dfl_weight / WEIGHT_ONE);
3123 	blkcg_print_blkgs(sf, blkcg, ioc_weight_prfill,
3124 			  &blkcg_policy_iocost, seq_cft(sf)->private, false);
3125 	return 0;
3126 }
3127 
3128 static ssize_t ioc_weight_write(struct kernfs_open_file *of, char *buf,
3129 				size_t nbytes, loff_t off)
3130 {
3131 	struct blkcg *blkcg = css_to_blkcg(of_css(of));
3132 	struct ioc_cgrp *iocc = blkcg_to_iocc(blkcg);
3133 	struct blkg_conf_ctx ctx;
3134 	struct ioc_now now;
3135 	struct ioc_gq *iocg;
3136 	u32 v;
3137 	int ret;
3138 
3139 	if (!strchr(buf, ':')) {
3140 		struct blkcg_gq *blkg;
3141 
3142 		if (!sscanf(buf, "default %u", &v) && !sscanf(buf, "%u", &v))
3143 			return -EINVAL;
3144 
3145 		if (v < CGROUP_WEIGHT_MIN || v > CGROUP_WEIGHT_MAX)
3146 			return -EINVAL;
3147 
3148 		spin_lock_irq(&blkcg->lock);
3149 		iocc->dfl_weight = v * WEIGHT_ONE;
3150 		hlist_for_each_entry(blkg, &blkcg->blkg_list, blkcg_node) {
3151 			struct ioc_gq *iocg = blkg_to_iocg(blkg);
3152 
3153 			if (iocg) {
3154 				spin_lock(&iocg->ioc->lock);
3155 				ioc_now(iocg->ioc, &now);
3156 				weight_updated(iocg, &now);
3157 				spin_unlock(&iocg->ioc->lock);
3158 			}
3159 		}
3160 		spin_unlock_irq(&blkcg->lock);
3161 
3162 		return nbytes;
3163 	}
3164 
3165 	blkg_conf_init(&ctx, buf);
3166 
3167 	ret = blkg_conf_open_bdev(&ctx);
3168 	if (ret)
3169 		return ret;
3170 
3171 	ret = blkg_conf_prep(blkcg, &blkcg_policy_iocost, &ctx);
3172 	if (ret)
3173 		goto close_bdev;
3174 
3175 	iocg = blkg_to_iocg(ctx.blkg);
3176 
3177 	ret = -EINVAL;
3178 
3179 	if (!strncmp(ctx.body, "default", 7)) {
3180 		v = 0;
3181 	} else {
3182 		if (!sscanf(ctx.body, "%u", &v))
3183 			goto unprep;
3184 		if (v < CGROUP_WEIGHT_MIN || v > CGROUP_WEIGHT_MAX)
3185 			goto unprep;
3186 	}
3187 
3188 	spin_lock(&iocg->ioc->lock);
3189 	iocg->cfg_weight = v * WEIGHT_ONE;
3190 	ioc_now(iocg->ioc, &now);
3191 	weight_updated(iocg, &now);
3192 	spin_unlock(&iocg->ioc->lock);
3193 
3194 	ret = 0;
3195 
3196 unprep:
3197 	blkg_conf_unprep(&ctx);
3198 
3199 close_bdev:
3200 	blkg_conf_close_bdev(&ctx);
3201 
3202 	return ret ?: nbytes;
3203 }
3204 
3205 static u64 ioc_qos_prfill(struct seq_file *sf, struct blkg_policy_data *pd,
3206 			  int off)
3207 {
3208 	const char *dname = blkg_dev_name(pd->blkg);
3209 	struct ioc *ioc = pd_to_iocg(pd)->ioc;
3210 
3211 	if (!dname)
3212 		return 0;
3213 
3214 	spin_lock(&ioc->lock);
3215 	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",
3216 		   dname, ioc->enabled, ioc->user_qos_params ? "user" : "auto",
3217 		   ioc->params.qos[QOS_RPPM] / 10000,
3218 		   ioc->params.qos[QOS_RPPM] % 10000 / 100,
3219 		   ioc->params.qos[QOS_RLAT],
3220 		   ioc->params.qos[QOS_WPPM] / 10000,
3221 		   ioc->params.qos[QOS_WPPM] % 10000 / 100,
3222 		   ioc->params.qos[QOS_WLAT],
3223 		   ioc->params.qos[QOS_MIN] / 10000,
3224 		   ioc->params.qos[QOS_MIN] % 10000 / 100,
3225 		   ioc->params.qos[QOS_MAX] / 10000,
3226 		   ioc->params.qos[QOS_MAX] % 10000 / 100);
3227 	spin_unlock(&ioc->lock);
3228 	return 0;
3229 }
3230 
3231 static int ioc_qos_show(struct seq_file *sf, void *v)
3232 {
3233 	struct blkcg *blkcg = css_to_blkcg(seq_css(sf));
3234 
3235 	blkcg_print_blkgs(sf, blkcg, ioc_qos_prfill,
3236 			  &blkcg_policy_iocost, seq_cft(sf)->private, false);
3237 	return 0;
3238 }
3239 
3240 static const match_table_t qos_ctrl_tokens = {
3241 	{ QOS_ENABLE,		"enable=%u"	},
3242 	{ QOS_CTRL,		"ctrl=%s"	},
3243 	{ NR_QOS_CTRL_PARAMS,	NULL		},
3244 };
3245 
3246 static const match_table_t qos_tokens = {
3247 	{ QOS_RPPM,		"rpct=%s"	},
3248 	{ QOS_RLAT,		"rlat=%u"	},
3249 	{ QOS_WPPM,		"wpct=%s"	},
3250 	{ QOS_WLAT,		"wlat=%u"	},
3251 	{ QOS_MIN,		"min=%s"	},
3252 	{ QOS_MAX,		"max=%s"	},
3253 	{ NR_QOS_PARAMS,	NULL		},
3254 };
3255 
3256 static ssize_t ioc_qos_write(struct kernfs_open_file *of, char *input,
3257 			     size_t nbytes, loff_t off)
3258 {
3259 	struct blkg_conf_ctx ctx;
3260 	struct request_queue *q;
3261 	struct gendisk *disk;
3262 	struct ioc *ioc;
3263 	u32 qos[NR_QOS_PARAMS];
3264 	bool enable, user;
3265 	char *body, *p;
3266 	unsigned int memflags;
3267 	int ret;
3268 
3269 	blkg_conf_init(&ctx, input);
3270 
3271 	ret = blkg_conf_open_bdev(&ctx);
3272 	if (ret)
3273 		return ret;
3274 	/*
3275 	 * At this point, we haven’t started protecting anything related to QoS,
3276 	 * so we release q->rq_qos_mutex here, which was first acquired in blkg_
3277 	 * conf_open_bdev. Later, we re-acquire q->rq_qos_mutex after freezing
3278 	 * the queue to maintain the correct locking order.
3279 	 */
3280 	mutex_unlock(&ctx.bdev->bd_queue->rq_qos_mutex);
3281 
3282 	memflags = blk_mq_freeze_queue(ctx.bdev->bd_queue);
3283 	mutex_lock(&ctx.bdev->bd_queue->rq_qos_mutex);
3284 
3285 	body = ctx.body;
3286 	disk = ctx.bdev->bd_disk;
3287 	if (!queue_is_mq(disk->queue)) {
3288 		ret = -EOPNOTSUPP;
3289 		goto close_bdev;
3290 	}
3291 
3292 	ioc = q_to_ioc(disk->queue);
3293 	if (!ioc) {
3294 		ret = blk_iocost_init(disk);
3295 		if (ret)
3296 			goto close_bdev;
3297 		ioc = q_to_ioc(disk->queue);
3298 	}
3299 
3300 	blk_mq_quiesce_queue(disk->queue);
3301 
3302 	spin_lock_irq(&ioc->lock);
3303 	memcpy(qos, ioc->params.qos, sizeof(qos));
3304 	enable = ioc->enabled;
3305 	user = ioc->user_qos_params;
3306 
3307 	while ((p = strsep(&body, " \t\n"))) {
3308 		substring_t args[MAX_OPT_ARGS];
3309 		char buf[32];
3310 		int tok;
3311 		s64 v;
3312 
3313 		if (!*p)
3314 			continue;
3315 
3316 		switch (match_token(p, qos_ctrl_tokens, args)) {
3317 		case QOS_ENABLE:
3318 			if (match_u64(&args[0], &v))
3319 				goto einval;
3320 			enable = v;
3321 			continue;
3322 		case QOS_CTRL:
3323 			match_strlcpy(buf, &args[0], sizeof(buf));
3324 			if (!strcmp(buf, "auto"))
3325 				user = false;
3326 			else if (!strcmp(buf, "user"))
3327 				user = true;
3328 			else
3329 				goto einval;
3330 			continue;
3331 		}
3332 
3333 		tok = match_token(p, qos_tokens, args);
3334 		switch (tok) {
3335 		case QOS_RPPM:
3336 		case QOS_WPPM:
3337 			if (match_strlcpy(buf, &args[0], sizeof(buf)) >=
3338 			    sizeof(buf))
3339 				goto einval;
3340 			if (cgroup_parse_float(buf, 2, &v))
3341 				goto einval;
3342 			if (v < 0 || v > 10000)
3343 				goto einval;
3344 			qos[tok] = v * 100;
3345 			break;
3346 		case QOS_RLAT:
3347 		case QOS_WLAT:
3348 			if (match_u64(&args[0], &v))
3349 				goto einval;
3350 			qos[tok] = v;
3351 			break;
3352 		case QOS_MIN:
3353 		case QOS_MAX:
3354 			if (match_strlcpy(buf, &args[0], sizeof(buf)) >=
3355 			    sizeof(buf))
3356 				goto einval;
3357 			if (cgroup_parse_float(buf, 2, &v))
3358 				goto einval;
3359 			if (v < 0)
3360 				goto einval;
3361 			qos[tok] = clamp_t(s64, v * 100,
3362 					   VRATE_MIN_PPM, VRATE_MAX_PPM);
3363 			break;
3364 		default:
3365 			goto einval;
3366 		}
3367 		user = true;
3368 	}
3369 
3370 	if (qos[QOS_MIN] > qos[QOS_MAX])
3371 		goto einval;
3372 
3373 	if (enable && !ioc->enabled) {
3374 		blk_stat_enable_accounting(disk->queue);
3375 		blk_queue_flag_set(QUEUE_FLAG_RQ_ALLOC_TIME, disk->queue);
3376 		ioc->enabled = true;
3377 	} else if (!enable && ioc->enabled) {
3378 		blk_stat_disable_accounting(disk->queue);
3379 		blk_queue_flag_clear(QUEUE_FLAG_RQ_ALLOC_TIME, disk->queue);
3380 		ioc->enabled = false;
3381 	}
3382 
3383 	if (user) {
3384 		memcpy(ioc->params.qos, qos, sizeof(qos));
3385 		ioc->user_qos_params = true;
3386 	} else {
3387 		ioc->user_qos_params = false;
3388 	}
3389 
3390 	ioc_refresh_params(ioc, true);
3391 	spin_unlock_irq(&ioc->lock);
3392 
3393 	if (enable)
3394 		wbt_disable_default(disk);
3395 	else
3396 		wbt_enable_default(disk);
3397 
3398 	blk_mq_unquiesce_queue(disk->queue);
3399 
3400 close_bdev:
3401 	q = ctx.bdev->bd_queue;
3402 	blkg_conf_close_bdev(&ctx);
3403 	blk_mq_unfreeze_queue(q, memflags);
3404 	return ret ?: nbytes;
3405 
3406 einval:
3407 	spin_unlock_irq(&ioc->lock);
3408 	blk_mq_unquiesce_queue(disk->queue);
3409 	ret = -EINVAL;
3410 	goto close_bdev;
3411 }
3412 
3413 static u64 ioc_cost_model_prfill(struct seq_file *sf,
3414 				 struct blkg_policy_data *pd, int off)
3415 {
3416 	const char *dname = blkg_dev_name(pd->blkg);
3417 	struct ioc *ioc = pd_to_iocg(pd)->ioc;
3418 	u64 *u = ioc->params.i_lcoefs;
3419 
3420 	if (!dname)
3421 		return 0;
3422 
3423 	spin_lock(&ioc->lock);
3424 	seq_printf(sf, "%s ctrl=%s model=linear "
3425 		   "rbps=%llu rseqiops=%llu rrandiops=%llu "
3426 		   "wbps=%llu wseqiops=%llu wrandiops=%llu\n",
3427 		   dname, ioc->user_cost_model ? "user" : "auto",
3428 		   u[I_LCOEF_RBPS], u[I_LCOEF_RSEQIOPS], u[I_LCOEF_RRANDIOPS],
3429 		   u[I_LCOEF_WBPS], u[I_LCOEF_WSEQIOPS], u[I_LCOEF_WRANDIOPS]);
3430 	spin_unlock(&ioc->lock);
3431 	return 0;
3432 }
3433 
3434 static int ioc_cost_model_show(struct seq_file *sf, void *v)
3435 {
3436 	struct blkcg *blkcg = css_to_blkcg(seq_css(sf));
3437 
3438 	blkcg_print_blkgs(sf, blkcg, ioc_cost_model_prfill,
3439 			  &blkcg_policy_iocost, seq_cft(sf)->private, false);
3440 	return 0;
3441 }
3442 
3443 static const match_table_t cost_ctrl_tokens = {
3444 	{ COST_CTRL,		"ctrl=%s"	},
3445 	{ COST_MODEL,		"model=%s"	},
3446 	{ NR_COST_CTRL_PARAMS,	NULL		},
3447 };
3448 
3449 static const match_table_t i_lcoef_tokens = {
3450 	{ I_LCOEF_RBPS,		"rbps=%u"	},
3451 	{ I_LCOEF_RSEQIOPS,	"rseqiops=%u"	},
3452 	{ I_LCOEF_RRANDIOPS,	"rrandiops=%u"	},
3453 	{ I_LCOEF_WBPS,		"wbps=%u"	},
3454 	{ I_LCOEF_WSEQIOPS,	"wseqiops=%u"	},
3455 	{ I_LCOEF_WRANDIOPS,	"wrandiops=%u"	},
3456 	{ NR_I_LCOEFS,		NULL		},
3457 };
3458 
3459 static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
3460 				    size_t nbytes, loff_t off)
3461 {
3462 	struct blkg_conf_ctx ctx;
3463 	struct request_queue *q;
3464 	unsigned int memflags;
3465 	struct ioc *ioc;
3466 	u64 u[NR_I_LCOEFS];
3467 	bool user;
3468 	char *body, *p;
3469 	int ret;
3470 
3471 	blkg_conf_init(&ctx, input);
3472 
3473 	ret = blkg_conf_open_bdev(&ctx);
3474 	if (ret)
3475 		return ret;
3476 
3477 	body = ctx.body;
3478 	q = bdev_get_queue(ctx.bdev);
3479 	if (!queue_is_mq(q)) {
3480 		ret = -EOPNOTSUPP;
3481 		goto close_bdev;
3482 	}
3483 
3484 	ioc = q_to_ioc(q);
3485 	if (!ioc) {
3486 		ret = blk_iocost_init(ctx.bdev->bd_disk);
3487 		if (ret)
3488 			goto close_bdev;
3489 		ioc = q_to_ioc(q);
3490 	}
3491 
3492 	memflags = blk_mq_freeze_queue(q);
3493 	blk_mq_quiesce_queue(q);
3494 
3495 	spin_lock_irq(&ioc->lock);
3496 	memcpy(u, ioc->params.i_lcoefs, sizeof(u));
3497 	user = ioc->user_cost_model;
3498 
3499 	ret = -EINVAL;
3500 
3501 	while ((p = strsep(&body, " \t\n"))) {
3502 		substring_t args[MAX_OPT_ARGS];
3503 		char buf[32];
3504 		int tok;
3505 		u64 v;
3506 
3507 		if (!*p)
3508 			continue;
3509 
3510 		switch (match_token(p, cost_ctrl_tokens, args)) {
3511 		case COST_CTRL:
3512 			match_strlcpy(buf, &args[0], sizeof(buf));
3513 			if (!strcmp(buf, "auto"))
3514 				user = false;
3515 			else if (!strcmp(buf, "user"))
3516 				user = true;
3517 			else
3518 				goto unlock;
3519 			continue;
3520 		case COST_MODEL:
3521 			match_strlcpy(buf, &args[0], sizeof(buf));
3522 			if (strcmp(buf, "linear"))
3523 				goto unlock;
3524 			continue;
3525 		}
3526 
3527 		tok = match_token(p, i_lcoef_tokens, args);
3528 		if (tok == NR_I_LCOEFS)
3529 			goto unlock;
3530 		if (match_u64(&args[0], &v))
3531 			goto unlock;
3532 		u[tok] = v;
3533 		user = true;
3534 	}
3535 
3536 	if (user) {
3537 		memcpy(ioc->params.i_lcoefs, u, sizeof(u));
3538 		ioc->user_cost_model = true;
3539 	} else {
3540 		ioc->user_cost_model = false;
3541 	}
3542 	ioc_refresh_params(ioc, true);
3543 
3544 	ret = 0;
3545 
3546 unlock:
3547 	spin_unlock_irq(&ioc->lock);
3548 
3549 	blk_mq_unquiesce_queue(q);
3550 	blk_mq_unfreeze_queue(q, memflags);
3551 
3552 close_bdev:
3553 	blkg_conf_close_bdev(&ctx);
3554 	return ret ?: nbytes;
3555 }
3556 
3557 static struct cftype ioc_files[] = {
3558 	{
3559 		.name = "weight",
3560 		.flags = CFTYPE_NOT_ON_ROOT,
3561 		.seq_show = ioc_weight_show,
3562 		.write = ioc_weight_write,
3563 	},
3564 	{
3565 		.name = "cost.qos",
3566 		.flags = CFTYPE_ONLY_ON_ROOT,
3567 		.seq_show = ioc_qos_show,
3568 		.write = ioc_qos_write,
3569 	},
3570 	{
3571 		.name = "cost.model",
3572 		.flags = CFTYPE_ONLY_ON_ROOT,
3573 		.seq_show = ioc_cost_model_show,
3574 		.write = ioc_cost_model_write,
3575 	},
3576 	{}
3577 };
3578 
3579 static struct blkcg_policy blkcg_policy_iocost = {
3580 	.dfl_cftypes	= ioc_files,
3581 	.cpd_alloc_fn	= ioc_cpd_alloc,
3582 	.cpd_free_fn	= ioc_cpd_free,
3583 	.pd_alloc_fn	= ioc_pd_alloc,
3584 	.pd_init_fn	= ioc_pd_init,
3585 	.pd_free_fn	= ioc_pd_free,
3586 	.pd_stat_fn	= ioc_pd_stat,
3587 };
3588 
3589 static int __init ioc_init(void)
3590 {
3591 	return blkcg_policy_register(&blkcg_policy_iocost);
3592 }
3593 
3594 static void __exit ioc_exit(void)
3595 {
3596 	blkcg_policy_unregister(&blkcg_policy_iocost);
3597 }
3598 
3599 module_init(ioc_init);
3600 module_exit(ioc_exit);
3601