Blame view

block/blk-iocost.c 96.1 KB
7caa47151   Tejun Heo   blkcg: implement ...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
  /* SPDX-License-Identifier: GPL-2.0
   *
   * IO cost model based controller.
   *
   * Copyright (C) 2019 Tejun Heo <tj@kernel.org>
   * Copyright (C) 2019 Andy Newell <newella@fb.com>
   * Copyright (C) 2019 Facebook
   *
   * One challenge of controlling IO resources is the lack of trivially
   * observable cost metric.  This is distinguished from CPU and memory where
   * wallclock time and the number of bytes can serve as accurate enough
   * approximations.
   *
   * Bandwidth and iops are the most commonly used metrics for IO devices but
   * depending on the type and specifics of the device, different IO patterns
   * easily lead to multiple orders of magnitude variations rendering them
   * useless for the purpose of IO capacity distribution.  While on-device
   * time, with a lot of clutches, could serve as a useful approximation for
   * non-queued rotational devices, this is no longer viable with modern
   * devices, even the rotational ones.
   *
   * While there is no cost metric we can trivially observe, it isn't a
   * complete mystery.  For example, on a rotational device, seek cost
   * dominates while a contiguous transfer contributes a smaller amount
   * proportional to the size.  If we can characterize at least the relative
   * costs of these different types of IOs, it should be possible to
   * implement a reasonable work-conserving proportional IO resource
   * distribution.
   *
   * 1. IO Cost Model
   *
   * IO cost model estimates the cost of an IO given its basic parameters and
   * history (e.g. the end sector of the last IO).  The cost is measured in
   * device time.  If a given IO is estimated to cost 10ms, the device should
   * be able to process ~100 of those IOs in a second.
   *
   * Currently, there's only one builtin cost model - linear.  Each IO is
   * classified as sequential or random and given a base cost accordingly.
   * On top of that, a size cost proportional to the length of the IO is
   * added.  While simple, this model captures the operational
   * characteristics of a wide varienty of devices well enough.  Default
5ba1add21   Baolin Wang   blk-iocost: Fix s...
42
   * parameters for several different classes of devices are provided and the
7caa47151   Tejun Heo   blkcg: implement ...
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
   * parameters can be configured from userspace via
   * /sys/fs/cgroup/io.cost.model.
   *
   * If needed, tools/cgroup/iocost_coef_gen.py can be used to generate
   * device-specific coefficients.
   *
   * 2. Control Strategy
   *
   * The device virtual time (vtime) is used as the primary control metric.
   * The control strategy is composed of the following three parts.
   *
   * 2-1. Vtime Distribution
   *
   * When a cgroup becomes active in terms of IOs, its hierarchical share is
   * calculated.  Please consider the following hierarchy where the numbers
   * inside parentheses denote the configured weights.
   *
   *           root
   *         /       \
   *      A (w:100)  B (w:300)
   *      /       \
   *  A0 (w:100)  A1 (w:100)
   *
   * If B is idle and only A0 and A1 are actively issuing IOs, as the two are
   * of equal weight, each gets 50% share.  If then B starts issuing IOs, B
   * gets 300/(100+300) or 75% share, and A0 and A1 equally splits the rest,
   * 12.5% each.  The distribution mechanism only cares about these flattened
   * shares.  They're called hweights (hierarchical weights) and always add
fe20cdb51   Tejun Heo   blk-iocost: s/HWE...
71
   * upto 1 (WEIGHT_ONE).
7caa47151   Tejun Heo   blkcg: implement ...
72
73
74
75
76
77
78
79
   *
   * A given cgroup's vtime runs slower in inverse proportion to its hweight.
   * For example, with 12.5% weight, A0's time runs 8 times slower (100/12.5)
   * against the device vtime - an IO which takes 10ms on the underlying
   * device is considered to take 80ms on A0.
   *
   * This constitutes the basis of IO capacity distribution.  Each cgroup's
   * vtime is running at a rate determined by its hweight.  A cgroup tracks
5ba1add21   Baolin Wang   blk-iocost: Fix s...
80
   * the vtime consumed by past IOs and can issue a new IO if doing so
7caa47151   Tejun Heo   blkcg: implement ...
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
   * wouldn't outrun the current device vtime.  Otherwise, the IO is
   * suspended until the vtime has progressed enough to cover it.
   *
   * 2-2. Vrate Adjustment
   *
   * It's unrealistic to expect the cost model to be perfect.  There are too
   * many devices and even on the same device the overall performance
   * fluctuates depending on numerous factors such as IO mixture and device
   * internal garbage collection.  The controller needs to adapt dynamically.
   *
   * This is achieved by adjusting the overall IO rate according to how busy
   * the device is.  If the device becomes overloaded, we're sending down too
   * many IOs and should generally slow down.  If there are waiting issuers
   * but the device isn't saturated, we're issuing too few and should
   * generally speed up.
   *
   * To slow down, we lower the vrate - the rate at which the device vtime
   * passes compared to the wall clock.  For example, if the vtime is running
   * at the vrate of 75%, all cgroups added up would only be able to issue
   * 750ms worth of IOs per second, and vice-versa for speeding up.
   *
   * Device business is determined using two criteria - rq wait and
   * completion latencies.
   *
   * When a device gets saturated, the on-device and then the request queues
   * fill up and a bio which is ready to be issued has to wait for a request
   * to become available.  When this delay becomes noticeable, it's a clear
   * indication that the device is saturated and we lower the vrate.  This
   * saturation signal is fairly conservative as it only triggers when both
   * hardware and software queues are filled up, and is used as the default
   * busy signal.
   *
   * As devices can have deep queues and be unfair in how the queued commands
   * are executed, soley depending on rq wait may not result in satisfactory
   * control quality.  For a better control quality, completion latency QoS
   * parameters can be configured so that the device is considered saturated
   * if N'th percentile completion latency rises above the set point.
   *
   * The completion latency requirements are a function of both the
   * underlying device characteristics and the desired IO latency quality of
   * service.  There is an inherent trade-off - the tighter the latency QoS,
   * the higher the bandwidth lossage.  Latency QoS is disabled by default
   * and can be set through /sys/fs/cgroup/io.cost.qos.
   *
   * 2-3. Work Conservation
   *
   * Imagine two cgroups A and B with equal weights.  A is issuing a small IO
   * periodically while B is sending out enough parallel IOs to saturate the
   * device on its own.  Let's say A's usage amounts to 100ms worth of IO
   * cost per second, i.e., 10% of the device capacity.  The naive
   * distribution of half and half would lead to 60% utilization of the
   * device, a significant reduction in the total amount of work done
   * compared to free-for-all competition.  This is too high a cost to pay
   * for IO control.
   *
   * To conserve the total amount of work done, we keep track of how much
   * each active cgroup is actually using and yield part of its weight if
   * there are other cgroups which can make use of it.  In the above case,
   * A's weight will be lowered so that it hovers above the actual usage and
   * B would be able to use the rest.
   *
   * As we don't want to penalize a cgroup for donating its weight, the
   * surplus weight adjustment factors in a margin and has an immediate
   * snapback mechanism in case the cgroup needs more IO vtime for itself.
   *
   * Note that adjusting down surplus weights has the same effects as
   * accelerating vtime for other cgroups and work conservation can also be
   * implemented by adjusting vrate dynamically.  However, squaring who can
   * donate and should take back how much requires hweight propagations
   * anyway making it easier to implement and understand as a separate
   * mechanism.
6954ff185   Tejun Heo   blkcg: add tools/...
152
153
154
155
156
157
   *
   * 3. Monitoring
   *
   * Instead of debugfs or other clumsy monitoring mechanisms, this
   * controller uses a drgn based monitoring script -
   * tools/cgroup/iocost_monitor.py.  For details on drgn, please see
5ba1add21   Baolin Wang   blk-iocost: Fix s...
158
   * https://github.com/osandov/drgn.  The output looks like the following.
6954ff185   Tejun Heo   blkcg: add tools/...
159
160
   *
   *  sdb RUN   per=300ms cur_per=234.218:v203.695 busy= +1 vrate= 62.12%
7c1ee704a   Tejun Heo   iocost_monitor: R...
161
162
163
   *                 active      weight      hweight% inflt% dbt  delay usages%
   *  test/a              *    50/   50  33.33/ 33.33  27.65   2  0*041 033:033:033
   *  test/b              *   100/  100  66.67/ 66.67  17.56   0  0*000 066:079:077
6954ff185   Tejun Heo   blkcg: add tools/...
164
165
166
167
168
169
170
171
172
   *
   * - per	: Timer period
   * - cur_per	: Internal wall and device vtime clock
   * - vrate	: Device virtual time rate against wall clock
   * - weight	: Surplus-adjusted and configured weights
   * - hweight	: Surplus-adjusted and configured hierarchical weights
   * - inflt	: The percentage of in-flight IO cost at the end of last period
   * - del_ms	: Deferred issuer delay induction level and duration
   * - usages	: Usage history
7caa47151   Tejun Heo   blkcg: implement ...
173
174
175
176
177
178
179
180
181
   */
  
  #include <linux/kernel.h>
  #include <linux/module.h>
  #include <linux/timer.h>
  #include <linux/time64.h>
  #include <linux/parser.h>
  #include <linux/sched/signal.h>
  #include <linux/blk-cgroup.h>
5e124f743   Tejun Heo   blk-iocost: use l...
182
183
  #include <asm/local.h>
  #include <asm/local64.h>
7caa47151   Tejun Heo   blkcg: implement ...
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
  #include "blk-rq-qos.h"
  #include "blk-stat.h"
  #include "blk-wbt.h"
  
  #ifdef CONFIG_TRACEPOINTS
  
  /* copied from TRACE_CGROUP_PATH, see cgroup-internal.h */
  #define TRACE_IOCG_PATH_LEN 1024
  static DEFINE_SPINLOCK(trace_iocg_path_lock);
  static char trace_iocg_path[TRACE_IOCG_PATH_LEN];
  
  #define TRACE_IOCG_PATH(type, iocg, ...)					\
  	do {									\
  		unsigned long flags;						\
  		if (trace_iocost_##type##_enabled()) {				\
  			spin_lock_irqsave(&trace_iocg_path_lock, flags);	\
  			cgroup_path(iocg_to_blkg(iocg)->blkcg->css.cgroup,	\
  				    trace_iocg_path, TRACE_IOCG_PATH_LEN);	\
  			trace_iocost_##type(iocg, trace_iocg_path,		\
  					      ##__VA_ARGS__);			\
  			spin_unlock_irqrestore(&trace_iocg_path_lock, flags);	\
  		}								\
  	} while (0)
  
  #else	/* CONFIG_TRACE_POINTS */
  #define TRACE_IOCG_PATH(type, iocg, ...)	do { } while (0)
  #endif	/* CONFIG_TRACE_POINTS */
  
  enum {
  	MILLION			= 1000000,
  
  	/* timer period is calculated from latency requirements, bound it */
  	MIN_PERIOD		= USEC_PER_MSEC,
  	MAX_PERIOD		= USEC_PER_SEC,
  
  	/*
f1de2439e   Tejun Heo   blk-iocost: revam...
220
  	 * iocg->vtime is targeted at 50% behind the device vtime, which
7caa47151   Tejun Heo   blkcg: implement ...
221
222
223
  	 * serves as its IO credit buffer.  Surplus weight adjustment is
  	 * immediately canceled if the vtime margin runs below 10%.
  	 */
7ca5b2e60   Tejun Heo   blk-iocost: strea...
224
  	MARGIN_MIN_PCT		= 10,
f1de2439e   Tejun Heo   blk-iocost: revam...
225
226
  	MARGIN_LOW_PCT		= 20,
  	MARGIN_TARGET_PCT	= 50,
7caa47151   Tejun Heo   blkcg: implement ...
227

b0853ab4a   Tejun Heo   blk-iocost: revam...
228
  	INUSE_ADJ_STEP_PCT	= 25,
7ca5b2e60   Tejun Heo   blk-iocost: strea...
229
230
  	/* Have some play in timer operations */
  	TIMER_SLACK_PCT		= 1,
7caa47151   Tejun Heo   blkcg: implement ...
231

7caa47151   Tejun Heo   blkcg: implement ...
232
  	/* 1/64k is granular enough and can easily be handled w/ u32 */
fe20cdb51   Tejun Heo   blk-iocost: s/HWE...
233
  	WEIGHT_ONE		= 1 << 16,
7caa47151   Tejun Heo   blkcg: implement ...
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
  
  	/*
  	 * As vtime is used to calculate the cost of each IO, it needs to
  	 * be fairly high precision.  For example, it should be able to
  	 * represent the cost of a single page worth of discard with
  	 * suffificient accuracy.  At the same time, it should be able to
  	 * represent reasonably long enough durations to be useful and
  	 * convenient during operation.
  	 *
  	 * 1s worth of vtime is 2^37.  This gives us both sub-nanosecond
  	 * granularity and days of wrap-around time even at extreme vrates.
  	 */
  	VTIME_PER_SEC_SHIFT	= 37,
  	VTIME_PER_SEC		= 1LLU << VTIME_PER_SEC_SHIFT,
  	VTIME_PER_USEC		= VTIME_PER_SEC / USEC_PER_SEC,
cd006509b   Tejun Heo   blk-iocost: accou...
249
  	VTIME_PER_NSEC		= VTIME_PER_SEC / NSEC_PER_SEC,
7caa47151   Tejun Heo   blkcg: implement ...
250
251
252
253
254
255
256
257
258
259
260
261
262
  
  	/* bound vrate adjustments within two orders of magnitude */
  	VRATE_MIN_PPM		= 10000,	/* 1% */
  	VRATE_MAX_PPM		= 100000000,	/* 10000% */
  
  	VRATE_MIN		= VTIME_PER_USEC * VRATE_MIN_PPM / MILLION,
  	VRATE_CLAMP_ADJ_PCT	= 4,
  
  	/* if IOs end up waiting for requests, issue less */
  	RQ_WAIT_BUSY_PCT	= 5,
  
  	/* unbusy hysterisis */
  	UNBUSY_THR_PCT		= 75,
5160a5a53   Tejun Heo   blk-iocost: imple...
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
  	/*
  	 * The effect of delay is indirect and non-linear and a huge amount of
  	 * future debt can accumulate abruptly while unthrottled. Linearly scale
  	 * up delay as debt is going up and then let it decay exponentially.
  	 * This gives us quick ramp ups while delay is accumulating and long
  	 * tails which can help reducing the frequency of debt explosions on
  	 * unthrottle. The parameters are experimentally determined.
  	 *
  	 * The delay mechanism provides adequate protection and behavior in many
  	 * cases. However, this is far from ideal and falls shorts on both
  	 * fronts. The debtors are often throttled too harshly costing a
  	 * significant level of fairness and possibly total work while the
  	 * protection against their impacts on the system can be choppy and
  	 * unreliable.
  	 *
  	 * The shortcoming primarily stems from the fact that, unlike for page
  	 * cache, the kernel doesn't have well-defined back-pressure propagation
  	 * mechanism and policies for anonymous memory. Fully addressing this
  	 * issue will likely require substantial improvements in the area.
  	 */
  	MIN_DELAY_THR_PCT	= 500,
  	MAX_DELAY_THR_PCT	= 25000,
  	MIN_DELAY		= 250,
  	MAX_DELAY		= 250 * USEC_PER_MSEC,
c7af2a003   Tejun Heo   iocost: reimpleme...
287
288
289
  	/* halve debts if avg usage over 100ms is under 50% */
  	DFGV_USAGE_PCT		= 50,
  	DFGV_PERIOD		= 100 * USEC_PER_MSEC,
dda1315f1   Tejun Heo   blk-iocost: halve...
290

7caa47151   Tejun Heo   blkcg: implement ...
291
292
  	/* don't let cmds which take a very long time pin lagging for too long */
  	MAX_LAGGING_PERIODS	= 10,
7caa47151   Tejun Heo   blkcg: implement ...
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
  	/* switch iff the conditions are met for longer than this */
  	AUTOP_CYCLE_NSEC	= 10LLU * NSEC_PER_SEC,
  
  	/*
  	 * Count IO size in 4k pages.  The 12bit shift helps keeping
  	 * size-proportional components of cost calculation in closer
  	 * numbers of digits to per-IO cost components.
  	 */
  	IOC_PAGE_SHIFT		= 12,
  	IOC_PAGE_SIZE		= 1 << IOC_PAGE_SHIFT,
  	IOC_SECT_TO_PAGE_SHIFT	= IOC_PAGE_SHIFT - SECTOR_SHIFT,
  
  	/* if apart further than 16M, consider randio for linear model */
  	LCOEF_RANDIO_PAGES	= 4096,
  };
  
  enum ioc_running {
  	IOC_IDLE,
  	IOC_RUNNING,
  	IOC_STOP,
  };
  
  /* io.cost.qos controls including per-dev enable of the whole controller */
  enum {
  	QOS_ENABLE,
  	QOS_CTRL,
  	NR_QOS_CTRL_PARAMS,
  };
  
  /* io.cost.qos params */
  enum {
  	QOS_RPPM,
  	QOS_RLAT,
  	QOS_WPPM,
  	QOS_WLAT,
  	QOS_MIN,
  	QOS_MAX,
  	NR_QOS_PARAMS,
  };
  
  /* io.cost.model controls */
  enum {
  	COST_CTRL,
  	COST_MODEL,
  	NR_COST_CTRL_PARAMS,
  };
  
  /* builtin linear cost model coefficients */
  enum {
  	I_LCOEF_RBPS,
  	I_LCOEF_RSEQIOPS,
  	I_LCOEF_RRANDIOPS,
  	I_LCOEF_WBPS,
  	I_LCOEF_WSEQIOPS,
  	I_LCOEF_WRANDIOPS,
  	NR_I_LCOEFS,
  };
  
  enum {
  	LCOEF_RPAGE,
  	LCOEF_RSEQIO,
  	LCOEF_RRANDIO,
  	LCOEF_WPAGE,
  	LCOEF_WSEQIO,
  	LCOEF_WRANDIO,
  	NR_LCOEFS,
  };
  
  enum {
  	AUTOP_INVALID,
  	AUTOP_HDD,
  	AUTOP_SSD_QD1,
  	AUTOP_SSD_DFL,
  	AUTOP_SSD_FAST,
  };
7caa47151   Tejun Heo   blkcg: implement ...
368
369
370
371
372
373
374
  struct ioc_params {
  	u32				qos[NR_QOS_PARAMS];
  	u64				i_lcoefs[NR_I_LCOEFS];
  	u64				lcoefs[NR_LCOEFS];
  	u32				too_fast_vrate_pct;
  	u32				too_slow_vrate_pct;
  };
7ca5b2e60   Tejun Heo   blk-iocost: strea...
375
376
  struct ioc_margins {
  	s64				min;
f1de2439e   Tejun Heo   blk-iocost: revam...
377
378
  	s64				low;
  	s64				target;
7ca5b2e60   Tejun Heo   blk-iocost: strea...
379
  };
7caa47151   Tejun Heo   blkcg: implement ...
380
  struct ioc_missed {
5e124f743   Tejun Heo   blk-iocost: use l...
381
382
  	local_t				nr_met;
  	local_t				nr_missed;
7caa47151   Tejun Heo   blkcg: implement ...
383
384
385
386
387
388
  	u32				last_met;
  	u32				last_missed;
  };
  
  struct ioc_pcpu_stat {
  	struct ioc_missed		missed[2];
5e124f743   Tejun Heo   blk-iocost: use l...
389
  	local64_t			rq_wait_ns;
7caa47151   Tejun Heo   blkcg: implement ...
390
391
392
393
394
395
396
397
398
399
  	u64				last_rq_wait_ns;
  };
  
  /* per device */
  struct ioc {
  	struct rq_qos			rqos;
  
  	bool				enabled;
  
  	struct ioc_params		params;
7ca5b2e60   Tejun Heo   blk-iocost: strea...
400
  	struct ioc_margins		margins;
7caa47151   Tejun Heo   blkcg: implement ...
401
  	u32				period_us;
7ca5b2e60   Tejun Heo   blk-iocost: strea...
402
  	u32				timer_slack_ns;
7caa47151   Tejun Heo   blkcg: implement ...
403
404
405
406
407
408
409
410
411
412
  	u64				vrate_min;
  	u64				vrate_max;
  
  	spinlock_t			lock;
  	struct timer_list		timer;
  	struct list_head		active_iocgs;	/* active cgroups */
  	struct ioc_pcpu_stat __percpu	*pcpu_stat;
  
  	enum ioc_running		running;
  	atomic64_t			vtime_rate;
ac33e91e2   Tejun Heo   blk-iocost: imple...
413
414
  	u64				vtime_base_rate;
  	s64				vtime_err;
7caa47151   Tejun Heo   blkcg: implement ...
415

67b7b641c   Ahmed S. Darwish   iocost: Use seque...
416
  	seqcount_spinlock_t		period_seqcount;
ce95570ac   Tejun Heo   blk-iocost: make ...
417
  	u64				period_at;	/* wallclock starttime */
7caa47151   Tejun Heo   blkcg: implement ...
418
419
420
421
  	u64				period_at_vtime; /* vtime starttime */
  
  	atomic64_t			cur_period;	/* inc'd each period */
  	int				busy_level;	/* saturation history */
7caa47151   Tejun Heo   blkcg: implement ...
422
423
  	bool				weights_updated;
  	atomic_t			hweight_gen;	/* for lazy hweights */
c7af2a003   Tejun Heo   iocost: reimpleme...
424
425
426
427
  	/* debt forgivness */
  	u64				dfgv_period_at;
  	u64				dfgv_period_rem;
  	u64				dfgv_usage_us_sum;
dda1315f1   Tejun Heo   blk-iocost: halve...
428

7caa47151   Tejun Heo   blkcg: implement ...
429
430
431
432
433
434
  	u64				autop_too_fast_at;
  	u64				autop_too_slow_at;
  	int				autop_idx;
  	bool				user_qos_params:1;
  	bool				user_cost_model:1;
  };
97eb19751   Tejun Heo   blk-iocost: add a...
435
436
437
438
439
440
  struct iocg_pcpu_stat {
  	local64_t			abs_vusage;
  };
  
  struct iocg_stat {
  	u64				usage_us;
f0bf84a5d   Tejun Heo   blk-iocost: add t...
441
442
443
  	u64				wait_us;
  	u64				indebt_us;
  	u64				indelay_us;
97eb19751   Tejun Heo   blk-iocost: add a...
444
  };
7caa47151   Tejun Heo   blkcg: implement ...
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
  /* per device-cgroup pair */
  struct ioc_gq {
  	struct blkg_policy_data		pd;
  	struct ioc			*ioc;
  
  	/*
  	 * A iocg can get its weight from two sources - an explicit
  	 * per-device-cgroup configuration or the default weight of the
  	 * cgroup.  `cfg_weight` is the explicit per-device-cgroup
  	 * configuration.  `weight` is the effective considering both
  	 * sources.
  	 *
  	 * When an idle cgroup becomes active its `active` goes from 0 to
  	 * `weight`.  `inuse` is the surplus adjusted active weight.
  	 * `active` and `inuse` are used to calculate `hweight_active` and
  	 * `hweight_inuse`.
  	 *
  	 * `last_inuse` remembers `inuse` while an iocg is idle to persist
  	 * surplus adjustments.
b0853ab4a   Tejun Heo   blk-iocost: revam...
464
465
466
  	 *
  	 * `inuse` may be adjusted dynamically during period. `saved_*` are used
  	 * to determine and track adjustments.
7caa47151   Tejun Heo   blkcg: implement ...
467
468
469
470
471
  	 */
  	u32				cfg_weight;
  	u32				weight;
  	u32				active;
  	u32				inuse;
b0853ab4a   Tejun Heo   blk-iocost: revam...
472

7caa47151   Tejun Heo   blkcg: implement ...
473
  	u32				last_inuse;
b0853ab4a   Tejun Heo   blk-iocost: revam...
474
  	s64				saved_margin;
7caa47151   Tejun Heo   blkcg: implement ...
475
476
477
478
479
480
  
  	sector_t			cursor;		/* to detect randio */
  
  	/*
  	 * `vtime` is this iocg's vtime cursor which progresses as IOs are
  	 * issued.  If lagging behind device vtime, the delta represents
5ba1add21   Baolin Wang   blk-iocost: Fix s...
481
  	 * the currently available IO budget.  If running ahead, the
7caa47151   Tejun Heo   blkcg: implement ...
482
483
484
485
486
  	 * overage.
  	 *
  	 * `vtime_done` is the same but progressed on completion rather
  	 * than issue.  The delta behind `vtime` represents the cost of
  	 * currently in-flight IOs.
7caa47151   Tejun Heo   blkcg: implement ...
487
488
489
  	 */
  	atomic64_t			vtime;
  	atomic64_t			done_vtime;
0b80f9866   Tejun Heo   iocost: protect i...
490
  	u64				abs_vdebt;
7caa47151   Tejun Heo   blkcg: implement ...
491

5160a5a53   Tejun Heo   blk-iocost: imple...
492
493
494
  	/* current delay in effect and when it started */
  	u64				delay;
  	u64				delay_at;
7caa47151   Tejun Heo   blkcg: implement ...
495
496
497
498
499
500
  	/*
  	 * The period this iocg was last active in.  Used for deactivation
  	 * and invalidating `vtime`.
  	 */
  	atomic64_t			active_period;
  	struct list_head		active_list;
00410f1b0   Tejun Heo   blk-iocost: renam...
501
  	/* see __propagate_weights() and current_hweight() for details */
7caa47151   Tejun Heo   blkcg: implement ...
502
503
  	u64				child_active_sum;
  	u64				child_inuse_sum;
e08d02aa5   Tejun Heo   blk-iocost: imple...
504
  	u64				child_adjusted_sum;
7caa47151   Tejun Heo   blkcg: implement ...
505
506
507
  	int				hweight_gen;
  	u32				hweight_active;
  	u32				hweight_inuse;
e08d02aa5   Tejun Heo   blk-iocost: imple...
508
  	u32				hweight_donating;
93f7d2db8   Tejun Heo   blk-iocost: restr...
509
  	u32				hweight_after_donation;
7caa47151   Tejun Heo   blkcg: implement ...
510

97eb19751   Tejun Heo   blk-iocost: add a...
511
  	struct list_head		walk_list;
8692d2db8   Tejun Heo   blk-iocost: repla...
512
  	struct list_head		surplus_list;
97eb19751   Tejun Heo   blk-iocost: add a...
513

7caa47151   Tejun Heo   blkcg: implement ...
514
515
  	struct wait_queue_head		waitq;
  	struct hrtimer			waitq_timer;
7caa47151   Tejun Heo   blkcg: implement ...
516

1aa50d020   Tejun Heo   blk-iocost: calcu...
517
518
  	/* timestamp at the latest activation */
  	u64				activated_at;
97eb19751   Tejun Heo   blk-iocost: add a...
519
520
521
522
523
524
  	/* statistics */
  	struct iocg_pcpu_stat __percpu	*pcpu_stat;
  	struct iocg_stat		local_stat;
  	struct iocg_stat		desc_stat;
  	struct iocg_stat		last_stat;
  	u64				last_stat_abs_vusage;
f1de2439e   Tejun Heo   blk-iocost: revam...
525
  	u64				usage_delta_us;
f0bf84a5d   Tejun Heo   blk-iocost: add t...
526
527
528
  	u64				wait_since;
  	u64				indebt_since;
  	u64				indelay_since;
7caa47151   Tejun Heo   blkcg: implement ...
529
530
531
532
533
534
535
536
537
538
539
540
541
542
  
  	/* this iocg's depth in the hierarchy and ancestors including self */
  	int				level;
  	struct ioc_gq			*ancestors[];
  };
  
  /* per cgroup */
  struct ioc_cgrp {
  	struct blkcg_policy_data	cpd;
  	unsigned int			dfl_weight;
  };
  
  struct ioc_now {
  	u64				now_ns;
ce95570ac   Tejun Heo   blk-iocost: make ...
543
  	u64				now;
7caa47151   Tejun Heo   blkcg: implement ...
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
  	u64				vnow;
  	u64				vrate;
  };
  
  struct iocg_wait {
  	struct wait_queue_entry		wait;
  	struct bio			*bio;
  	u64				abs_cost;
  	bool				committed;
  };
  
  struct iocg_wake_ctx {
  	struct ioc_gq			*iocg;
  	u32				hw_inuse;
  	s64				vbudget;
  };
  
  static const struct ioc_params autop[] = {
  	[AUTOP_HDD] = {
  		.qos				= {
7afcccafa   Tejun Heo   iocost: bump up d...
564
565
  			[QOS_RLAT]		=        250000, /* 250ms */
  			[QOS_WLAT]		=        250000,
7caa47151   Tejun Heo   blkcg: implement ...
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
  			[QOS_MIN]		= VRATE_MIN_PPM,
  			[QOS_MAX]		= VRATE_MAX_PPM,
  		},
  		.i_lcoefs			= {
  			[I_LCOEF_RBPS]		=     174019176,
  			[I_LCOEF_RSEQIOPS]	=         41708,
  			[I_LCOEF_RRANDIOPS]	=           370,
  			[I_LCOEF_WBPS]		=     178075866,
  			[I_LCOEF_WSEQIOPS]	=         42705,
  			[I_LCOEF_WRANDIOPS]	=           378,
  		},
  	},
  	[AUTOP_SSD_QD1] = {
  		.qos				= {
  			[QOS_RLAT]		=         25000, /* 25ms */
  			[QOS_WLAT]		=         25000,
  			[QOS_MIN]		= VRATE_MIN_PPM,
  			[QOS_MAX]		= VRATE_MAX_PPM,
  		},
  		.i_lcoefs			= {
  			[I_LCOEF_RBPS]		=     245855193,
  			[I_LCOEF_RSEQIOPS]	=         61575,
  			[I_LCOEF_RRANDIOPS]	=          6946,
  			[I_LCOEF_WBPS]		=     141365009,
  			[I_LCOEF_WSEQIOPS]	=         33716,
  			[I_LCOEF_WRANDIOPS]	=         26796,
  		},
  	},
  	[AUTOP_SSD_DFL] = {
  		.qos				= {
  			[QOS_RLAT]		=         25000, /* 25ms */
  			[QOS_WLAT]		=         25000,
  			[QOS_MIN]		= VRATE_MIN_PPM,
  			[QOS_MAX]		= VRATE_MAX_PPM,
  		},
  		.i_lcoefs			= {
  			[I_LCOEF_RBPS]		=     488636629,
  			[I_LCOEF_RSEQIOPS]	=          8932,
  			[I_LCOEF_RRANDIOPS]	=          8518,
  			[I_LCOEF_WBPS]		=     427891549,
  			[I_LCOEF_WSEQIOPS]	=         28755,
  			[I_LCOEF_WRANDIOPS]	=         21940,
  		},
  		.too_fast_vrate_pct		=           500,
  	},
  	[AUTOP_SSD_FAST] = {
  		.qos				= {
  			[QOS_RLAT]		=          5000, /* 5ms */
  			[QOS_WLAT]		=          5000,
  			[QOS_MIN]		= VRATE_MIN_PPM,
  			[QOS_MAX]		= VRATE_MAX_PPM,
  		},
  		.i_lcoefs			= {
  			[I_LCOEF_RBPS]		=    3102524156LLU,
  			[I_LCOEF_RSEQIOPS]	=        724816,
  			[I_LCOEF_RRANDIOPS]	=        778122,
  			[I_LCOEF_WBPS]		=    1742780862LLU,
  			[I_LCOEF_WSEQIOPS]	=        425702,
  			[I_LCOEF_WRANDIOPS]	=	 443193,
  		},
  		.too_slow_vrate_pct		=            10,
  	},
  };
  
  /*
   * vrate adjust percentages indexed by ioc->busy_level.  We adjust up on
   * vtime credit shortage and down on device saturation.
   */
  static u32 vrate_adj_pct[] =
  	{ 0, 0, 0, 0,
  	  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  	  2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  	  4, 4, 4, 4, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8, 16 };
  
  static struct blkcg_policy blkcg_policy_iocost;
  
  /* accessors and helpers */
  static struct ioc *rqos_to_ioc(struct rq_qos *rqos)
  {
  	return container_of(rqos, struct ioc, rqos);
  }
  
  static struct ioc *q_to_ioc(struct request_queue *q)
  {
  	return rqos_to_ioc(rq_qos_id(q, RQ_QOS_COST));
  }
  
  static const char *q_name(struct request_queue *q)
  {
75e6c00fc   Yufen Yu   block: use helper...
655
  	if (blk_queue_registered(q))
7caa47151   Tejun Heo   blkcg: implement ...
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
  		return kobject_name(q->kobj.parent);
  	else
  		return "<unknown>";
  }
  
  static const char __maybe_unused *ioc_name(struct ioc *ioc)
  {
  	return q_name(ioc->rqos.q);
  }
  
  static struct ioc_gq *pd_to_iocg(struct blkg_policy_data *pd)
  {
  	return pd ? container_of(pd, struct ioc_gq, pd) : NULL;
  }
  
  static struct ioc_gq *blkg_to_iocg(struct blkcg_gq *blkg)
  {
  	return pd_to_iocg(blkg_to_pd(blkg, &blkcg_policy_iocost));
  }
  
  static struct blkcg_gq *iocg_to_blkg(struct ioc_gq *iocg)
  {
  	return pd_to_blkg(&iocg->pd);
  }
  
  static struct ioc_cgrp *blkcg_to_iocc(struct blkcg *blkcg)
  {
  	return container_of(blkcg_to_cpd(blkcg, &blkcg_policy_iocost),
  			    struct ioc_cgrp, cpd);
  }
  
  /*
   * Scale @abs_cost to the inverse of @hw_inuse.  The lower the hierarchical
36a524814   Tejun Heo   blk-iocost: Accou...
689
   * weight, the more expensive each IO.  Must round up.
7caa47151   Tejun Heo   blkcg: implement ...
690
691
692
   */
  static u64 abs_cost_to_cost(u64 abs_cost, u32 hw_inuse)
  {
fe20cdb51   Tejun Heo   blk-iocost: s/HWE...
693
  	return DIV64_U64_ROUND_UP(abs_cost * WEIGHT_ONE, hw_inuse);
7caa47151   Tejun Heo   blkcg: implement ...
694
  }
36a524814   Tejun Heo   blk-iocost: Accou...
695
696
697
698
699
  /*
   * The inverse of abs_cost_to_cost().  Must round up.
   */
  static u64 cost_to_abs_cost(u64 cost, u32 hw_inuse)
  {
fe20cdb51   Tejun Heo   blk-iocost: s/HWE...
700
  	return DIV64_U64_ROUND_UP(cost * hw_inuse, WEIGHT_ONE);
36a524814   Tejun Heo   blk-iocost: Accou...
701
  }
97eb19751   Tejun Heo   blk-iocost: add a...
702
703
  static void iocg_commit_bio(struct ioc_gq *iocg, struct bio *bio,
  			    u64 abs_cost, u64 cost)
7caa47151   Tejun Heo   blkcg: implement ...
704
  {
97eb19751   Tejun Heo   blk-iocost: add a...
705
  	struct iocg_pcpu_stat *gcs;
7caa47151   Tejun Heo   blkcg: implement ...
706
707
  	bio->bi_iocost_cost = cost;
  	atomic64_add(cost, &iocg->vtime);
97eb19751   Tejun Heo   blk-iocost: add a...
708
709
710
711
  
  	gcs = get_cpu_ptr(iocg->pcpu_stat);
  	local64_add(abs_cost, &gcs->abs_vusage);
  	put_cpu_ptr(gcs);
7caa47151   Tejun Heo   blkcg: implement ...
712
  }
da437b95d   Tejun Heo   blk-iocost: grab ...
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
  static void iocg_lock(struct ioc_gq *iocg, bool lock_ioc, unsigned long *flags)
  {
  	if (lock_ioc) {
  		spin_lock_irqsave(&iocg->ioc->lock, *flags);
  		spin_lock(&iocg->waitq.lock);
  	} else {
  		spin_lock_irqsave(&iocg->waitq.lock, *flags);
  	}
  }
  
  static void iocg_unlock(struct ioc_gq *iocg, bool unlock_ioc, unsigned long *flags)
  {
  	if (unlock_ioc) {
  		spin_unlock(&iocg->waitq.lock);
  		spin_unlock_irqrestore(&iocg->ioc->lock, *flags);
  	} else {
  		spin_unlock_irqrestore(&iocg->waitq.lock, *flags);
  	}
  }
7caa47151   Tejun Heo   blkcg: implement ...
732
733
  #define CREATE_TRACE_POINTS
  #include <trace/events/iocost.h>
7ca5b2e60   Tejun Heo   blk-iocost: strea...
734
735
736
737
  static void ioc_refresh_margins(struct ioc *ioc)
  {
  	struct ioc_margins *margins = &ioc->margins;
  	u32 period_us = ioc->period_us;
ac33e91e2   Tejun Heo   blk-iocost: imple...
738
  	u64 vrate = ioc->vtime_base_rate;
7ca5b2e60   Tejun Heo   blk-iocost: strea...
739
740
  
  	margins->min = (period_us * MARGIN_MIN_PCT / 100) * vrate;
f1de2439e   Tejun Heo   blk-iocost: revam...
741
742
  	margins->low = (period_us * MARGIN_LOW_PCT / 100) * vrate;
  	margins->target = (period_us * MARGIN_TARGET_PCT / 100) * vrate;
7ca5b2e60   Tejun Heo   blk-iocost: strea...
743
  }
7caa47151   Tejun Heo   blkcg: implement ...
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
  /* latency Qos params changed, update period_us and all the dependent params */
  static void ioc_refresh_period_us(struct ioc *ioc)
  {
  	u32 ppm, lat, multi, period_us;
  
  	lockdep_assert_held(&ioc->lock);
  
  	/* pick the higher latency target */
  	if (ioc->params.qos[QOS_RLAT] >= ioc->params.qos[QOS_WLAT]) {
  		ppm = ioc->params.qos[QOS_RPPM];
  		lat = ioc->params.qos[QOS_RLAT];
  	} else {
  		ppm = ioc->params.qos[QOS_WPPM];
  		lat = ioc->params.qos[QOS_WLAT];
  	}
  
  	/*
  	 * We want the period to be long enough to contain a healthy number
  	 * of IOs while short enough for granular control.  Define it as a
  	 * multiple of the latency target.  Ideally, the multiplier should
  	 * be scaled according to the percentile so that it would nominally
  	 * contain a certain number of requests.  Let's be simpler and
  	 * scale it linearly so that it's 2x >= pct(90) and 10x at pct(50).
  	 */
  	if (ppm)
  		multi = max_t(u32, (MILLION - ppm) / 50000, 2);
  	else
  		multi = 2;
  	period_us = multi * lat;
  	period_us = clamp_t(u32, period_us, MIN_PERIOD, MAX_PERIOD);
  
  	/* calculate dependent params */
  	ioc->period_us = period_us;
7ca5b2e60   Tejun Heo   blk-iocost: strea...
777
778
779
780
  	ioc->timer_slack_ns = div64_u64(
  		(u64)period_us * NSEC_PER_USEC * TIMER_SLACK_PCT,
  		100);
  	ioc_refresh_margins(ioc);
7caa47151   Tejun Heo   blkcg: implement ...
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
  }
  
  static int ioc_autop_idx(struct ioc *ioc)
  {
  	int idx = ioc->autop_idx;
  	const struct ioc_params *p = &autop[idx];
  	u32 vrate_pct;
  	u64 now_ns;
  
  	/* rotational? */
  	if (!blk_queue_nonrot(ioc->rqos.q))
  		return AUTOP_HDD;
  
  	/* handle SATA SSDs w/ broken NCQ */
  	if (blk_queue_depth(ioc->rqos.q) == 1)
  		return AUTOP_SSD_QD1;
  
  	/* use one of the normal ssd sets */
  	if (idx < AUTOP_SSD_DFL)
  		return AUTOP_SSD_DFL;
  
  	/* if user is overriding anything, maintain what was there */
  	if (ioc->user_qos_params || ioc->user_cost_model)
  		return idx;
  
  	/* step up/down based on the vrate */
ac33e91e2   Tejun Heo   blk-iocost: imple...
807
  	vrate_pct = div64_u64(ioc->vtime_base_rate * 100, VTIME_PER_USEC);
7caa47151   Tejun Heo   blkcg: implement ...
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
  	now_ns = ktime_get_ns();
  
  	if (p->too_fast_vrate_pct && p->too_fast_vrate_pct <= vrate_pct) {
  		if (!ioc->autop_too_fast_at)
  			ioc->autop_too_fast_at = now_ns;
  		if (now_ns - ioc->autop_too_fast_at >= AUTOP_CYCLE_NSEC)
  			return idx + 1;
  	} else {
  		ioc->autop_too_fast_at = 0;
  	}
  
  	if (p->too_slow_vrate_pct && p->too_slow_vrate_pct >= vrate_pct) {
  		if (!ioc->autop_too_slow_at)
  			ioc->autop_too_slow_at = now_ns;
  		if (now_ns - ioc->autop_too_slow_at >= AUTOP_CYCLE_NSEC)
  			return idx - 1;
  	} else {
  		ioc->autop_too_slow_at = 0;
  	}
  
  	return idx;
  }
  
  /*
   * Take the followings as input
   *
   *  @bps	maximum sequential throughput
   *  @seqiops	maximum sequential 4k iops
   *  @randiops	maximum random 4k iops
   *
   * and calculate the linear model cost coefficients.
   *
   *  *@page	per-page cost		1s / (@bps / 4096)
   *  *@seqio	base cost of a seq IO	max((1s / @seqiops) - *@page, 0)
   *  @randiops	base cost of a rand IO	max((1s / @randiops) - *@page, 0)
   */
  static void calc_lcoefs(u64 bps, u64 seqiops, u64 randiops,
  			u64 *page, u64 *seqio, u64 *randio)
  {
  	u64 v;
  
  	*page = *seqio = *randio = 0;
  
  	if (bps)
  		*page = DIV64_U64_ROUND_UP(VTIME_PER_SEC,
  					   DIV_ROUND_UP_ULL(bps, IOC_PAGE_SIZE));
  
  	if (seqiops) {
  		v = DIV64_U64_ROUND_UP(VTIME_PER_SEC, seqiops);
  		if (v > *page)
  			*seqio = v - *page;
  	}
  
  	if (randiops) {
  		v = DIV64_U64_ROUND_UP(VTIME_PER_SEC, randiops);
  		if (v > *page)
  			*randio = v - *page;
  	}
  }
  
  static void ioc_refresh_lcoefs(struct ioc *ioc)
  {
  	u64 *u = ioc->params.i_lcoefs;
  	u64 *c = ioc->params.lcoefs;
  
  	calc_lcoefs(u[I_LCOEF_RBPS], u[I_LCOEF_RSEQIOPS], u[I_LCOEF_RRANDIOPS],
  		    &c[LCOEF_RPAGE], &c[LCOEF_RSEQIO], &c[LCOEF_RRANDIO]);
  	calc_lcoefs(u[I_LCOEF_WBPS], u[I_LCOEF_WSEQIOPS], u[I_LCOEF_WRANDIOPS],
  		    &c[LCOEF_WPAGE], &c[LCOEF_WSEQIO], &c[LCOEF_WRANDIO]);
  }
  
  static bool ioc_refresh_params(struct ioc *ioc, bool force)
  {
  	const struct ioc_params *p;
  	int idx;
  
  	lockdep_assert_held(&ioc->lock);
  
  	idx = ioc_autop_idx(ioc);
  	p = &autop[idx];
  
  	if (idx == ioc->autop_idx && !force)
  		return false;
  
  	if (idx != ioc->autop_idx)
  		atomic64_set(&ioc->vtime_rate, VTIME_PER_USEC);
  
  	ioc->autop_idx = idx;
  	ioc->autop_too_fast_at = 0;
  	ioc->autop_too_slow_at = 0;
  
  	if (!ioc->user_qos_params)
  		memcpy(ioc->params.qos, p->qos, sizeof(p->qos));
  	if (!ioc->user_cost_model)
  		memcpy(ioc->params.i_lcoefs, p->i_lcoefs, sizeof(p->i_lcoefs));
  
  	ioc_refresh_period_us(ioc);
  	ioc_refresh_lcoefs(ioc);
  
  	ioc->vrate_min = DIV64_U64_ROUND_UP((u64)ioc->params.qos[QOS_MIN] *
  					    VTIME_PER_USEC, MILLION);
  	ioc->vrate_max = div64_u64((u64)ioc->params.qos[QOS_MAX] *
  				   VTIME_PER_USEC, MILLION);
  
  	return true;
  }
ac33e91e2   Tejun Heo   blk-iocost: imple...
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
  /*
   * When an iocg accumulates too much vtime or gets deactivated, we throw away
   * some vtime, which lowers the overall device utilization. As the exact amount
   * which is being thrown away is known, we can compensate by accelerating the
   * vrate accordingly so that the extra vtime generated in the current period
   * matches what got lost.
   */
  static void ioc_refresh_vrate(struct ioc *ioc, struct ioc_now *now)
  {
  	s64 pleft = ioc->period_at + ioc->period_us - now->now;
  	s64 vperiod = ioc->period_us * ioc->vtime_base_rate;
  	s64 vcomp, vcomp_min, vcomp_max;
  
  	lockdep_assert_held(&ioc->lock);
  
  	/* we need some time left in this period */
  	if (pleft <= 0)
  		goto done;
  
  	/*
  	 * Calculate how much vrate should be adjusted to offset the error.
  	 * Limit the amount of adjustment and deduct the adjusted amount from
  	 * the error.
  	 */
  	vcomp = -div64_s64(ioc->vtime_err, pleft);
  	vcomp_min = -(ioc->vtime_base_rate >> 1);
  	vcomp_max = ioc->vtime_base_rate;
  	vcomp = clamp(vcomp, vcomp_min, vcomp_max);
  
  	ioc->vtime_err += vcomp * pleft;
  
  	atomic64_set(&ioc->vtime_rate, ioc->vtime_base_rate + vcomp);
  done:
  	/* bound how much error can accumulate */
  	ioc->vtime_err = clamp(ioc->vtime_err, -vperiod, vperiod);
  }
926f75f6a   Baolin Wang   blk-iocost: Facto...
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
  static void ioc_adjust_base_vrate(struct ioc *ioc, u32 rq_wait_pct,
  				  int nr_lagging, int nr_shortages,
  				  int prev_busy_level, u32 *missed_ppm)
  {
  	u64 vrate = ioc->vtime_base_rate;
  	u64 vrate_min = ioc->vrate_min, vrate_max = ioc->vrate_max;
  
  	if (!ioc->busy_level || (ioc->busy_level < 0 && nr_lagging)) {
  		if (ioc->busy_level != prev_busy_level || nr_lagging)
  			trace_iocost_ioc_vrate_adj(ioc, atomic64_read(&ioc->vtime_rate),
  						   missed_ppm, rq_wait_pct,
  						   nr_lagging, nr_shortages);
  
  		return;
  	}
  
  	/* rq_wait signal is always reliable, ignore user vrate_min */
  	if (rq_wait_pct > RQ_WAIT_BUSY_PCT)
  		vrate_min = VRATE_MIN;
  
  	/*
  	 * If vrate is out of bounds, apply clamp gradually as the
  	 * bounds can change abruptly.  Otherwise, apply busy_level
  	 * based adjustment.
  	 */
  	if (vrate < vrate_min) {
  		vrate = div64_u64(vrate * (100 + VRATE_CLAMP_ADJ_PCT), 100);
  		vrate = min(vrate, vrate_min);
  	} else if (vrate > vrate_max) {
  		vrate = div64_u64(vrate * (100 - VRATE_CLAMP_ADJ_PCT), 100);
  		vrate = max(vrate, vrate_max);
  	} else {
  		int idx = min_t(int, abs(ioc->busy_level),
  				ARRAY_SIZE(vrate_adj_pct) - 1);
  		u32 adj_pct = vrate_adj_pct[idx];
  
  		if (ioc->busy_level > 0)
  			adj_pct = 100 - adj_pct;
  		else
  			adj_pct = 100 + adj_pct;
  
  		vrate = clamp(DIV64_U64_ROUND_UP(vrate * adj_pct, 100),
  			      vrate_min, vrate_max);
  	}
  
  	trace_iocost_ioc_vrate_adj(ioc, vrate, missed_ppm, rq_wait_pct,
  				   nr_lagging, nr_shortages);
  
  	ioc->vtime_base_rate = vrate;
  	ioc_refresh_margins(ioc);
  }
7caa47151   Tejun Heo   blkcg: implement ...
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
  /* take a snapshot of the current [v]time and vrate */
  static void ioc_now(struct ioc *ioc, struct ioc_now *now)
  {
  	unsigned seq;
  
  	now->now_ns = ktime_get();
  	now->now = ktime_to_us(now->now_ns);
  	now->vrate = atomic64_read(&ioc->vtime_rate);
  
  	/*
  	 * The current vtime is
  	 *
  	 *   vtime at period start + (wallclock time since the start) * vrate
  	 *
  	 * As a consistent snapshot of `period_at_vtime` and `period_at` is
  	 * needed, they're seqcount protected.
  	 */
  	do {
  		seq = read_seqcount_begin(&ioc->period_seqcount);
  		now->vnow = ioc->period_at_vtime +
  			(now->now - ioc->period_at) * now->vrate;
  	} while (read_seqcount_retry(&ioc->period_seqcount, seq));
  }
  
  static void ioc_start_period(struct ioc *ioc, struct ioc_now *now)
  {
7caa47151   Tejun Heo   blkcg: implement ...
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
  	WARN_ON_ONCE(ioc->running != IOC_RUNNING);
  
  	write_seqcount_begin(&ioc->period_seqcount);
  	ioc->period_at = now->now;
  	ioc->period_at_vtime = now->vnow;
  	write_seqcount_end(&ioc->period_seqcount);
  
  	ioc->timer.expires = jiffies + usecs_to_jiffies(ioc->period_us);
  	add_timer(&ioc->timer);
  }
  
  /*
   * Update @iocg's `active` and `inuse` to @active and @inuse, update level
b0853ab4a   Tejun Heo   blk-iocost: revam...
1040
1041
   * weight sums and propagate upwards accordingly. If @save, the current margin
   * is saved to be used as reference for later inuse in-period adjustments.
7caa47151   Tejun Heo   blkcg: implement ...
1042
   */
b0853ab4a   Tejun Heo   blk-iocost: revam...
1043
1044
  static void __propagate_weights(struct ioc_gq *iocg, u32 active, u32 inuse,
  				bool save, struct ioc_now *now)
7caa47151   Tejun Heo   blkcg: implement ...
1045
1046
1047
1048
1049
  {
  	struct ioc *ioc = iocg->ioc;
  	int lvl;
  
  	lockdep_assert_held(&ioc->lock);
db84a72af   Tejun Heo   blk-iocost: clamp...
1050
  	inuse = clamp_t(u32, inuse, 1, active);
b0853ab4a   Tejun Heo   blk-iocost: revam...
1051
1052
1053
  	iocg->last_inuse = iocg->inuse;
  	if (save)
  		iocg->saved_margin = now->vnow - atomic64_read(&iocg->vtime);
db84a72af   Tejun Heo   blk-iocost: clamp...
1054
1055
  	if (active == iocg->active && inuse == iocg->inuse)
  		return;
7caa47151   Tejun Heo   blkcg: implement ...
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
  
  	for (lvl = iocg->level - 1; lvl >= 0; lvl--) {
  		struct ioc_gq *parent = iocg->ancestors[lvl];
  		struct ioc_gq *child = iocg->ancestors[lvl + 1];
  		u32 parent_active = 0, parent_inuse = 0;
  
  		/* update the level sums */
  		parent->child_active_sum += (s32)(active - child->active);
  		parent->child_inuse_sum += (s32)(inuse - child->inuse);
  		/* apply the udpates */
  		child->active = active;
  		child->inuse = inuse;
  
  		/*
  		 * The delta between inuse and active sums indicates that
5ba1add21   Baolin Wang   blk-iocost: Fix s...
1071
  		 * much of weight is being given away.  Parent's inuse
7caa47151   Tejun Heo   blkcg: implement ...
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
  		 * and active should reflect the ratio.
  		 */
  		if (parent->child_active_sum) {
  			parent_active = parent->weight;
  			parent_inuse = DIV64_U64_ROUND_UP(
  				parent_active * parent->child_inuse_sum,
  				parent->child_active_sum);
  		}
  
  		/* do we need to keep walking up? */
  		if (parent_active == parent->active &&
  		    parent_inuse == parent->inuse)
  			break;
  
  		active = parent_active;
  		inuse = parent_inuse;
  	}
  
  	ioc->weights_updated = true;
  }
00410f1b0   Tejun Heo   blk-iocost: renam...
1092
  static void commit_weights(struct ioc *ioc)
7caa47151   Tejun Heo   blkcg: implement ...
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
  {
  	lockdep_assert_held(&ioc->lock);
  
  	if (ioc->weights_updated) {
  		/* paired with rmb in current_hweight(), see there */
  		smp_wmb();
  		atomic_inc(&ioc->hweight_gen);
  		ioc->weights_updated = false;
  	}
  }
b0853ab4a   Tejun Heo   blk-iocost: revam...
1103
1104
  static void propagate_weights(struct ioc_gq *iocg, u32 active, u32 inuse,
  			      bool save, struct ioc_now *now)
7caa47151   Tejun Heo   blkcg: implement ...
1105
  {
b0853ab4a   Tejun Heo   blk-iocost: revam...
1106
  	__propagate_weights(iocg, active, inuse, save, now);
00410f1b0   Tejun Heo   blk-iocost: renam...
1107
  	commit_weights(iocg->ioc);
7caa47151   Tejun Heo   blkcg: implement ...
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
  }
  
  static void current_hweight(struct ioc_gq *iocg, u32 *hw_activep, u32 *hw_inusep)
  {
  	struct ioc *ioc = iocg->ioc;
  	int lvl;
  	u32 hwa, hwi;
  	int ioc_gen;
  
  	/* hot path - if uptodate, use cached */
  	ioc_gen = atomic_read(&ioc->hweight_gen);
  	if (ioc_gen == iocg->hweight_gen)
  		goto out;
  
  	/*
00410f1b0   Tejun Heo   blk-iocost: renam...
1123
1124
1125
  	 * Paired with wmb in commit_weights(). If we saw the updated
  	 * hweight_gen, all the weight updates from __propagate_weights() are
  	 * visible too.
7caa47151   Tejun Heo   blkcg: implement ...
1126
1127
1128
1129
1130
1131
1132
  	 *
  	 * We can race with weight updates during calculation and get it
  	 * wrong.  However, hweight_gen would have changed and a future
  	 * reader will recalculate and we're guaranteed to discard the
  	 * wrong result soon.
  	 */
  	smp_rmb();
fe20cdb51   Tejun Heo   blk-iocost: s/HWE...
1133
  	hwa = hwi = WEIGHT_ONE;
7caa47151   Tejun Heo   blkcg: implement ...
1134
1135
1136
  	for (lvl = 0; lvl <= iocg->level - 1; lvl++) {
  		struct ioc_gq *parent = iocg->ancestors[lvl];
  		struct ioc_gq *child = iocg->ancestors[lvl + 1];
bd0adb91a   Tejun Heo   blk-iocost: use W...
1137
1138
  		u64 active_sum = READ_ONCE(parent->child_active_sum);
  		u64 inuse_sum = READ_ONCE(parent->child_inuse_sum);
7caa47151   Tejun Heo   blkcg: implement ...
1139
1140
1141
1142
1143
1144
  		u32 active = READ_ONCE(child->active);
  		u32 inuse = READ_ONCE(child->inuse);
  
  		/* we can race with deactivations and either may read as zero */
  		if (!active_sum || !inuse_sum)
  			continue;
bd0adb91a   Tejun Heo   blk-iocost: use W...
1145
1146
  		active_sum = max_t(u64, active, active_sum);
  		hwa = div64_u64((u64)hwa * active, active_sum);
7caa47151   Tejun Heo   blkcg: implement ...
1147

bd0adb91a   Tejun Heo   blk-iocost: use W...
1148
1149
  		inuse_sum = max_t(u64, inuse, inuse_sum);
  		hwi = div64_u64((u64)hwi * inuse, inuse_sum);
7caa47151   Tejun Heo   blkcg: implement ...
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
  	}
  
  	iocg->hweight_active = max_t(u32, hwa, 1);
  	iocg->hweight_inuse = max_t(u32, hwi, 1);
  	iocg->hweight_gen = ioc_gen;
  out:
  	if (hw_activep)
  		*hw_activep = iocg->hweight_active;
  	if (hw_inusep)
  		*hw_inusep = iocg->hweight_inuse;
  }
93f7d2db8   Tejun Heo   blk-iocost: restr...
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
  /*
   * Calculate the hweight_inuse @iocg would get with max @inuse assuming all the
   * other weights stay unchanged.
   */
  static u32 current_hweight_max(struct ioc_gq *iocg)
  {
  	u32 hwm = WEIGHT_ONE;
  	u32 inuse = iocg->active;
  	u64 child_inuse_sum;
  	int lvl;
  
  	lockdep_assert_held(&iocg->ioc->lock);
  
  	for (lvl = iocg->level - 1; lvl >= 0; lvl--) {
  		struct ioc_gq *parent = iocg->ancestors[lvl];
  		struct ioc_gq *child = iocg->ancestors[lvl + 1];
  
  		child_inuse_sum = parent->child_inuse_sum + inuse - child->inuse;
  		hwm = div64_u64((u64)hwm * inuse, child_inuse_sum);
  		inuse = DIV64_U64_ROUND_UP(parent->active * child_inuse_sum,
  					   parent->child_active_sum);
  	}
  
  	return max_t(u32, hwm, 1);
  }
b0853ab4a   Tejun Heo   blk-iocost: revam...
1186
  static void weight_updated(struct ioc_gq *iocg, struct ioc_now *now)
7caa47151   Tejun Heo   blkcg: implement ...
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
  {
  	struct ioc *ioc = iocg->ioc;
  	struct blkcg_gq *blkg = iocg_to_blkg(iocg);
  	struct ioc_cgrp *iocc = blkcg_to_iocc(blkg->blkcg);
  	u32 weight;
  
  	lockdep_assert_held(&ioc->lock);
  
  	weight = iocg->cfg_weight ?: iocc->dfl_weight;
  	if (weight != iocg->weight && iocg->active)
b0853ab4a   Tejun Heo   blk-iocost: revam...
1197
  		propagate_weights(iocg, weight, iocg->inuse, true, now);
7caa47151   Tejun Heo   blkcg: implement ...
1198
1199
1200
1201
1202
1203
  	iocg->weight = weight;
  }
  
  static bool iocg_activate(struct ioc_gq *iocg, struct ioc_now *now)
  {
  	struct ioc *ioc = iocg->ioc;
ac33e91e2   Tejun Heo   blk-iocost: imple...
1204
1205
  	u64 last_period, cur_period;
  	u64 vtime, vtarget;
7caa47151   Tejun Heo   blkcg: implement ...
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
  	int i;
  
  	/*
  	 * If seem to be already active, just update the stamp to tell the
  	 * timer that we're still active.  We don't mind occassional races.
  	 */
  	if (!list_empty(&iocg->active_list)) {
  		ioc_now(ioc, now);
  		cur_period = atomic64_read(&ioc->cur_period);
  		if (atomic64_read(&iocg->active_period) != cur_period)
  			atomic64_set(&iocg->active_period, cur_period);
  		return true;
  	}
  
  	/* racy check on internal node IOs, treat as root level IOs */
  	if (iocg->child_active_sum)
  		return false;
  
  	spin_lock_irq(&ioc->lock);
  
  	ioc_now(ioc, now);
  
  	/* update period */
  	cur_period = atomic64_read(&ioc->cur_period);
  	last_period = atomic64_read(&iocg->active_period);
  	atomic64_set(&iocg->active_period, cur_period);
  
  	/* already activated or breaking leaf-only constraint? */
8b37bc277   Jiufei Xue   iocost: check act...
1234
1235
1236
1237
  	if (!list_empty(&iocg->active_list))
  		goto succeed_unlock;
  	for (i = iocg->level - 1; i > 0; i--)
  		if (!list_empty(&iocg->ancestors[i]->active_list))
7caa47151   Tejun Heo   blkcg: implement ...
1238
  			goto fail_unlock;
8b37bc277   Jiufei Xue   iocost: check act...
1239

7caa47151   Tejun Heo   blkcg: implement ...
1240
1241
1242
1243
  	if (iocg->child_active_sum)
  		goto fail_unlock;
  
  	/*
ac33e91e2   Tejun Heo   blk-iocost: imple...
1244
1245
  	 * Always start with the target budget. On deactivation, we throw away
  	 * anything above it.
7caa47151   Tejun Heo   blkcg: implement ...
1246
  	 */
ac33e91e2   Tejun Heo   blk-iocost: imple...
1247
  	vtarget = now->vnow - ioc->margins.target;
7caa47151   Tejun Heo   blkcg: implement ...
1248
  	vtime = atomic64_read(&iocg->vtime);
7caa47151   Tejun Heo   blkcg: implement ...
1249

ac33e91e2   Tejun Heo   blk-iocost: imple...
1250
1251
1252
  	atomic64_add(vtarget - vtime, &iocg->vtime);
  	atomic64_add(vtarget - vtime, &iocg->done_vtime);
  	vtime = vtarget;
7caa47151   Tejun Heo   blkcg: implement ...
1253
1254
1255
1256
1257
1258
1259
1260
  
  	/*
  	 * Activate, propagate weight and start period timer if not
  	 * running.  Reset hweight_gen to avoid accidental match from
  	 * wrapping.
  	 */
  	iocg->hweight_gen = atomic_read(&ioc->hweight_gen) - 1;
  	list_add(&iocg->active_list, &ioc->active_iocgs);
b0853ab4a   Tejun Heo   blk-iocost: revam...
1261

00410f1b0   Tejun Heo   blk-iocost: renam...
1262
  	propagate_weights(iocg, iocg->weight,
b0853ab4a   Tejun Heo   blk-iocost: revam...
1263
  			  iocg->last_inuse ?: iocg->weight, true, now);
7caa47151   Tejun Heo   blkcg: implement ...
1264
1265
1266
  
  	TRACE_IOCG_PATH(iocg_activate, iocg, now,
  			last_period, cur_period, vtime);
1aa50d020   Tejun Heo   blk-iocost: calcu...
1267
  	iocg->activated_at = now->now;
7caa47151   Tejun Heo   blkcg: implement ...
1268
1269
1270
  
  	if (ioc->running == IOC_IDLE) {
  		ioc->running = IOC_RUNNING;
c7af2a003   Tejun Heo   iocost: reimpleme...
1271
1272
  		ioc->dfgv_period_at = now->now;
  		ioc->dfgv_period_rem = 0;
7caa47151   Tejun Heo   blkcg: implement ...
1273
1274
  		ioc_start_period(ioc, now);
  	}
8b37bc277   Jiufei Xue   iocost: check act...
1275
  succeed_unlock:
7caa47151   Tejun Heo   blkcg: implement ...
1276
1277
1278
1279
1280
1281
1282
  	spin_unlock_irq(&ioc->lock);
  	return true;
  
  fail_unlock:
  	spin_unlock_irq(&ioc->lock);
  	return false;
  }
6ef20f787   Tejun Heo   blk-iocost: move ...
1283
1284
1285
1286
  static bool iocg_kick_delay(struct ioc_gq *iocg, struct ioc_now *now)
  {
  	struct ioc *ioc = iocg->ioc;
  	struct blkcg_gq *blkg = iocg_to_blkg(iocg);
5160a5a53   Tejun Heo   blk-iocost: imple...
1287
1288
  	u64 tdelta, delay, new_delay;
  	s64 vover, vover_pct;
c421a3eb2   Tejun Heo   blk-iocost: revam...
1289
  	u32 hwa;
6ef20f787   Tejun Heo   blk-iocost: move ...
1290
1291
  
  	lockdep_assert_held(&iocg->waitq.lock);
5160a5a53   Tejun Heo   blk-iocost: imple...
1292
1293
1294
1295
1296
1297
1298
1299
  	/* calculate the current delay in effect - 1/2 every second */
  	tdelta = now->now - iocg->delay_at;
  	if (iocg->delay)
  		delay = iocg->delay >> div64_u64(tdelta, USEC_PER_SEC);
  	else
  		delay = 0;
  
  	/* calculate the new delay from the debt amount */
c421a3eb2   Tejun Heo   blk-iocost: revam...
1300
  	current_hweight(iocg, &hwa, NULL);
5160a5a53   Tejun Heo   blk-iocost: imple...
1301
1302
  	vover = atomic64_read(&iocg->vtime) +
  		abs_cost_to_cost(iocg->abs_vdebt, hwa) - now->vnow;
ac33e91e2   Tejun Heo   blk-iocost: imple...
1303
1304
  	vover_pct = div64_s64(100 * vover,
  			      ioc->period_us * ioc->vtime_base_rate);
5160a5a53   Tejun Heo   blk-iocost: imple...
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
  
  	if (vover_pct <= MIN_DELAY_THR_PCT)
  		new_delay = 0;
  	else if (vover_pct >= MAX_DELAY_THR_PCT)
  		new_delay = MAX_DELAY;
  	else
  		new_delay = MIN_DELAY +
  			div_u64((MAX_DELAY - MIN_DELAY) *
  				(vover_pct - MIN_DELAY_THR_PCT),
  				MAX_DELAY_THR_PCT - MIN_DELAY_THR_PCT);
  
  	/* pick the higher one and apply */
  	if (new_delay > delay) {
  		iocg->delay = new_delay;
  		iocg->delay_at = now->now;
  		delay = new_delay;
  	}
6ef20f787   Tejun Heo   blk-iocost: move ...
1322

5160a5a53   Tejun Heo   blk-iocost: imple...
1323
  	if (delay >= MIN_DELAY) {
f0bf84a5d   Tejun Heo   blk-iocost: add t...
1324
1325
  		if (!iocg->indelay_since)
  			iocg->indelay_since = now->now;
5160a5a53   Tejun Heo   blk-iocost: imple...
1326
1327
1328
  		blkcg_set_delay(blkg, delay * NSEC_PER_USEC);
  		return true;
  	} else {
f0bf84a5d   Tejun Heo   blk-iocost: add t...
1329
1330
1331
1332
  		if (iocg->indelay_since) {
  			iocg->local_stat.indelay_us += now->now - iocg->indelay_since;
  			iocg->indelay_since = 0;
  		}
5160a5a53   Tejun Heo   blk-iocost: imple...
1333
  		iocg->delay = 0;
6ef20f787   Tejun Heo   blk-iocost: move ...
1334
1335
1336
  		blkcg_clear_delay(blkg);
  		return false;
  	}
6ef20f787   Tejun Heo   blk-iocost: move ...
1337
  }
c421a3eb2   Tejun Heo   blk-iocost: revam...
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
  static void iocg_incur_debt(struct ioc_gq *iocg, u64 abs_cost,
  			    struct ioc_now *now)
  {
  	struct iocg_pcpu_stat *gcs;
  
  	lockdep_assert_held(&iocg->ioc->lock);
  	lockdep_assert_held(&iocg->waitq.lock);
  	WARN_ON_ONCE(list_empty(&iocg->active_list));
  
  	/*
  	 * Once in debt, debt handling owns inuse. @iocg stays at the minimum
  	 * inuse donating all of it share to others until its debt is paid off.
  	 */
f0bf84a5d   Tejun Heo   blk-iocost: add t...
1351
1352
  	if (!iocg->abs_vdebt && abs_cost) {
  		iocg->indebt_since = now->now;
c421a3eb2   Tejun Heo   blk-iocost: revam...
1353
  		propagate_weights(iocg, iocg->active, 0, false, now);
f0bf84a5d   Tejun Heo   blk-iocost: add t...
1354
  	}
c421a3eb2   Tejun Heo   blk-iocost: revam...
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
  
  	iocg->abs_vdebt += abs_cost;
  
  	gcs = get_cpu_ptr(iocg->pcpu_stat);
  	local64_add(abs_cost, &gcs->abs_vusage);
  	put_cpu_ptr(gcs);
  }
  
  static void iocg_pay_debt(struct ioc_gq *iocg, u64 abs_vpay,
  			  struct ioc_now *now)
  {
  	lockdep_assert_held(&iocg->ioc->lock);
  	lockdep_assert_held(&iocg->waitq.lock);
  
  	/* make sure that nobody messed with @iocg */
  	WARN_ON_ONCE(list_empty(&iocg->active_list));
  	WARN_ON_ONCE(iocg->inuse > 1);
  
  	iocg->abs_vdebt -= min(abs_vpay, iocg->abs_vdebt);
  
  	/* if debt is paid in full, restore inuse */
f0bf84a5d   Tejun Heo   blk-iocost: add t...
1376
1377
1378
  	if (!iocg->abs_vdebt) {
  		iocg->local_stat.indebt_us += now->now - iocg->indebt_since;
  		iocg->indebt_since = 0;
c421a3eb2   Tejun Heo   blk-iocost: revam...
1379
1380
  		propagate_weights(iocg, iocg->active, iocg->last_inuse,
  				  false, now);
f0bf84a5d   Tejun Heo   blk-iocost: add t...
1381
  	}
c421a3eb2   Tejun Heo   blk-iocost: revam...
1382
  }
7caa47151   Tejun Heo   blkcg: implement ...
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
  static int iocg_wake_fn(struct wait_queue_entry *wq_entry, unsigned mode,
  			int flags, void *key)
  {
  	struct iocg_wait *wait = container_of(wq_entry, struct iocg_wait, wait);
  	struct iocg_wake_ctx *ctx = (struct iocg_wake_ctx *)key;
  	u64 cost = abs_cost_to_cost(wait->abs_cost, ctx->hw_inuse);
  
  	ctx->vbudget -= cost;
  
  	if (ctx->vbudget < 0)
  		return -1;
97eb19751   Tejun Heo   blk-iocost: add a...
1394
  	iocg_commit_bio(ctx->iocg, wait->bio, wait->abs_cost, cost);
7caa47151   Tejun Heo   blkcg: implement ...
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
  
  	/*
  	 * autoremove_wake_function() removes the wait entry only when it
  	 * actually changed the task state.  We want the wait always
  	 * removed.  Remove explicitly and use default_wake_function().
  	 */
  	list_del_init(&wq_entry->entry);
  	wait->committed = true;
  
  	default_wake_function(wq_entry, mode, flags, key);
  	return 0;
  }
da437b95d   Tejun Heo   blk-iocost: grab ...
1407
1408
1409
1410
1411
1412
1413
  /*
   * Calculate the accumulated budget, pay debt if @pay_debt and wake up waiters
   * accordingly. When @pay_debt is %true, the caller must be holding ioc->lock in
   * addition to iocg->waitq.lock.
   */
  static void iocg_kick_waitq(struct ioc_gq *iocg, bool pay_debt,
  			    struct ioc_now *now)
7caa47151   Tejun Heo   blkcg: implement ...
1414
1415
1416
  {
  	struct ioc *ioc = iocg->ioc;
  	struct iocg_wake_ctx ctx = { .iocg = iocg };
da437b95d   Tejun Heo   blk-iocost: grab ...
1417
  	u64 vshortage, expires, oexpires;
36a524814   Tejun Heo   blk-iocost: Accou...
1418
  	s64 vbudget;
c421a3eb2   Tejun Heo   blk-iocost: revam...
1419
  	u32 hwa;
7caa47151   Tejun Heo   blkcg: implement ...
1420
1421
  
  	lockdep_assert_held(&iocg->waitq.lock);
c421a3eb2   Tejun Heo   blk-iocost: revam...
1422
  	current_hweight(iocg, &hwa, NULL);
36a524814   Tejun Heo   blk-iocost: Accou...
1423
1424
1425
  	vbudget = now->vnow - atomic64_read(&iocg->vtime);
  
  	/* pay off debt */
da437b95d   Tejun Heo   blk-iocost: grab ...
1426
  	if (pay_debt && iocg->abs_vdebt && vbudget > 0) {
c421a3eb2   Tejun Heo   blk-iocost: revam...
1427
1428
1429
  		u64 abs_vbudget = cost_to_abs_cost(vbudget, hwa);
  		u64 abs_vpay = min_t(u64, abs_vbudget, iocg->abs_vdebt);
  		u64 vpay = abs_cost_to_cost(abs_vpay, hwa);
36a524814   Tejun Heo   blk-iocost: Accou...
1430

da437b95d   Tejun Heo   blk-iocost: grab ...
1431
  		lockdep_assert_held(&ioc->lock);
c421a3eb2   Tejun Heo   blk-iocost: revam...
1432
1433
1434
1435
  		atomic64_add(vpay, &iocg->vtime);
  		atomic64_add(vpay, &iocg->done_vtime);
  		iocg_pay_debt(iocg, abs_vpay, now);
  		vbudget -= vpay;
5160a5a53   Tejun Heo   blk-iocost: imple...
1436
  	}
7b84b49e3   Tejun Heo   blk-iocost: make ...
1437

5160a5a53   Tejun Heo   blk-iocost: imple...
1438
  	if (iocg->abs_vdebt || iocg->delay)
7b84b49e3   Tejun Heo   blk-iocost: make ...
1439
  		iocg_kick_delay(iocg, now);
36a524814   Tejun Heo   blk-iocost: Accou...
1440

7caa47151   Tejun Heo   blkcg: implement ...
1441
  	/*
da437b95d   Tejun Heo   blk-iocost: grab ...
1442
1443
1444
1445
1446
1447
  	 * Debt can still be outstanding if we haven't paid all yet or the
  	 * caller raced and called without @pay_debt. Shouldn't wake up waiters
  	 * under debt. Make sure @vbudget reflects the outstanding amount and is
  	 * not positive.
  	 */
  	if (iocg->abs_vdebt) {
c421a3eb2   Tejun Heo   blk-iocost: revam...
1448
  		s64 vdebt = abs_cost_to_cost(iocg->abs_vdebt, hwa);
da437b95d   Tejun Heo   blk-iocost: grab ...
1449
1450
1451
1452
  		vbudget = min_t(s64, 0, vbudget - vdebt);
  	}
  
  	/*
c421a3eb2   Tejun Heo   blk-iocost: revam...
1453
1454
1455
  	 * Wake up the ones which are due and see how much vtime we'll need for
  	 * the next one. As paying off debt restores hw_inuse, it must be read
  	 * after the above debt payment.
7caa47151   Tejun Heo   blkcg: implement ...
1456
  	 */
da437b95d   Tejun Heo   blk-iocost: grab ...
1457
  	ctx.vbudget = vbudget;
c421a3eb2   Tejun Heo   blk-iocost: revam...
1458
  	current_hweight(iocg, NULL, &ctx.hw_inuse);
7caa47151   Tejun Heo   blkcg: implement ...
1459
  	__wake_up_locked_key(&iocg->waitq, TASK_NORMAL, &ctx);
c421a3eb2   Tejun Heo   blk-iocost: revam...
1460

f0bf84a5d   Tejun Heo   blk-iocost: add t...
1461
1462
1463
1464
1465
  	if (!waitqueue_active(&iocg->waitq)) {
  		if (iocg->wait_since) {
  			iocg->local_stat.wait_us += now->now - iocg->wait_since;
  			iocg->wait_since = 0;
  		}
7caa47151   Tejun Heo   blkcg: implement ...
1466
  		return;
f0bf84a5d   Tejun Heo   blk-iocost: add t...
1467
1468
1469
1470
  	}
  
  	if (!iocg->wait_since)
  		iocg->wait_since = now->now;
7caa47151   Tejun Heo   blkcg: implement ...
1471
1472
  	if (WARN_ON_ONCE(ctx.vbudget >= 0))
  		return;
7ca5b2e60   Tejun Heo   blk-iocost: strea...
1473
  	/* determine next wakeup, add a timer margin to guarantee chunking */
7caa47151   Tejun Heo   blkcg: implement ...
1474
1475
  	vshortage = -ctx.vbudget;
  	expires = now->now_ns +
ac33e91e2   Tejun Heo   blk-iocost: imple...
1476
1477
  		DIV64_U64_ROUND_UP(vshortage, ioc->vtime_base_rate) *
  		NSEC_PER_USEC;
7ca5b2e60   Tejun Heo   blk-iocost: strea...
1478
  	expires += ioc->timer_slack_ns;
7caa47151   Tejun Heo   blkcg: implement ...
1479
1480
1481
1482
  
  	/* if already active and close enough, don't bother */
  	oexpires = ktime_to_ns(hrtimer_get_softexpires(&iocg->waitq_timer));
  	if (hrtimer_is_queued(&iocg->waitq_timer) &&
7ca5b2e60   Tejun Heo   blk-iocost: strea...
1483
  	    abs(oexpires - expires) <= ioc->timer_slack_ns)
7caa47151   Tejun Heo   blkcg: implement ...
1484
1485
1486
  		return;
  
  	hrtimer_start_range_ns(&iocg->waitq_timer, ns_to_ktime(expires),
7ca5b2e60   Tejun Heo   blk-iocost: strea...
1487
  			       ioc->timer_slack_ns, HRTIMER_MODE_ABS);
7caa47151   Tejun Heo   blkcg: implement ...
1488
1489
1490
1491
1492
  }
  
  static enum hrtimer_restart iocg_waitq_timer_fn(struct hrtimer *timer)
  {
  	struct ioc_gq *iocg = container_of(timer, struct ioc_gq, waitq_timer);
da437b95d   Tejun Heo   blk-iocost: grab ...
1493
  	bool pay_debt = READ_ONCE(iocg->abs_vdebt);
7caa47151   Tejun Heo   blkcg: implement ...
1494
1495
1496
1497
  	struct ioc_now now;
  	unsigned long flags;
  
  	ioc_now(iocg->ioc, &now);
da437b95d   Tejun Heo   blk-iocost: grab ...
1498
1499
1500
  	iocg_lock(iocg, pay_debt, &flags);
  	iocg_kick_waitq(iocg, pay_debt, &now);
  	iocg_unlock(iocg, pay_debt, &flags);
7caa47151   Tejun Heo   blkcg: implement ...
1501
1502
1503
  
  	return HRTIMER_NORESTART;
  }
7caa47151   Tejun Heo   blkcg: implement ...
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
  static void ioc_lat_stat(struct ioc *ioc, u32 *missed_ppm_ar, u32 *rq_wait_pct_p)
  {
  	u32 nr_met[2] = { };
  	u32 nr_missed[2] = { };
  	u64 rq_wait_ns = 0;
  	int cpu, rw;
  
  	for_each_online_cpu(cpu) {
  		struct ioc_pcpu_stat *stat = per_cpu_ptr(ioc->pcpu_stat, cpu);
  		u64 this_rq_wait_ns;
  
  		for (rw = READ; rw <= WRITE; rw++) {
5e124f743   Tejun Heo   blk-iocost: use l...
1516
1517
  			u32 this_met = local_read(&stat->missed[rw].nr_met);
  			u32 this_missed = local_read(&stat->missed[rw].nr_missed);
7caa47151   Tejun Heo   blkcg: implement ...
1518
1519
1520
1521
1522
1523
  
  			nr_met[rw] += this_met - stat->missed[rw].last_met;
  			nr_missed[rw] += this_missed - stat->missed[rw].last_missed;
  			stat->missed[rw].last_met = this_met;
  			stat->missed[rw].last_missed = this_missed;
  		}
5e124f743   Tejun Heo   blk-iocost: use l...
1524
  		this_rq_wait_ns = local64_read(&stat->rq_wait_ns);
7caa47151   Tejun Heo   blkcg: implement ...
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
  		rq_wait_ns += this_rq_wait_ns - stat->last_rq_wait_ns;
  		stat->last_rq_wait_ns = this_rq_wait_ns;
  	}
  
  	for (rw = READ; rw <= WRITE; rw++) {
  		if (nr_met[rw] + nr_missed[rw])
  			missed_ppm_ar[rw] =
  				DIV64_U64_ROUND_UP((u64)nr_missed[rw] * MILLION,
  						   nr_met[rw] + nr_missed[rw]);
  		else
  			missed_ppm_ar[rw] = 0;
  	}
  
  	*rq_wait_pct_p = div64_u64(rq_wait_ns * 100,
  				   ioc->period_us * NSEC_PER_USEC);
  }
  
  /* was iocg idle this period? */
  static bool iocg_is_idle(struct ioc_gq *iocg)
  {
  	struct ioc *ioc = iocg->ioc;
  
  	/* did something get issued this period? */
  	if (atomic64_read(&iocg->active_period) ==
  	    atomic64_read(&ioc->cur_period))
  		return false;
  
  	/* is something in flight? */
dcd6589b1   Tejun Heo   blk-iocost: fix i...
1553
  	if (atomic64_read(&iocg->done_vtime) != atomic64_read(&iocg->vtime))
7caa47151   Tejun Heo   blkcg: implement ...
1554
1555
1556
1557
  		return false;
  
  	return true;
  }
97eb19751   Tejun Heo   blk-iocost: add a...
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
  /*
   * Call this function on the target leaf @iocg's to build pre-order traversal
   * list of all the ancestors in @inner_walk. The inner nodes are linked through
   * ->walk_list and the caller is responsible for dissolving the list after use.
   */
  static void iocg_build_inner_walk(struct ioc_gq *iocg,
  				  struct list_head *inner_walk)
  {
  	int lvl;
  
  	WARN_ON_ONCE(!list_empty(&iocg->walk_list));
  
  	/* find the first ancestor which hasn't been visited yet */
  	for (lvl = iocg->level - 1; lvl >= 0; lvl--) {
  		if (!list_empty(&iocg->ancestors[lvl]->walk_list))
  			break;
  	}
  
  	/* walk down and visit the inner nodes to get pre-order traversal */
  	while (++lvl <= iocg->level - 1) {
  		struct ioc_gq *inner = iocg->ancestors[lvl];
  
  		/* record traversal order */
  		list_add_tail(&inner->walk_list, inner_walk);
  	}
  }
  
  /* collect per-cpu counters and propagate the deltas to the parent */
  static void iocg_flush_stat_one(struct ioc_gq *iocg, struct ioc_now *now)
  {
ac33e91e2   Tejun Heo   blk-iocost: imple...
1588
  	struct ioc *ioc = iocg->ioc;
97eb19751   Tejun Heo   blk-iocost: add a...
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
  	struct iocg_stat new_stat;
  	u64 abs_vusage = 0;
  	u64 vusage_delta;
  	int cpu;
  
  	lockdep_assert_held(&iocg->ioc->lock);
  
  	/* collect per-cpu counters */
  	for_each_possible_cpu(cpu) {
  		abs_vusage += local64_read(
  				per_cpu_ptr(&iocg->pcpu_stat->abs_vusage, cpu));
  	}
  	vusage_delta = abs_vusage - iocg->last_stat_abs_vusage;
  	iocg->last_stat_abs_vusage = abs_vusage;
ac33e91e2   Tejun Heo   blk-iocost: imple...
1603
  	iocg->usage_delta_us = div64_u64(vusage_delta, ioc->vtime_base_rate);
1aa50d020   Tejun Heo   blk-iocost: calcu...
1604
  	iocg->local_stat.usage_us += iocg->usage_delta_us;
97eb19751   Tejun Heo   blk-iocost: add a...
1605

f0bf84a5d   Tejun Heo   blk-iocost: add t...
1606
  	/* propagate upwards */
97eb19751   Tejun Heo   blk-iocost: add a...
1607
1608
  	new_stat.usage_us =
  		iocg->local_stat.usage_us + iocg->desc_stat.usage_us;
f0bf84a5d   Tejun Heo   blk-iocost: add t...
1609
1610
1611
1612
1613
1614
  	new_stat.wait_us =
  		iocg->local_stat.wait_us + iocg->desc_stat.wait_us;
  	new_stat.indebt_us =
  		iocg->local_stat.indebt_us + iocg->desc_stat.indebt_us;
  	new_stat.indelay_us =
  		iocg->local_stat.indelay_us + iocg->desc_stat.indelay_us;
97eb19751   Tejun Heo   blk-iocost: add a...
1615
1616
1617
1618
1619
1620
1621
1622
  
  	/* propagate the deltas to the parent */
  	if (iocg->level > 0) {
  		struct iocg_stat *parent_stat =
  			&iocg->ancestors[iocg->level - 1]->desc_stat;
  
  		parent_stat->usage_us +=
  			new_stat.usage_us - iocg->last_stat.usage_us;
f0bf84a5d   Tejun Heo   blk-iocost: add t...
1623
1624
1625
1626
1627
1628
  		parent_stat->wait_us +=
  			new_stat.wait_us - iocg->last_stat.wait_us;
  		parent_stat->indebt_us +=
  			new_stat.indebt_us - iocg->last_stat.indebt_us;
  		parent_stat->indelay_us +=
  			new_stat.indelay_us - iocg->last_stat.indelay_us;
97eb19751   Tejun Heo   blk-iocost: add a...
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
  	}
  
  	iocg->last_stat = new_stat;
  }
  
  /* get stat counters ready for reading on all active iocgs */
  static void iocg_flush_stat(struct list_head *target_iocgs, struct ioc_now *now)
  {
  	LIST_HEAD(inner_walk);
  	struct ioc_gq *iocg, *tiocg;
  
  	/* flush leaves and build inner node walk list */
  	list_for_each_entry(iocg, target_iocgs, active_list) {
  		iocg_flush_stat_one(iocg, now);
  		iocg_build_inner_walk(iocg, &inner_walk);
  	}
  
  	/* keep flushing upwards by walking the inner list backwards */
  	list_for_each_entry_safe_reverse(iocg, tiocg, &inner_walk, walk_list) {
  		iocg_flush_stat_one(iocg, now);
  		list_del_init(&iocg->walk_list);
  	}
  }
93f7d2db8   Tejun Heo   blk-iocost: restr...
1652
1653
1654
1655
1656
  /*
   * Determine what @iocg's hweight_inuse should be after donating unused
   * capacity. @hwm is the upper bound and used to signal no donation. This
   * function also throws away @iocg's excess budget.
   */
ac33e91e2   Tejun Heo   blk-iocost: imple...
1657
1658
  static u32 hweight_after_donation(struct ioc_gq *iocg, u32 old_hwi, u32 hwm,
  				  u32 usage, struct ioc_now *now)
7caa47151   Tejun Heo   blkcg: implement ...
1659
  {
93f7d2db8   Tejun Heo   blk-iocost: restr...
1660
1661
  	struct ioc *ioc = iocg->ioc;
  	u64 vtime = atomic64_read(&iocg->vtime);
f1de2439e   Tejun Heo   blk-iocost: revam...
1662
  	s64 excess, delta, target, new_hwi;
93f7d2db8   Tejun Heo   blk-iocost: restr...
1663

c421a3eb2   Tejun Heo   blk-iocost: revam...
1664
1665
1666
  	/* debt handling owns inuse for debtors */
  	if (iocg->abs_vdebt)
  		return 1;
93f7d2db8   Tejun Heo   blk-iocost: restr...
1667
1668
1669
1670
  	/* see whether minimum margin requirement is met */
  	if (waitqueue_active(&iocg->waitq) ||
  	    time_after64(vtime, now->vnow - ioc->margins.min))
  		return hwm;
ac33e91e2   Tejun Heo   blk-iocost: imple...
1671
1672
  	/* throw away excess above target */
  	excess = now->vnow - vtime - ioc->margins.target;
93f7d2db8   Tejun Heo   blk-iocost: restr...
1673
1674
1675
1676
  	if (excess > 0) {
  		atomic64_add(excess, &iocg->vtime);
  		atomic64_add(excess, &iocg->done_vtime);
  		vtime += excess;
ac33e91e2   Tejun Heo   blk-iocost: imple...
1677
  		ioc->vtime_err -= div64_u64(excess * old_hwi, WEIGHT_ONE);
93f7d2db8   Tejun Heo   blk-iocost: restr...
1678
  	}
f1de2439e   Tejun Heo   blk-iocost: revam...
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
  	/*
  	 * Let's say the distance between iocg's and device's vtimes as a
  	 * fraction of period duration is delta. Assuming that the iocg will
  	 * consume the usage determined above, we want to determine new_hwi so
  	 * that delta equals MARGIN_TARGET at the end of the next period.
  	 *
  	 * We need to execute usage worth of IOs while spending the sum of the
  	 * new budget (1 - MARGIN_TARGET) and the leftover from the last period
  	 * (delta):
  	 *
  	 *   usage = (1 - MARGIN_TARGET + delta) * new_hwi
  	 *
  	 * Therefore, the new_hwi is:
  	 *
  	 *   new_hwi = usage / (1 - MARGIN_TARGET + delta)
  	 */
  	delta = div64_s64(WEIGHT_ONE * (now->vnow - vtime),
  			  now->vnow - ioc->period_at_vtime);
  	target = WEIGHT_ONE * MARGIN_TARGET_PCT / 100;
  	new_hwi = div64_s64(WEIGHT_ONE * usage, WEIGHT_ONE - target + delta);
7caa47151   Tejun Heo   blkcg: implement ...
1699

f1de2439e   Tejun Heo   blk-iocost: revam...
1700
  	return clamp_t(s64, new_hwi, 1, hwm);
7caa47151   Tejun Heo   blkcg: implement ...
1701
  }
e08d02aa5   Tejun Heo   blk-iocost: imple...
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
  /*
   * For work-conservation, an iocg which isn't using all of its share should
   * donate the leftover to other iocgs. There are two ways to achieve this - 1.
   * bumping up vrate accordingly 2. lowering the donating iocg's inuse weight.
   *
   * #1 is mathematically simpler but has the drawback of requiring synchronous
   * global hweight_inuse updates when idle iocg's get activated or inuse weights
   * change due to donation snapbacks as it has the possibility of grossly
   * overshooting what's allowed by the model and vrate.
   *
   * #2 is inherently safe with local operations. The donating iocg can easily
   * snap back to higher weights when needed without worrying about impacts on
   * other nodes as the impacts will be inherently correct. This also makes idle
   * iocg activations safe. The only effect activations have is decreasing
   * hweight_inuse of others, the right solution to which is for those iocgs to
   * snap back to higher weights.
   *
   * So, we go with #2. The challenge is calculating how each donating iocg's
   * inuse should be adjusted to achieve the target donation amounts. This is done
   * using Andy's method described in the following pdf.
   *
   *   https://drive.google.com/file/d/1PsJwxPFtjUnwOY1QJ5AeICCcsL7BM3bo
   *
   * Given the weights and target after-donation hweight_inuse values, Andy's
   * method determines how the proportional distribution should look like at each
   * sibling level to maintain the relative relationship between all non-donating
   * pairs. To roughly summarize, it divides the tree into donating and
   * non-donating parts, calculates global donation rate which is used to
   * determine the target hweight_inuse for each node, and then derives per-level
   * proportions.
   *
   * The following pdf shows that global distribution calculated this way can be
   * achieved by scaling inuse weights of donating leaves and propagating the
   * adjustments upwards proportionally.
   *
   *   https://drive.google.com/file/d/1vONz1-fzVO7oY5DXXsLjSxEtYYQbOvsE
   *
   * Combining the above two, we can determine how each leaf iocg's inuse should
   * be adjusted to achieve the target donation.
   *
   *   https://drive.google.com/file/d/1WcrltBOSPN0qXVdBgnKm4mdp9FhuEFQN
   *
   * The inline comments use symbols from the last pdf.
   *
   *   b is the sum of the absolute budgets in the subtree. 1 for the root node.
   *   f is the sum of the absolute budgets of non-donating nodes in the subtree.
   *   t is the sum of the absolute budgets of donating nodes in the subtree.
   *   w is the weight of the node. w = w_f + w_t
   *   w_f is the non-donating portion of w. w_f = w * f / b
   *   w_b is the donating portion of w. w_t = w * t / b
   *   s is the sum of all sibling weights. s = Sum(w) for siblings
   *   s_f and s_t are the non-donating and donating portions of s.
   *
   * Subscript p denotes the parent's counterpart and ' the adjusted value - e.g.
   * w_pt is the donating portion of the parent's weight and w'_pt the same value
   * after adjustments. Subscript r denotes the root node's values.
   */
93f7d2db8   Tejun Heo   blk-iocost: restr...
1759
1760
  static void transfer_surpluses(struct list_head *surpluses, struct ioc_now *now)
  {
e08d02aa5   Tejun Heo   blk-iocost: imple...
1761
1762
1763
1764
  	LIST_HEAD(over_hwa);
  	LIST_HEAD(inner_walk);
  	struct ioc_gq *iocg, *tiocg, *root_iocg;
  	u32 after_sum, over_sum, over_target, gamma;
93f7d2db8   Tejun Heo   blk-iocost: restr...
1765

e08d02aa5   Tejun Heo   blk-iocost: imple...
1766
1767
1768
1769
1770
1771
1772
1773
1774
  	/*
  	 * It's pretty unlikely but possible for the total sum of
  	 * hweight_after_donation's to be higher than WEIGHT_ONE, which will
  	 * confuse the following calculations. If such condition is detected,
  	 * scale down everyone over its full share equally to keep the sum below
  	 * WEIGHT_ONE.
  	 */
  	after_sum = 0;
  	over_sum = 0;
93f7d2db8   Tejun Heo   blk-iocost: restr...
1775
  	list_for_each_entry(iocg, surpluses, surplus_list) {
e08d02aa5   Tejun Heo   blk-iocost: imple...
1776
  		u32 hwa;
93f7d2db8   Tejun Heo   blk-iocost: restr...
1777

e08d02aa5   Tejun Heo   blk-iocost: imple...
1778
1779
  		current_hweight(iocg, &hwa, NULL);
  		after_sum += iocg->hweight_after_donation;
93f7d2db8   Tejun Heo   blk-iocost: restr...
1780

e08d02aa5   Tejun Heo   blk-iocost: imple...
1781
1782
1783
1784
  		if (iocg->hweight_after_donation > hwa) {
  			over_sum += iocg->hweight_after_donation;
  			list_add(&iocg->walk_list, &over_hwa);
  		}
93f7d2db8   Tejun Heo   blk-iocost: restr...
1785
  	}
e08d02aa5   Tejun Heo   blk-iocost: imple...
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
  
  	if (after_sum >= WEIGHT_ONE) {
  		/*
  		 * The delta should be deducted from the over_sum, calculate
  		 * target over_sum value.
  		 */
  		u32 over_delta = after_sum - (WEIGHT_ONE - 1);
  		WARN_ON_ONCE(over_sum <= over_delta);
  		over_target = over_sum - over_delta;
  	} else {
  		over_target = 0;
  	}
  
  	list_for_each_entry_safe(iocg, tiocg, &over_hwa, walk_list) {
  		if (over_target)
  			iocg->hweight_after_donation =
  				div_u64((u64)iocg->hweight_after_donation *
  					over_target, over_sum);
  		list_del_init(&iocg->walk_list);
  	}
  
  	/*
  	 * Build pre-order inner node walk list and prepare for donation
  	 * adjustment calculations.
  	 */
  	list_for_each_entry(iocg, surpluses, surplus_list) {
  		iocg_build_inner_walk(iocg, &inner_walk);
  	}
  
  	root_iocg = list_first_entry(&inner_walk, struct ioc_gq, walk_list);
  	WARN_ON_ONCE(root_iocg->level > 0);
  
  	list_for_each_entry(iocg, &inner_walk, walk_list) {
  		iocg->child_adjusted_sum = 0;
  		iocg->hweight_donating = 0;
  		iocg->hweight_after_donation = 0;
  	}
  
  	/*
  	 * Propagate the donating budget (b_t) and after donation budget (b'_t)
  	 * up the hierarchy.
  	 */
  	list_for_each_entry(iocg, surpluses, surplus_list) {
  		struct ioc_gq *parent = iocg->ancestors[iocg->level - 1];
  
  		parent->hweight_donating += iocg->hweight_donating;
  		parent->hweight_after_donation += iocg->hweight_after_donation;
  	}
  
  	list_for_each_entry_reverse(iocg, &inner_walk, walk_list) {
  		if (iocg->level > 0) {
  			struct ioc_gq *parent = iocg->ancestors[iocg->level - 1];
  
  			parent->hweight_donating += iocg->hweight_donating;
  			parent->hweight_after_donation += iocg->hweight_after_donation;
  		}
  	}
  
  	/*
  	 * Calculate inner hwa's (b) and make sure the donation values are
  	 * within the accepted ranges as we're doing low res calculations with
  	 * roundups.
  	 */
  	list_for_each_entry(iocg, &inner_walk, walk_list) {
  		if (iocg->level) {
  			struct ioc_gq *parent = iocg->ancestors[iocg->level - 1];
  
  			iocg->hweight_active = DIV64_U64_ROUND_UP(
  				(u64)parent->hweight_active * iocg->active,
  				parent->child_active_sum);
  
  		}
  
  		iocg->hweight_donating = min(iocg->hweight_donating,
  					     iocg->hweight_active);
  		iocg->hweight_after_donation = min(iocg->hweight_after_donation,
  						   iocg->hweight_donating - 1);
  		if (WARN_ON_ONCE(iocg->hweight_active <= 1 ||
  				 iocg->hweight_donating <= 1 ||
  				 iocg->hweight_after_donation == 0)) {
  			pr_warn("iocg: invalid donation weights in ");
  			pr_cont_cgroup_path(iocg_to_blkg(iocg)->blkcg->css.cgroup);
  			pr_cont(": active=%u donating=%u after=%u
  ",
  				iocg->hweight_active, iocg->hweight_donating,
  				iocg->hweight_after_donation);
  		}
  	}
  
  	/*
  	 * Calculate the global donation rate (gamma) - the rate to adjust
769b628de   Tejun Heo   blk-iocost: fix d...
1877
1878
1879
1880
1881
1882
1883
1884
1885
  	 * non-donating budgets by.
  	 *
  	 * No need to use 64bit multiplication here as the first operand is
  	 * guaranteed to be smaller than WEIGHT_ONE (1<<16).
  	 *
  	 * We know that there are beneficiary nodes and the sum of the donating
  	 * hweights can't be whole; however, due to the round-ups during hweight
  	 * calculations, root_iocg->hweight_donating might still end up equal to
  	 * or greater than whole. Limit the range when calculating the divider.
e08d02aa5   Tejun Heo   blk-iocost: imple...
1886
1887
1888
1889
1890
  	 *
  	 * gamma = (1 - t_r') / (1 - t_r)
  	 */
  	gamma = DIV_ROUND_UP(
  		(WEIGHT_ONE - root_iocg->hweight_after_donation) * WEIGHT_ONE,
769b628de   Tejun Heo   blk-iocost: fix d...
1891
  		WEIGHT_ONE - min_t(u32, root_iocg->hweight_donating, WEIGHT_ONE - 1));
e08d02aa5   Tejun Heo   blk-iocost: imple...
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
  
  	/*
  	 * Calculate adjusted hwi, child_adjusted_sum and inuse for the inner
  	 * nodes.
  	 */
  	list_for_each_entry(iocg, &inner_walk, walk_list) {
  		struct ioc_gq *parent;
  		u32 inuse, wpt, wptp;
  		u64 st, sf;
  
  		if (iocg->level == 0) {
  			/* adjusted weight sum for 1st level: s' = s * b_pf / b'_pf */
  			iocg->child_adjusted_sum = DIV64_U64_ROUND_UP(
  				iocg->child_active_sum * (WEIGHT_ONE - iocg->hweight_donating),
  				WEIGHT_ONE - iocg->hweight_after_donation);
  			continue;
  		}
  
  		parent = iocg->ancestors[iocg->level - 1];
  
  		/* b' = gamma * b_f + b_t' */
  		iocg->hweight_inuse = DIV64_U64_ROUND_UP(
  			(u64)gamma * (iocg->hweight_active - iocg->hweight_donating),
  			WEIGHT_ONE) + iocg->hweight_after_donation;
  
  		/* w' = s' * b' / b'_p */
  		inuse = DIV64_U64_ROUND_UP(
  			(u64)parent->child_adjusted_sum * iocg->hweight_inuse,
  			parent->hweight_inuse);
  
  		/* adjusted weight sum for children: s' = s_f + s_t * w'_pt / w_pt */
  		st = DIV64_U64_ROUND_UP(
  			iocg->child_active_sum * iocg->hweight_donating,
  			iocg->hweight_active);
  		sf = iocg->child_active_sum - st;
  		wpt = DIV64_U64_ROUND_UP(
  			(u64)iocg->active * iocg->hweight_donating,
  			iocg->hweight_active);
  		wptp = DIV64_U64_ROUND_UP(
  			(u64)inuse * iocg->hweight_after_donation,
  			iocg->hweight_inuse);
  
  		iocg->child_adjusted_sum = sf + DIV64_U64_ROUND_UP(st * wptp, wpt);
  	}
  
  	/*
  	 * All inner nodes now have ->hweight_inuse and ->child_adjusted_sum and
  	 * we can finally determine leaf adjustments.
  	 */
  	list_for_each_entry(iocg, surpluses, surplus_list) {
  		struct ioc_gq *parent = iocg->ancestors[iocg->level - 1];
  		u32 inuse;
c421a3eb2   Tejun Heo   blk-iocost: revam...
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
  		/*
  		 * In-debt iocgs participated in the donation calculation with
  		 * the minimum target hweight_inuse. Configuring inuse
  		 * accordingly would work fine but debt handling expects
  		 * @iocg->inuse stay at the minimum and we don't wanna
  		 * interfere.
  		 */
  		if (iocg->abs_vdebt) {
  			WARN_ON_ONCE(iocg->inuse > 1);
  			continue;
  		}
e08d02aa5   Tejun Heo   blk-iocost: imple...
1955
1956
1957
1958
  		/* w' = s' * b' / b'_p, note that b' == b'_t for donating leaves */
  		inuse = DIV64_U64_ROUND_UP(
  			parent->child_adjusted_sum * iocg->hweight_after_donation,
  			parent->hweight_inuse);
046037551   Tejun Heo   blk-iocost: resto...
1959
1960
1961
1962
1963
  
  		TRACE_IOCG_PATH(inuse_transfer, iocg, now,
  				iocg->inuse, inuse,
  				iocg->hweight_inuse,
  				iocg->hweight_after_donation);
b0853ab4a   Tejun Heo   blk-iocost: revam...
1964
  		__propagate_weights(iocg, iocg->active, inuse, true, now);
e08d02aa5   Tejun Heo   blk-iocost: imple...
1965
1966
1967
1968
1969
  	}
  
  	/* walk list should be dissolved after use */
  	list_for_each_entry_safe(iocg, tiocg, &inner_walk, walk_list)
  		list_del_init(&iocg->walk_list);
93f7d2db8   Tejun Heo   blk-iocost: restr...
1970
  }
ab8df828b   Tejun Heo   iocost: factor ou...
1971
1972
1973
1974
1975
1976
1977
1978
  /*
   * A low weight iocg can amass a large amount of debt, for example, when
   * anonymous memory gets reclaimed aggressively. If the system has a lot of
   * memory paired with a slow IO device, the debt can span multiple seconds or
   * more. If there are no other subsequent IO issuers, the in-debt iocg may end
   * up blocked paying its debt while the IO device is idle.
   *
   * The following protects against such cases. If the device has been
d95178410   Tejun Heo   iocost: recalcula...
1979
1980
   * sufficiently idle for a while, the debts are halved and delays are
   * recalculated.
ab8df828b   Tejun Heo   iocost: factor ou...
1981
1982
   */
  static void ioc_forgive_debts(struct ioc *ioc, u64 usage_us_sum, int nr_debtors,
33a1fe6d8   Tejun Heo   iocost: replace n...
1983
  			      struct ioc_now *now)
ab8df828b   Tejun Heo   iocost: factor ou...
1984
  {
c7af2a003   Tejun Heo   iocost: reimpleme...
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
  	struct ioc_gq *iocg;
  	u64 dur, usage_pct, nr_cycles;
  
  	/* if no debtor, reset the cycle */
  	if (!nr_debtors) {
  		ioc->dfgv_period_at = now->now;
  		ioc->dfgv_period_rem = 0;
  		ioc->dfgv_usage_us_sum = 0;
  		return;
  	}
  
  	/*
  	 * Debtors can pass through a lot of writes choking the device and we
  	 * don't want to be forgiving debts while the device is struggling from
  	 * write bursts. If we're missing latency targets, consider the device
  	 * fully utilized.
  	 */
  	if (ioc->busy_level > 0)
  		usage_us_sum = max_t(u64, usage_us_sum, ioc->period_us);
  
  	ioc->dfgv_usage_us_sum += usage_us_sum;
  	if (time_before64(now->now, ioc->dfgv_period_at + DFGV_PERIOD))
  		return;
  
  	/*
  	 * At least DFGV_PERIOD has passed since the last period. Calculate the
  	 * average usage and reset the period counters.
  	 */
  	dur = now->now - ioc->dfgv_period_at;
  	usage_pct = div64_u64(100 * ioc->dfgv_usage_us_sum, dur);
  
  	ioc->dfgv_period_at = now->now;
  	ioc->dfgv_usage_us_sum = 0;
  
  	/* if was too busy, reset everything */
  	if (usage_pct > DFGV_USAGE_PCT) {
  		ioc->dfgv_period_rem = 0;
  		return;
  	}
  
  	/*
  	 * Usage is lower than threshold. Let's forgive some debts. Debt
  	 * forgiveness runs off of the usual ioc timer but its period usually
  	 * doesn't match ioc's. Compensate the difference by performing the
  	 * reduction as many times as would fit in the duration since the last
  	 * run and carrying over the left-over duration in @ioc->dfgv_period_rem
  	 * - if ioc period is 75% of DFGV_PERIOD, one out of three consecutive
  	 * reductions is doubled.
  	 */
  	nr_cycles = dur + ioc->dfgv_period_rem;
  	ioc->dfgv_period_rem = do_div(nr_cycles, DFGV_PERIOD);
  
  	list_for_each_entry(iocg, &ioc->active_iocgs, active_list) {
c5a6561b8   Tejun Heo   iocost: add iocg_...
2038
  		u64 __maybe_unused old_debt, __maybe_unused old_delay;
bec02dbba   Tejun Heo   iocost: consider ...
2039
  		if (!iocg->abs_vdebt && !iocg->delay)
c7af2a003   Tejun Heo   iocost: reimpleme...
2040
  			continue;
c5a6561b8   Tejun Heo   iocost: add iocg_...
2041

c7af2a003   Tejun Heo   iocost: reimpleme...
2042
  		spin_lock(&iocg->waitq.lock);
c5a6561b8   Tejun Heo   iocost: add iocg_...
2043
2044
2045
  
  		old_debt = iocg->abs_vdebt;
  		old_delay = iocg->delay;
bec02dbba   Tejun Heo   iocost: consider ...
2046
2047
2048
2049
  		if (iocg->abs_vdebt)
  			iocg->abs_vdebt = iocg->abs_vdebt >> nr_cycles ?: 1;
  		if (iocg->delay)
  			iocg->delay = iocg->delay >> nr_cycles ?: 1;
c7af2a003   Tejun Heo   iocost: reimpleme...
2050
  		iocg_kick_waitq(iocg, true, now);
c5a6561b8   Tejun Heo   iocost: add iocg_...
2051
2052
2053
2054
  
  		TRACE_IOCG_PATH(iocg_forgive_debt, iocg, now, usage_pct,
  				old_debt, iocg->abs_vdebt,
  				old_delay, iocg->delay);
c7af2a003   Tejun Heo   iocost: reimpleme...
2055
  		spin_unlock(&iocg->waitq.lock);
ab8df828b   Tejun Heo   iocost: factor ou...
2056
2057
  	}
  }
2474787a7   Baolin Wang   blk-iocost: Facto...
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
  /*
   * Check the active iocgs' state to avoid oversleeping and deactive
   * idle iocgs.
   *
   * Since waiters determine the sleep durations based on the vrate
   * they saw at the time of sleep, if vrate has increased, some
   * waiters could be sleeping for too long. Wake up tardy waiters
   * which should have woken up in the last period and expire idle
   * iocgs.
   */
  static int ioc_check_iocgs(struct ioc *ioc, struct ioc_now *now)
7caa47151   Tejun Heo   blkcg: implement ...
2069
  {
2474787a7   Baolin Wang   blk-iocost: Facto...
2070
  	int nr_debtors = 0;
7caa47151   Tejun Heo   blkcg: implement ...
2071
  	struct ioc_gq *iocg, *tiocg;
7caa47151   Tejun Heo   blkcg: implement ...
2072

7caa47151   Tejun Heo   blkcg: implement ...
2073
  	list_for_each_entry_safe(iocg, tiocg, &ioc->active_iocgs, active_list) {
d9012a59d   Chengming Zhou   iocost: Fix check...
2074
  		if (!waitqueue_active(&iocg->waitq) && !iocg->abs_vdebt &&
5160a5a53   Tejun Heo   blk-iocost: imple...
2075
  		    !iocg->delay && !iocg_is_idle(iocg))
7caa47151   Tejun Heo   blkcg: implement ...
2076
2077
2078
  			continue;
  
  		spin_lock(&iocg->waitq.lock);
f0bf84a5d   Tejun Heo   blk-iocost: add t...
2079
2080
  		/* flush wait and indebt stat deltas */
  		if (iocg->wait_since) {
2474787a7   Baolin Wang   blk-iocost: Facto...
2081
2082
  			iocg->local_stat.wait_us += now->now - iocg->wait_since;
  			iocg->wait_since = now->now;
f0bf84a5d   Tejun Heo   blk-iocost: add t...
2083
2084
2085
  		}
  		if (iocg->indebt_since) {
  			iocg->local_stat.indebt_us +=
2474787a7   Baolin Wang   blk-iocost: Facto...
2086
2087
  				now->now - iocg->indebt_since;
  			iocg->indebt_since = now->now;
f0bf84a5d   Tejun Heo   blk-iocost: add t...
2088
2089
2090
  		}
  		if (iocg->indelay_since) {
  			iocg->local_stat.indelay_us +=
2474787a7   Baolin Wang   blk-iocost: Facto...
2091
2092
  				now->now - iocg->indelay_since;
  			iocg->indelay_since = now->now;
f0bf84a5d   Tejun Heo   blk-iocost: add t...
2093
  		}
5160a5a53   Tejun Heo   blk-iocost: imple...
2094
2095
  		if (waitqueue_active(&iocg->waitq) || iocg->abs_vdebt ||
  		    iocg->delay) {
7caa47151   Tejun Heo   blkcg: implement ...
2096
  			/* might be oversleeping vtime / hweight changes, kick */
2474787a7   Baolin Wang   blk-iocost: Facto...
2097
  			iocg_kick_waitq(iocg, true, now);
bec02dbba   Tejun Heo   iocost: consider ...
2098
  			if (iocg->abs_vdebt || iocg->delay)
dda1315f1   Tejun Heo   blk-iocost: halve...
2099
  				nr_debtors++;
7caa47151   Tejun Heo   blkcg: implement ...
2100
2101
  		} else if (iocg_is_idle(iocg)) {
  			/* no waiter and idle, deactivate */
ac33e91e2   Tejun Heo   blk-iocost: imple...
2102
2103
2104
2105
2106
2107
2108
2109
2110
  			u64 vtime = atomic64_read(&iocg->vtime);
  			s64 excess;
  
  			/*
  			 * @iocg has been inactive for a full duration and will
  			 * have a high budget. Account anything above target as
  			 * error and throw away. On reactivation, it'll start
  			 * with the target budget.
  			 */
2474787a7   Baolin Wang   blk-iocost: Facto...
2111
  			excess = now->vnow - vtime - ioc->margins.target;
ac33e91e2   Tejun Heo   blk-iocost: imple...
2112
2113
2114
2115
2116
2117
2118
  			if (excess > 0) {
  				u32 old_hwi;
  
  				current_hweight(iocg, NULL, &old_hwi);
  				ioc->vtime_err -= div64_u64(excess * old_hwi,
  							    WEIGHT_ONE);
  			}
76efc1c77   Baolin Wang   blk-iocost: Add i...
2119
2120
2121
  			TRACE_IOCG_PATH(iocg_idle, iocg, now,
  					atomic64_read(&iocg->active_period),
  					atomic64_read(&ioc->cur_period), vtime);
2474787a7   Baolin Wang   blk-iocost: Facto...
2122
  			__propagate_weights(iocg, 0, 0, false, now);
7caa47151   Tejun Heo   blkcg: implement ...
2123
2124
2125
2126
2127
  			list_del_init(&iocg->active_list);
  		}
  
  		spin_unlock(&iocg->waitq.lock);
  	}
2474787a7   Baolin Wang   blk-iocost: Facto...
2128

00410f1b0   Tejun Heo   blk-iocost: renam...
2129
  	commit_weights(ioc);
2474787a7   Baolin Wang   blk-iocost: Facto...
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
  	return nr_debtors;
  }
  
  static void ioc_timer_fn(struct timer_list *timer)
  {
  	struct ioc *ioc = container_of(timer, struct ioc, timer);
  	struct ioc_gq *iocg, *tiocg;
  	struct ioc_now now;
  	LIST_HEAD(surpluses);
  	int nr_debtors, nr_shortages = 0, nr_lagging = 0;
  	u64 usage_us_sum = 0;
  	u32 ppm_rthr = MILLION - ioc->params.qos[QOS_RPPM];
  	u32 ppm_wthr = MILLION - ioc->params.qos[QOS_WPPM];
  	u32 missed_ppm[2], rq_wait_pct;
  	u64 period_vtime;
  	int prev_busy_level;
  
  	/* how were the latencies during the period? */
  	ioc_lat_stat(ioc, missed_ppm, &rq_wait_pct);
  
  	/* take care of active iocgs */
  	spin_lock_irq(&ioc->lock);
  
  	ioc_now(ioc, &now);
  
  	period_vtime = now.vnow - ioc->period_at_vtime;
  	if (WARN_ON_ONCE(!period_vtime)) {
  		spin_unlock_irq(&ioc->lock);
  		return;
  	}
  
  	nr_debtors = ioc_check_iocgs(ioc, &now);
7caa47151   Tejun Heo   blkcg: implement ...
2162

f0bf84a5d   Tejun Heo   blk-iocost: add t...
2163
2164
2165
2166
2167
  	/*
  	 * Wait and indebt stat are flushed above and the donation calculation
  	 * below needs updated usage stat. Let's bring stat up-to-date.
  	 */
  	iocg_flush_stat(&ioc->active_iocgs, &now);
f1de2439e   Tejun Heo   blk-iocost: revam...
2168
  	/* calc usage and see whether some weights need to be moved around */
7caa47151   Tejun Heo   blkcg: implement ...
2169
  	list_for_each_entry(iocg, &ioc->active_iocgs, active_list) {
c09245f61   Baolin Wang   blk-iocost: Move ...
2170
2171
  		u64 vdone, vtime, usage_us;
  		u32 hw_active, hw_inuse;
7caa47151   Tejun Heo   blkcg: implement ...
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
  
  		/*
  		 * Collect unused and wind vtime closer to vnow to prevent
  		 * iocgs from accumulating a large amount of budget.
  		 */
  		vdone = atomic64_read(&iocg->done_vtime);
  		vtime = atomic64_read(&iocg->vtime);
  		current_hweight(iocg, &hw_active, &hw_inuse);
  
  		/*
  		 * Latency QoS detection doesn't account for IOs which are
  		 * in-flight for longer than a period.  Detect them by
  		 * comparing vdone against period start.  If lagging behind
  		 * IOs from past periods, don't increase vrate.
  		 */
7cd806a9a   Tejun Heo   iocost: improve n...
2187
2188
  		if ((ppm_rthr != MILLION || ppm_wthr != MILLION) &&
  		    !atomic_read(&iocg_to_blkg(iocg)->use_delay) &&
7caa47151   Tejun Heo   blkcg: implement ...
2189
2190
2191
2192
2193
  		    time_after64(vtime, vdone) &&
  		    time_after64(vtime, now.vnow -
  				 MAX_LAGGING_PERIODS * period_vtime) &&
  		    time_before64(vdone, now.vnow - period_vtime))
  			nr_lagging++;
7caa47151   Tejun Heo   blkcg: implement ...
2194
  		/*
f1de2439e   Tejun Heo   blk-iocost: revam...
2195
2196
  		 * Determine absolute usage factoring in in-flight IOs to avoid
  		 * high-latency completions appearing as idle.
7caa47151   Tejun Heo   blkcg: implement ...
2197
  		 */
1aa50d020   Tejun Heo   blk-iocost: calcu...
2198
  		usage_us = iocg->usage_delta_us;
dda1315f1   Tejun Heo   blk-iocost: halve...
2199
  		usage_us_sum += usage_us;
f1de2439e   Tejun Heo   blk-iocost: revam...
2200

7caa47151   Tejun Heo   blkcg: implement ...
2201
  		/* see whether there's surplus vtime */
8692d2db8   Tejun Heo   blk-iocost: repla...
2202
  		WARN_ON_ONCE(!list_empty(&iocg->surplus_list));
93f7d2db8   Tejun Heo   blk-iocost: restr...
2203
2204
  		if (hw_inuse < hw_active ||
  		    (!waitqueue_active(&iocg->waitq) &&
f1de2439e   Tejun Heo   blk-iocost: revam...
2205
  		     time_before64(vtime, now.vnow - ioc->margins.low))) {
c09245f61   Baolin Wang   blk-iocost: Move ...
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
  			u32 hwa, old_hwi, hwm, new_hwi, usage;
  			u64 usage_dur;
  
  			if (vdone != vtime) {
  				u64 inflight_us = DIV64_U64_ROUND_UP(
  					cost_to_abs_cost(vtime - vdone, hw_inuse),
  					ioc->vtime_base_rate);
  
  				usage_us = max(usage_us, inflight_us);
  			}
  
  			/* convert to hweight based usage ratio */
  			if (time_after64(iocg->activated_at, ioc->period_at))
  				usage_dur = max_t(u64, now.now - iocg->activated_at, 1);
  			else
  				usage_dur = max_t(u64, now.now - ioc->period_at, 1);
  
  			usage = clamp_t(u32,
  				DIV64_U64_ROUND_UP(usage_us * WEIGHT_ONE,
  						   usage_dur),
  				1, WEIGHT_ONE);
93f7d2db8   Tejun Heo   blk-iocost: restr...
2227
2228
2229
2230
2231
  
  			/*
  			 * Already donating or accumulated enough to start.
  			 * Determine the donation amount.
  			 */
ac33e91e2   Tejun Heo   blk-iocost: imple...
2232
  			current_hweight(iocg, &hwa, &old_hwi);
93f7d2db8   Tejun Heo   blk-iocost: restr...
2233
  			hwm = current_hweight_max(iocg);
ac33e91e2   Tejun Heo   blk-iocost: imple...
2234
2235
  			new_hwi = hweight_after_donation(iocg, old_hwi, hwm,
  							 usage, &now);
93f7d2db8   Tejun Heo   blk-iocost: restr...
2236
  			if (new_hwi < hwm) {
e08d02aa5   Tejun Heo   blk-iocost: imple...
2237
  				iocg->hweight_donating = hwa;
93f7d2db8   Tejun Heo   blk-iocost: restr...
2238
  				iocg->hweight_after_donation = new_hwi;
8692d2db8   Tejun Heo   blk-iocost: repla...
2239
  				list_add(&iocg->surplus_list, &surpluses);
7caa47151   Tejun Heo   blkcg: implement ...
2240
  			} else {
046037551   Tejun Heo   blk-iocost: resto...
2241
2242
2243
  				TRACE_IOCG_PATH(inuse_shortage, iocg, &now,
  						iocg->inuse, iocg->active,
  						iocg->hweight_inuse, new_hwi);
93f7d2db8   Tejun Heo   blk-iocost: restr...
2244
  				__propagate_weights(iocg, iocg->active,
b0853ab4a   Tejun Heo   blk-iocost: revam...
2245
  						    iocg->active, true, &now);
93f7d2db8   Tejun Heo   blk-iocost: restr...
2246
  				nr_shortages++;
7caa47151   Tejun Heo   blkcg: implement ...
2247
2248
  			}
  		} else {
93f7d2db8   Tejun Heo   blk-iocost: restr...
2249
  			/* genuinely short on vtime */
7caa47151   Tejun Heo   blkcg: implement ...
2250
2251
2252
  			nr_shortages++;
  		}
  	}
93f7d2db8   Tejun Heo   blk-iocost: restr...
2253
2254
  	if (!list_empty(&surpluses) && nr_shortages)
  		transfer_surpluses(&surpluses, &now);
7caa47151   Tejun Heo   blkcg: implement ...
2255

00410f1b0   Tejun Heo   blk-iocost: renam...
2256
  	commit_weights(ioc);
7caa47151   Tejun Heo   blkcg: implement ...
2257

8692d2db8   Tejun Heo   blk-iocost: repla...
2258
2259
2260
  	/* surplus list should be dissolved after use */
  	list_for_each_entry_safe(iocg, tiocg, &surpluses, surplus_list)
  		list_del_init(&iocg->surplus_list);
dda1315f1   Tejun Heo   blk-iocost: halve...
2261
  	/*
7caa47151   Tejun Heo   blkcg: implement ...
2262
2263
2264
2265
2266
  	 * If q is getting clogged or we're missing too much, we're issuing
  	 * too much IO and should lower vtime rate.  If we're not missing
  	 * and experiencing shortages but not surpluses, we're too stingy
  	 * and should increase vtime rate.
  	 */
25d41e4aa   Tejun Heo   iocost: better tr...
2267
  	prev_busy_level = ioc->busy_level;
7caa47151   Tejun Heo   blkcg: implement ...
2268
2269
2270
  	if (rq_wait_pct > RQ_WAIT_BUSY_PCT ||
  	    missed_ppm[READ] > ppm_rthr ||
  	    missed_ppm[WRITE] > ppm_wthr) {
81ca627a9   Tejun Heo   iocost: don't let...
2271
  		/* clearly missing QoS targets, slow down vrate */
7caa47151   Tejun Heo   blkcg: implement ...
2272
2273
  		ioc->busy_level = max(ioc->busy_level, 0);
  		ioc->busy_level++;
7cd806a9a   Tejun Heo   iocost: improve n...
2274
  	} else if (rq_wait_pct <= RQ_WAIT_BUSY_PCT * UNBUSY_THR_PCT / 100 &&
7caa47151   Tejun Heo   blkcg: implement ...
2275
2276
  		   missed_ppm[READ] <= ppm_rthr * UNBUSY_THR_PCT / 100 &&
  		   missed_ppm[WRITE] <= ppm_wthr * UNBUSY_THR_PCT / 100) {
81ca627a9   Tejun Heo   iocost: don't let...
2277
2278
2279
2280
2281
2282
  		/* QoS targets are being met with >25% margin */
  		if (nr_shortages) {
  			/*
  			 * We're throttling while the device has spare
  			 * capacity.  If vrate was being slowed down, stop.
  			 */
7cd806a9a   Tejun Heo   iocost: improve n...
2283
  			ioc->busy_level = min(ioc->busy_level, 0);
81ca627a9   Tejun Heo   iocost: don't let...
2284
2285
2286
  
  			/*
  			 * If there are IOs spanning multiple periods, wait
065655c86   Tejun Heo   blk-iocost: decou...
2287
  			 * them out before pushing the device harder.
81ca627a9   Tejun Heo   iocost: don't let...
2288
  			 */
065655c86   Tejun Heo   blk-iocost: decou...
2289
  			if (!nr_lagging)
7cd806a9a   Tejun Heo   iocost: improve n...
2290
  				ioc->busy_level--;
81ca627a9   Tejun Heo   iocost: don't let...
2291
2292
2293
2294
2295
2296
2297
2298
  		} else {
  			/*
  			 * Nobody is being throttled and the users aren't
  			 * issuing enough IOs to saturate the device.  We
  			 * simply don't know how close the device is to
  			 * saturation.  Coast.
  			 */
  			ioc->busy_level = 0;
7cd806a9a   Tejun Heo   iocost: improve n...
2299
  		}
7caa47151   Tejun Heo   blkcg: implement ...
2300
  	} else {
81ca627a9   Tejun Heo   iocost: don't let...
2301
  		/* inside the hysterisis margin, we're good */
7caa47151   Tejun Heo   blkcg: implement ...
2302
2303
2304
2305
  		ioc->busy_level = 0;
  	}
  
  	ioc->busy_level = clamp(ioc->busy_level, -1000, 1000);
926f75f6a   Baolin Wang   blk-iocost: Facto...
2306
2307
  	ioc_adjust_base_vrate(ioc, rq_wait_pct, nr_lagging, nr_shortages,
  			      prev_busy_level, missed_ppm);
7caa47151   Tejun Heo   blkcg: implement ...
2308
2309
  
  	ioc_refresh_params(ioc, false);
33a1fe6d8   Tejun Heo   iocost: replace n...
2310
  	ioc_forgive_debts(ioc, usage_us_sum, nr_debtors, &now);
7caa47151   Tejun Heo   blkcg: implement ...
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
  	/*
  	 * This period is done.  Move onto the next one.  If nothing's
  	 * going on with the device, stop the timer.
  	 */
  	atomic64_inc(&ioc->cur_period);
  
  	if (ioc->running != IOC_STOP) {
  		if (!list_empty(&ioc->active_iocgs)) {
  			ioc_start_period(ioc, &now);
  		} else {
  			ioc->busy_level = 0;
ac33e91e2   Tejun Heo   blk-iocost: imple...
2322
  			ioc->vtime_err = 0;
7caa47151   Tejun Heo   blkcg: implement ...
2323
2324
  			ioc->running = IOC_IDLE;
  		}
ac33e91e2   Tejun Heo   blk-iocost: imple...
2325
2326
  
  		ioc_refresh_vrate(ioc, &now);
7caa47151   Tejun Heo   blkcg: implement ...
2327
2328
2329
2330
  	}
  
  	spin_unlock_irq(&ioc->lock);
  }
b0853ab4a   Tejun Heo   blk-iocost: revam...
2331
2332
2333
2334
2335
  static u64 adjust_inuse_and_calc_cost(struct ioc_gq *iocg, u64 vtime,
  				      u64 abs_cost, struct ioc_now *now)
  {
  	struct ioc *ioc = iocg->ioc;
  	struct ioc_margins *margins = &ioc->margins;
046037551   Tejun Heo   blk-iocost: resto...
2336
  	u32 __maybe_unused old_inuse = iocg->inuse, __maybe_unused old_hwi;
aa67db24b   Tejun Heo   iocost: fix infin...
2337
  	u32 hwi, adj_step;
b0853ab4a   Tejun Heo   blk-iocost: revam...
2338
2339
2340
2341
  	s64 margin;
  	u64 cost, new_inuse;
  
  	current_hweight(iocg, NULL, &hwi);
046037551   Tejun Heo   blk-iocost: resto...
2342
  	old_hwi = hwi;
b0853ab4a   Tejun Heo   blk-iocost: revam...
2343
2344
  	cost = abs_cost_to_cost(abs_cost, hwi);
  	margin = now->vnow - vtime - cost;
c421a3eb2   Tejun Heo   blk-iocost: revam...
2345
2346
2347
  	/* debt handling owns inuse for debtors */
  	if (iocg->abs_vdebt)
  		return cost;
b0853ab4a   Tejun Heo   blk-iocost: revam...
2348
  	/*
5ba1add21   Baolin Wang   blk-iocost: Fix s...
2349
  	 * We only increase inuse during period and do so if the margin has
b0853ab4a   Tejun Heo   blk-iocost: revam...
2350
2351
2352
2353
2354
2355
2356
2357
2358
  	 * deteriorated since the previous adjustment.
  	 */
  	if (margin >= iocg->saved_margin || margin >= margins->low ||
  	    iocg->inuse == iocg->active)
  		return cost;
  
  	spin_lock_irq(&ioc->lock);
  
  	/* we own inuse only when @iocg is in the normal active state */
c421a3eb2   Tejun Heo   blk-iocost: revam...
2359
  	if (iocg->abs_vdebt || list_empty(&iocg->active_list)) {
b0853ab4a   Tejun Heo   blk-iocost: revam...
2360
2361
2362
  		spin_unlock_irq(&ioc->lock);
  		return cost;
  	}
aa67db24b   Tejun Heo   iocost: fix infin...
2363
2364
2365
2366
2367
2368
2369
  	/*
  	 * Bump up inuse till @abs_cost fits in the existing budget.
  	 * adj_step must be determined after acquiring ioc->lock - we might
  	 * have raced and lost to another thread for activation and could
  	 * be reading 0 iocg->active before ioc->lock which will lead to
  	 * infinite loop.
  	 */
b0853ab4a   Tejun Heo   blk-iocost: revam...
2370
  	new_inuse = iocg->inuse;
aa67db24b   Tejun Heo   iocost: fix infin...
2371
  	adj_step = DIV_ROUND_UP(iocg->active * INUSE_ADJ_STEP_PCT, 100);
b0853ab4a   Tejun Heo   blk-iocost: revam...
2372
2373
2374
2375
2376
2377
2378
2379
2380
  	do {
  		new_inuse = new_inuse + adj_step;
  		propagate_weights(iocg, iocg->active, new_inuse, true, now);
  		current_hweight(iocg, NULL, &hwi);
  		cost = abs_cost_to_cost(abs_cost, hwi);
  	} while (time_after64(vtime + cost, now->vnow) &&
  		 iocg->inuse != iocg->active);
  
  	spin_unlock_irq(&ioc->lock);
046037551   Tejun Heo   blk-iocost: resto...
2381
2382
2383
  
  	TRACE_IOCG_PATH(inuse_adjust, iocg, now,
  			old_inuse, iocg->inuse, old_hwi, hwi);
b0853ab4a   Tejun Heo   blk-iocost: revam...
2384
2385
  	return cost;
  }
7caa47151   Tejun Heo   blkcg: implement ...
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
  static void calc_vtime_cost_builtin(struct bio *bio, struct ioc_gq *iocg,
  				    bool is_merge, u64 *costp)
  {
  	struct ioc *ioc = iocg->ioc;
  	u64 coef_seqio, coef_randio, coef_page;
  	u64 pages = max_t(u64, bio_sectors(bio) >> IOC_SECT_TO_PAGE_SHIFT, 1);
  	u64 seek_pages = 0;
  	u64 cost = 0;
  
  	switch (bio_op(bio)) {
  	case REQ_OP_READ:
  		coef_seqio	= ioc->params.lcoefs[LCOEF_RSEQIO];
  		coef_randio	= ioc->params.lcoefs[LCOEF_RRANDIO];
  		coef_page	= ioc->params.lcoefs[LCOEF_RPAGE];
  		break;
  	case REQ_OP_WRITE:
  		coef_seqio	= ioc->params.lcoefs[LCOEF_WSEQIO];
  		coef_randio	= ioc->params.lcoefs[LCOEF_WRANDIO];
  		coef_page	= ioc->params.lcoefs[LCOEF_WPAGE];
  		break;
  	default:
  		goto out;
  	}
  
  	if (iocg->cursor) {
  		seek_pages = abs(bio->bi_iter.bi_sector - iocg->cursor);
  		seek_pages >>= IOC_SECT_TO_PAGE_SHIFT;
  	}
  
  	if (!is_merge) {
  		if (seek_pages > LCOEF_RANDIO_PAGES) {
  			cost += coef_randio;
  		} else {
  			cost += coef_seqio;
  		}
  	}
  	cost += pages * coef_page;
  out:
  	*costp = cost;
  }
  
  static u64 calc_vtime_cost(struct bio *bio, struct ioc_gq *iocg, bool is_merge)
  {
  	u64 cost;
  
  	calc_vtime_cost_builtin(bio, iocg, is_merge, &cost);
  	return cost;
  }
cd006509b   Tejun Heo   blk-iocost: accou...
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
  static void calc_size_vtime_cost_builtin(struct request *rq, struct ioc *ioc,
  					 u64 *costp)
  {
  	unsigned int pages = blk_rq_stats_sectors(rq) >> IOC_SECT_TO_PAGE_SHIFT;
  
  	switch (req_op(rq)) {
  	case REQ_OP_READ:
  		*costp = pages * ioc->params.lcoefs[LCOEF_RPAGE];
  		break;
  	case REQ_OP_WRITE:
  		*costp = pages * ioc->params.lcoefs[LCOEF_WPAGE];
  		break;
  	default:
  		*costp = 0;
  	}
  }
  
  static u64 calc_size_vtime_cost(struct request *rq, struct ioc *ioc)
  {
  	u64 cost;
  
  	calc_size_vtime_cost_builtin(rq, ioc, &cost);
  	return cost;
  }
7caa47151   Tejun Heo   blkcg: implement ...
2458
2459
2460
2461
2462
2463
2464
  static void ioc_rqos_throttle(struct rq_qos *rqos, struct bio *bio)
  {
  	struct blkcg_gq *blkg = bio->bi_blkg;
  	struct ioc *ioc = rqos_to_ioc(rqos);
  	struct ioc_gq *iocg = blkg_to_iocg(blkg);
  	struct ioc_now now;
  	struct iocg_wait wait;
7caa47151   Tejun Heo   blkcg: implement ...
2465
  	u64 abs_cost, cost, vtime;
da437b95d   Tejun Heo   blk-iocost: grab ...
2466
2467
  	bool use_debt, ioc_locked;
  	unsigned long flags;
7caa47151   Tejun Heo   blkcg: implement ...
2468

d16baa3f1   Tejun Heo   blk-iocost: fix N...
2469
2470
  	/* bypass IOs if disabled, still initializing, or for root cgroup */
  	if (!ioc->enabled || !iocg || !iocg->level)
7caa47151   Tejun Heo   blkcg: implement ...
2471
  		return;
7caa47151   Tejun Heo   blkcg: implement ...
2472
2473
2474
2475
  	/* calculate the absolute vtime cost */
  	abs_cost = calc_vtime_cost(bio, iocg, false);
  	if (!abs_cost)
  		return;
f1de2439e   Tejun Heo   blk-iocost: revam...
2476
2477
  	if (!iocg_activate(iocg, &now))
  		return;
7caa47151   Tejun Heo   blkcg: implement ...
2478
  	iocg->cursor = bio_end_sector(bio);
7caa47151   Tejun Heo   blkcg: implement ...
2479
  	vtime = atomic64_read(&iocg->vtime);
b0853ab4a   Tejun Heo   blk-iocost: revam...
2480
  	cost = adjust_inuse_and_calc_cost(iocg, vtime, abs_cost, &now);
7caa47151   Tejun Heo   blkcg: implement ...
2481
2482
2483
2484
2485
2486
  
  	/*
  	 * If no one's waiting and within budget, issue right away.  The
  	 * tests are racy but the races aren't systemic - we only miss once
  	 * in a while which is fine.
  	 */
0b80f9866   Tejun Heo   iocost: protect i...
2487
  	if (!waitqueue_active(&iocg->waitq) && !iocg->abs_vdebt &&
7caa47151   Tejun Heo   blkcg: implement ...
2488
  	    time_before_eq64(vtime + cost, now.vnow)) {
97eb19751   Tejun Heo   blk-iocost: add a...
2489
  		iocg_commit_bio(iocg, bio, abs_cost, cost);
7caa47151   Tejun Heo   blkcg: implement ...
2490
2491
  		return;
  	}
36a524814   Tejun Heo   blk-iocost: Accou...
2492
  	/*
da437b95d   Tejun Heo   blk-iocost: grab ...
2493
2494
2495
2496
2497
  	 * We're over budget. This can be handled in two ways. IOs which may
  	 * cause priority inversions are punted to @ioc->aux_iocg and charged as
  	 * debt. Otherwise, the issuer is blocked on @iocg->waitq. Debt handling
  	 * requires @ioc->lock, waitq handling @iocg->waitq.lock. Determine
  	 * whether debt handling is needed and acquire locks accordingly.
0b80f9866   Tejun Heo   iocost: protect i...
2498
  	 */
da437b95d   Tejun Heo   blk-iocost: grab ...
2499
2500
  	use_debt = bio_issue_as_root_blkg(bio) || fatal_signal_pending(current);
  	ioc_locked = use_debt || READ_ONCE(iocg->abs_vdebt);
b0853ab4a   Tejun Heo   blk-iocost: revam...
2501
  retry_lock:
da437b95d   Tejun Heo   blk-iocost: grab ...
2502
2503
2504
2505
2506
2507
2508
2509
2510
  	iocg_lock(iocg, ioc_locked, &flags);
  
  	/*
  	 * @iocg must stay activated for debt and waitq handling. Deactivation
  	 * is synchronized against both ioc->lock and waitq.lock and we won't
  	 * get deactivated as long as we're waiting or has debt, so we're good
  	 * if we're activated here. In the unlikely cases that we aren't, just
  	 * issue the IO.
  	 */
0b80f9866   Tejun Heo   iocost: protect i...
2511
  	if (unlikely(list_empty(&iocg->active_list))) {
da437b95d   Tejun Heo   blk-iocost: grab ...
2512
  		iocg_unlock(iocg, ioc_locked, &flags);
97eb19751   Tejun Heo   blk-iocost: add a...
2513
  		iocg_commit_bio(iocg, bio, abs_cost, cost);
0b80f9866   Tejun Heo   iocost: protect i...
2514
2515
2516
2517
2518
2519
2520
2521
  		return;
  	}
  
  	/*
  	 * We're over budget. If @bio has to be issued regardless, remember
  	 * the abs_cost instead of advancing vtime. iocg_kick_waitq() will pay
  	 * off the debt before waking more IOs.
  	 *
36a524814   Tejun Heo   blk-iocost: Accou...
2522
  	 * This way, the debt is continuously paid off each period with the
0b80f9866   Tejun Heo   iocost: protect i...
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
  	 * actual budget available to the cgroup. If we just wound vtime, we
  	 * would incorrectly use the current hw_inuse for the entire amount
  	 * which, for example, can lead to the cgroup staying blocked for a
  	 * long time even with substantially raised hw_inuse.
  	 *
  	 * An iocg with vdebt should stay online so that the timer can keep
  	 * deducting its vdebt and [de]activate use_delay mechanism
  	 * accordingly. We don't want to race against the timer trying to
  	 * clear them and leave @iocg inactive w/ dangling use_delay heavily
  	 * penalizing the cgroup and its descendants.
36a524814   Tejun Heo   blk-iocost: Accou...
2533
  	 */
da437b95d   Tejun Heo   blk-iocost: grab ...
2534
  	if (use_debt) {
c421a3eb2   Tejun Heo   blk-iocost: revam...
2535
  		iocg_incur_debt(iocg, abs_cost, &now);
54c52e10d   Tejun Heo   blk-iocost: switc...
2536
  		if (iocg_kick_delay(iocg, &now))
d7bd15a13   Tejun Heo   iocost: over-budg...
2537
2538
  			blkcg_schedule_throttle(rqos->q,
  					(bio->bi_opf & REQ_SWAP) == REQ_SWAP);
da437b95d   Tejun Heo   blk-iocost: grab ...
2539
  		iocg_unlock(iocg, ioc_locked, &flags);
7caa47151   Tejun Heo   blkcg: implement ...
2540
2541
  		return;
  	}
b0853ab4a   Tejun Heo   blk-iocost: revam...
2542
  	/* guarantee that iocgs w/ waiters have maximum inuse */
c421a3eb2   Tejun Heo   blk-iocost: revam...
2543
  	if (!iocg->abs_vdebt && iocg->inuse != iocg->active) {
b0853ab4a   Tejun Heo   blk-iocost: revam...
2544
2545
2546
2547
2548
2549
2550
2551
  		if (!ioc_locked) {
  			iocg_unlock(iocg, false, &flags);
  			ioc_locked = true;
  			goto retry_lock;
  		}
  		propagate_weights(iocg, iocg->active, iocg->active, true,
  				  &now);
  	}
7caa47151   Tejun Heo   blkcg: implement ...
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
  	/*
  	 * Append self to the waitq and schedule the wakeup timer if we're
  	 * the first waiter.  The timer duration is calculated based on the
  	 * current vrate.  vtime and hweight changes can make it too short
  	 * or too long.  Each wait entry records the absolute cost it's
  	 * waiting for to allow re-evaluation using a custom wait entry.
  	 *
  	 * If too short, the timer simply reschedules itself.  If too long,
  	 * the period timer will notice and trigger wakeups.
  	 *
  	 * All waiters are on iocg->waitq and the wait states are
  	 * synchronized using waitq.lock.
  	 */
7caa47151   Tejun Heo   blkcg: implement ...
2565
2566
2567
2568
2569
2570
2571
  	init_waitqueue_func_entry(&wait.wait, iocg_wake_fn);
  	wait.wait.private = current;
  	wait.bio = bio;
  	wait.abs_cost = abs_cost;
  	wait.committed = false;	/* will be set true by waker */
  
  	__add_wait_queue_entry_tail(&iocg->waitq, &wait.wait);
da437b95d   Tejun Heo   blk-iocost: grab ...
2572
  	iocg_kick_waitq(iocg, ioc_locked, &now);
7caa47151   Tejun Heo   blkcg: implement ...
2573

da437b95d   Tejun Heo   blk-iocost: grab ...
2574
  	iocg_unlock(iocg, ioc_locked, &flags);
7caa47151   Tejun Heo   blkcg: implement ...
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
  
  	while (true) {
  		set_current_state(TASK_UNINTERRUPTIBLE);
  		if (wait.committed)
  			break;
  		io_schedule();
  	}
  
  	/* waker already committed us, proceed */
  	finish_wait(&iocg->waitq, &wait.wait);
  }
  
  static void ioc_rqos_merge(struct rq_qos *rqos, struct request *rq,
  			   struct bio *bio)
  {
  	struct ioc_gq *iocg = blkg_to_iocg(bio->bi_blkg);
d16baa3f1   Tejun Heo   blk-iocost: fix N...
2591
  	struct ioc *ioc = rqos_to_ioc(rqos);
7caa47151   Tejun Heo   blkcg: implement ...
2592
  	sector_t bio_end = bio_end_sector(bio);
e1518f63f   Tejun Heo   blk-iocost: Don't...
2593
  	struct ioc_now now;
b0853ab4a   Tejun Heo   blk-iocost: revam...
2594
  	u64 vtime, abs_cost, cost;
0b80f9866   Tejun Heo   iocost: protect i...
2595
  	unsigned long flags;
7caa47151   Tejun Heo   blkcg: implement ...
2596

d16baa3f1   Tejun Heo   blk-iocost: fix N...
2597
2598
  	/* bypass if disabled, still initializing, or for root cgroup */
  	if (!ioc->enabled || !iocg || !iocg->level)
7caa47151   Tejun Heo   blkcg: implement ...
2599
2600
2601
2602
2603
  		return;
  
  	abs_cost = calc_vtime_cost(bio, iocg, true);
  	if (!abs_cost)
  		return;
e1518f63f   Tejun Heo   blk-iocost: Don't...
2604
  	ioc_now(ioc, &now);
b0853ab4a   Tejun Heo   blk-iocost: revam...
2605
2606
2607
  
  	vtime = atomic64_read(&iocg->vtime);
  	cost = adjust_inuse_and_calc_cost(iocg, vtime, abs_cost, &now);
e1518f63f   Tejun Heo   blk-iocost: Don't...
2608

7caa47151   Tejun Heo   blkcg: implement ...
2609
2610
2611
2612
  	/* update cursor if backmerging into the request at the cursor */
  	if (blk_rq_pos(rq) < bio_end &&
  	    blk_rq_pos(rq) + blk_rq_sectors(rq) == iocg->cursor)
  		iocg->cursor = bio_end;
e1518f63f   Tejun Heo   blk-iocost: Don't...
2613
  	/*
0b80f9866   Tejun Heo   iocost: protect i...
2614
2615
  	 * Charge if there's enough vtime budget and the existing request has
  	 * cost assigned.
e1518f63f   Tejun Heo   blk-iocost: Don't...
2616
2617
  	 */
  	if (rq->bio && rq->bio->bi_iocost_cost &&
0b80f9866   Tejun Heo   iocost: protect i...
2618
  	    time_before_eq64(atomic64_read(&iocg->vtime) + cost, now.vnow)) {
97eb19751   Tejun Heo   blk-iocost: add a...
2619
  		iocg_commit_bio(iocg, bio, abs_cost, cost);
0b80f9866   Tejun Heo   iocost: protect i...
2620
2621
2622
2623
2624
2625
2626
2627
  		return;
  	}
  
  	/*
  	 * Otherwise, account it as debt if @iocg is online, which it should
  	 * be for the vast majority of cases. See debt handling in
  	 * ioc_rqos_throttle() for details.
  	 */
c421a3eb2   Tejun Heo   blk-iocost: revam...
2628
2629
  	spin_lock_irqsave(&ioc->lock, flags);
  	spin_lock(&iocg->waitq.lock);
0b80f9866   Tejun Heo   iocost: protect i...
2630
  	if (likely(!list_empty(&iocg->active_list))) {
c421a3eb2   Tejun Heo   blk-iocost: revam...
2631
2632
2633
2634
  		iocg_incur_debt(iocg, abs_cost, &now);
  		if (iocg_kick_delay(iocg, &now))
  			blkcg_schedule_throttle(rqos->q,
  					(bio->bi_opf & REQ_SWAP) == REQ_SWAP);
0b80f9866   Tejun Heo   iocost: protect i...
2635
  	} else {
97eb19751   Tejun Heo   blk-iocost: add a...
2636
  		iocg_commit_bio(iocg, bio, abs_cost, cost);
0b80f9866   Tejun Heo   iocost: protect i...
2637
  	}
c421a3eb2   Tejun Heo   blk-iocost: revam...
2638
2639
2640
  
  	spin_unlock(&iocg->waitq.lock);
  	spin_unlock_irqrestore(&ioc->lock, flags);
7caa47151   Tejun Heo   blkcg: implement ...
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
  }
  
  static void ioc_rqos_done_bio(struct rq_qos *rqos, struct bio *bio)
  {
  	struct ioc_gq *iocg = blkg_to_iocg(bio->bi_blkg);
  
  	if (iocg && bio->bi_iocost_cost)
  		atomic64_add(bio->bi_iocost_cost, &iocg->done_vtime);
  }
  
  static void ioc_rqos_done(struct rq_qos *rqos, struct request *rq)
  {
  	struct ioc *ioc = rqos_to_ioc(rqos);
5e124f743   Tejun Heo   blk-iocost: use l...
2654
  	struct ioc_pcpu_stat *ccs;
cd006509b   Tejun Heo   blk-iocost: accou...
2655
  	u64 on_q_ns, rq_wait_ns, size_nsec;
7caa47151   Tejun Heo   blkcg: implement ...
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
  	int pidx, rw;
  
  	if (!ioc->enabled || !rq->alloc_time_ns || !rq->start_time_ns)
  		return;
  
  	switch (req_op(rq) & REQ_OP_MASK) {
  	case REQ_OP_READ:
  		pidx = QOS_RLAT;
  		rw = READ;
  		break;
  	case REQ_OP_WRITE:
  		pidx = QOS_WLAT;
  		rw = WRITE;
  		break;
  	default:
  		return;
  	}
  
  	on_q_ns = ktime_get_ns() - rq->alloc_time_ns;
  	rq_wait_ns = rq->start_time_ns - rq->alloc_time_ns;
cd006509b   Tejun Heo   blk-iocost: accou...
2676
  	size_nsec = div64_u64(calc_size_vtime_cost(rq, ioc), VTIME_PER_NSEC);
7caa47151   Tejun Heo   blkcg: implement ...
2677

5e124f743   Tejun Heo   blk-iocost: use l...
2678
  	ccs = get_cpu_ptr(ioc->pcpu_stat);
cd006509b   Tejun Heo   blk-iocost: accou...
2679
2680
  	if (on_q_ns <= size_nsec ||
  	    on_q_ns - size_nsec <= ioc->params.qos[pidx] * NSEC_PER_USEC)
5e124f743   Tejun Heo   blk-iocost: use l...
2681
  		local_inc(&ccs->missed[rw].nr_met);
7caa47151   Tejun Heo   blkcg: implement ...
2682
  	else
5e124f743   Tejun Heo   blk-iocost: use l...
2683
2684
2685
  		local_inc(&ccs->missed[rw].nr_missed);
  
  	local64_add(rq_wait_ns, &ccs->rq_wait_ns);
7caa47151   Tejun Heo   blkcg: implement ...
2686

5e124f743   Tejun Heo   blk-iocost: use l...
2687
  	put_cpu_ptr(ccs);
7caa47151   Tejun Heo   blkcg: implement ...
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
  }
  
  static void ioc_rqos_queue_depth_changed(struct rq_qos *rqos)
  {
  	struct ioc *ioc = rqos_to_ioc(rqos);
  
  	spin_lock_irq(&ioc->lock);
  	ioc_refresh_params(ioc, false);
  	spin_unlock_irq(&ioc->lock);
  }
  
  static void ioc_rqos_exit(struct rq_qos *rqos)
  {
  	struct ioc *ioc = rqos_to_ioc(rqos);
  
  	blkcg_deactivate_policy(rqos->q, &blkcg_policy_iocost);
  
  	spin_lock_irq(&ioc->lock);
  	ioc->running = IOC_STOP;
  	spin_unlock_irq(&ioc->lock);
  
  	del_timer_sync(&ioc->timer);
  	free_percpu(ioc->pcpu_stat);
  	kfree(ioc);
  }
  
  static struct rq_qos_ops ioc_rqos_ops = {
  	.throttle = ioc_rqos_throttle,
  	.merge = ioc_rqos_merge,
  	.done_bio = ioc_rqos_done_bio,
  	.done = ioc_rqos_done,
  	.queue_depth_changed = ioc_rqos_queue_depth_changed,
  	.exit = ioc_rqos_exit,
  };
  
  static int blk_iocost_init(struct request_queue *q)
  {
  	struct ioc *ioc;
  	struct rq_qos *rqos;
5e124f743   Tejun Heo   blk-iocost: use l...
2727
  	int i, cpu, ret;
7caa47151   Tejun Heo   blkcg: implement ...
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
  
  	ioc = kzalloc(sizeof(*ioc), GFP_KERNEL);
  	if (!ioc)
  		return -ENOMEM;
  
  	ioc->pcpu_stat = alloc_percpu(struct ioc_pcpu_stat);
  	if (!ioc->pcpu_stat) {
  		kfree(ioc);
  		return -ENOMEM;
  	}
5e124f743   Tejun Heo   blk-iocost: use l...
2738
2739
2740
2741
2742
2743
2744
2745
2746
  	for_each_possible_cpu(cpu) {
  		struct ioc_pcpu_stat *ccs = per_cpu_ptr(ioc->pcpu_stat, cpu);
  
  		for (i = 0; i < ARRAY_SIZE(ccs->missed); i++) {
  			local_set(&ccs->missed[i].nr_met, 0);
  			local_set(&ccs->missed[i].nr_missed, 0);
  		}
  		local64_set(&ccs->rq_wait_ns, 0);
  	}
7caa47151   Tejun Heo   blkcg: implement ...
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
  	rqos = &ioc->rqos;
  	rqos->id = RQ_QOS_COST;
  	rqos->ops = &ioc_rqos_ops;
  	rqos->q = q;
  
  	spin_lock_init(&ioc->lock);
  	timer_setup(&ioc->timer, ioc_timer_fn, 0);
  	INIT_LIST_HEAD(&ioc->active_iocgs);
  
  	ioc->running = IOC_IDLE;
ac33e91e2   Tejun Heo   blk-iocost: imple...
2757
  	ioc->vtime_base_rate = VTIME_PER_USEC;
7caa47151   Tejun Heo   blkcg: implement ...
2758
  	atomic64_set(&ioc->vtime_rate, VTIME_PER_USEC);
67b7b641c   Ahmed S. Darwish   iocost: Use seque...
2759
  	seqcount_spinlock_init(&ioc->period_seqcount, &ioc->lock);
7caa47151   Tejun Heo   blkcg: implement ...
2760
2761
2762
2763
2764
2765
2766
2767
  	ioc->period_at = ktime_to_us(ktime_get());
  	atomic64_set(&ioc->cur_period, 0);
  	atomic_set(&ioc->hweight_gen, 0);
  
  	spin_lock_irq(&ioc->lock);
  	ioc->autop_idx = AUTOP_INVALID;
  	ioc_refresh_params(ioc, true);
  	spin_unlock_irq(&ioc->lock);
d16baa3f1   Tejun Heo   blk-iocost: fix N...
2768
2769
2770
2771
2772
2773
  	/*
  	 * rqos must be added before activation to allow iocg_pd_init() to
  	 * lookup the ioc from q. This means that the rqos methods may get
  	 * called before policy activation completion, can't assume that the
  	 * target bio has an iocg associated and need to test for NULL iocg.
  	 */
7caa47151   Tejun Heo   blkcg: implement ...
2774
2775
2776
2777
  	rq_qos_add(q, rqos);
  	ret = blkcg_activate_policy(q, &blkcg_policy_iocost);
  	if (ret) {
  		rq_qos_del(q, rqos);
3532e7227   Tejun Heo   blkcg: fix missin...
2778
  		free_percpu(ioc->pcpu_stat);
7caa47151   Tejun Heo   blkcg: implement ...
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
  		kfree(ioc);
  		return ret;
  	}
  	return 0;
  }
  
  static struct blkcg_policy_data *ioc_cpd_alloc(gfp_t gfp)
  {
  	struct ioc_cgrp *iocc;
  
  	iocc = kzalloc(sizeof(struct ioc_cgrp), gfp);
e916ad29d   Tejun Heo   blkcg: add missin...
2790
2791
  	if (!iocc)
  		return NULL;
7caa47151   Tejun Heo   blkcg: implement ...
2792

bd0adb91a   Tejun Heo   blk-iocost: use W...
2793
  	iocc->dfl_weight = CGROUP_WEIGHT_DFL * WEIGHT_ONE;
7caa47151   Tejun Heo   blkcg: implement ...
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
  	return &iocc->cpd;
  }
  
  static void ioc_cpd_free(struct blkcg_policy_data *cpd)
  {
  	kfree(container_of(cpd, struct ioc_cgrp, cpd));
  }
  
  static struct blkg_policy_data *ioc_pd_alloc(gfp_t gfp, struct request_queue *q,
  					     struct blkcg *blkcg)
  {
  	int levels = blkcg->css.cgroup->level + 1;
  	struct ioc_gq *iocg;
f61d6e259   Gustavo A. R. Silva   blk-iocost: Use s...
2807
  	iocg = kzalloc_node(struct_size(iocg, ancestors, levels), gfp, q->node);
7caa47151   Tejun Heo   blkcg: implement ...
2808
2809
  	if (!iocg)
  		return NULL;
97eb19751   Tejun Heo   blk-iocost: add a...
2810
2811
2812
2813
2814
  	iocg->pcpu_stat = alloc_percpu_gfp(struct iocg_pcpu_stat, gfp);
  	if (!iocg->pcpu_stat) {
  		kfree(iocg);
  		return NULL;
  	}
7caa47151   Tejun Heo   blkcg: implement ...
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
  	return &iocg->pd;
  }
  
  static void ioc_pd_init(struct blkg_policy_data *pd)
  {
  	struct ioc_gq *iocg = pd_to_iocg(pd);
  	struct blkcg_gq *blkg = pd_to_blkg(&iocg->pd);
  	struct ioc *ioc = q_to_ioc(blkg->q);
  	struct ioc_now now;
  	struct blkcg_gq *tblkg;
  	unsigned long flags;
  
  	ioc_now(ioc, &now);
  
  	iocg->ioc = ioc;
  	atomic64_set(&iocg->vtime, now.vnow);
  	atomic64_set(&iocg->done_vtime, now.vnow);
  	atomic64_set(&iocg->active_period, atomic64_read(&ioc->cur_period));
  	INIT_LIST_HEAD(&iocg->active_list);
97eb19751   Tejun Heo   blk-iocost: add a...
2834
  	INIT_LIST_HEAD(&iocg->walk_list);
8692d2db8   Tejun Heo   blk-iocost: repla...
2835
  	INIT_LIST_HEAD(&iocg->surplus_list);
fe20cdb51   Tejun Heo   blk-iocost: s/HWE...
2836
2837
  	iocg->hweight_active = WEIGHT_ONE;
  	iocg->hweight_inuse = WEIGHT_ONE;
7caa47151   Tejun Heo   blkcg: implement ...
2838
2839
2840
2841
  
  	init_waitqueue_head(&iocg->waitq);
  	hrtimer_init(&iocg->waitq_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
  	iocg->waitq_timer.function = iocg_waitq_timer_fn;
7caa47151   Tejun Heo   blkcg: implement ...
2842
2843
2844
2845
2846
2847
2848
2849
2850
  
  	iocg->level = blkg->blkcg->css.cgroup->level;
  
  	for (tblkg = blkg; tblkg; tblkg = tblkg->parent) {
  		struct ioc_gq *tiocg = blkg_to_iocg(tblkg);
  		iocg->ancestors[tiocg->level] = tiocg;
  	}
  
  	spin_lock_irqsave(&ioc->lock, flags);
b0853ab4a   Tejun Heo   blk-iocost: revam...
2851
  	weight_updated(iocg, &now);
7caa47151   Tejun Heo   blkcg: implement ...
2852
2853
2854
2855
2856
2857
2858
  	spin_unlock_irqrestore(&ioc->lock, flags);
  }
  
  static void ioc_pd_free(struct blkg_policy_data *pd)
  {
  	struct ioc_gq *iocg = pd_to_iocg(pd);
  	struct ioc *ioc = iocg->ioc;
5aeac7c4b   Tejun Heo   blk-iocost: ioc_p...
2859
  	unsigned long flags;
7caa47151   Tejun Heo   blkcg: implement ...
2860
2861
  
  	if (ioc) {
5aeac7c4b   Tejun Heo   blk-iocost: ioc_p...
2862
  		spin_lock_irqsave(&ioc->lock, flags);
97eb19751   Tejun Heo   blk-iocost: add a...
2863

7caa47151   Tejun Heo   blkcg: implement ...
2864
  		if (!list_empty(&iocg->active_list)) {
b0853ab4a   Tejun Heo   blk-iocost: revam...
2865
2866
2867
2868
  			struct ioc_now now;
  
  			ioc_now(ioc, &now);
  			propagate_weights(iocg, 0, 0, false, &now);
7caa47151   Tejun Heo   blkcg: implement ...
2869
2870
  			list_del_init(&iocg->active_list);
  		}
97eb19751   Tejun Heo   blk-iocost: add a...
2871
2872
  
  		WARN_ON_ONCE(!list_empty(&iocg->walk_list));
8692d2db8   Tejun Heo   blk-iocost: repla...
2873
  		WARN_ON_ONCE(!list_empty(&iocg->surplus_list));
97eb19751   Tejun Heo   blk-iocost: add a...
2874

5aeac7c4b   Tejun Heo   blk-iocost: ioc_p...
2875
  		spin_unlock_irqrestore(&ioc->lock, flags);
e036c4cab   Tejun Heo   blk-iocost: Fix i...
2876
2877
  
  		hrtimer_cancel(&iocg->waitq_timer);
7caa47151   Tejun Heo   blkcg: implement ...
2878
  	}
97eb19751   Tejun Heo   blk-iocost: add a...
2879
  	free_percpu(iocg->pcpu_stat);
7caa47151   Tejun Heo   blkcg: implement ...
2880
2881
  	kfree(iocg);
  }
97eb19751   Tejun Heo   blk-iocost: add a...
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
  static size_t ioc_pd_stat(struct blkg_policy_data *pd, char *buf, size_t size)
  {
  	struct ioc_gq *iocg = pd_to_iocg(pd);
  	struct ioc *ioc = iocg->ioc;
  	size_t pos = 0;
  
  	if (!ioc->enabled)
  		return 0;
  
  	if (iocg->level == 0) {
  		unsigned vp10k = DIV64_U64_ROUND_CLOSEST(
ac33e91e2   Tejun Heo   blk-iocost: imple...
2893
  			ioc->vtime_base_rate * 10000,
97eb19751   Tejun Heo   blk-iocost: add a...
2894
2895
2896
2897
2898
2899
2900
  			VTIME_PER_USEC);
  		pos += scnprintf(buf + pos, size - pos, " cost.vrate=%u.%02u",
  				  vp10k / 100, vp10k % 100);
  	}
  
  	pos += scnprintf(buf + pos, size - pos, " cost.usage=%llu",
  			 iocg->last_stat.usage_us);
f0bf84a5d   Tejun Heo   blk-iocost: add t...
2901
2902
2903
2904
2905
2906
  	if (blkcg_debug_stats)
  		pos += scnprintf(buf + pos, size - pos,
  				 " cost.wait=%llu cost.indebt=%llu cost.indelay=%llu",
  				 iocg->last_stat.wait_us,
  				 iocg->last_stat.indebt_us,
  				 iocg->last_stat.indelay_us);
97eb19751   Tejun Heo   blk-iocost: add a...
2907
2908
  	return pos;
  }
7caa47151   Tejun Heo   blkcg: implement ...
2909
2910
2911
2912
2913
2914
2915
  static u64 ioc_weight_prfill(struct seq_file *sf, struct blkg_policy_data *pd,
  			     int off)
  {
  	const char *dname = blkg_dev_name(pd->blkg);
  	struct ioc_gq *iocg = pd_to_iocg(pd);
  
  	if (dname && iocg->cfg_weight)
bd0adb91a   Tejun Heo   blk-iocost: use W...
2916
2917
  		seq_printf(sf, "%s %u
  ", dname, iocg->cfg_weight / WEIGHT_ONE);
7caa47151   Tejun Heo   blkcg: implement ...
2918
2919
2920
2921
2922
2923
2924
2925
  	return 0;
  }
  
  
  static int ioc_weight_show(struct seq_file *sf, void *v)
  {
  	struct blkcg *blkcg = css_to_blkcg(seq_css(sf));
  	struct ioc_cgrp *iocc = blkcg_to_iocc(blkcg);
bd0adb91a   Tejun Heo   blk-iocost: use W...
2926
2927
  	seq_printf(sf, "default %u
  ", iocc->dfl_weight / WEIGHT_ONE);
7caa47151   Tejun Heo   blkcg: implement ...
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
  	blkcg_print_blkgs(sf, blkcg, ioc_weight_prfill,
  			  &blkcg_policy_iocost, seq_cft(sf)->private, false);
  	return 0;
  }
  
  static ssize_t ioc_weight_write(struct kernfs_open_file *of, char *buf,
  				size_t nbytes, loff_t off)
  {
  	struct blkcg *blkcg = css_to_blkcg(of_css(of));
  	struct ioc_cgrp *iocc = blkcg_to_iocc(blkcg);
  	struct blkg_conf_ctx ctx;
b0853ab4a   Tejun Heo   blk-iocost: revam...
2939
  	struct ioc_now now;
7caa47151   Tejun Heo   blkcg: implement ...
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
  	struct ioc_gq *iocg;
  	u32 v;
  	int ret;
  
  	if (!strchr(buf, ':')) {
  		struct blkcg_gq *blkg;
  
  		if (!sscanf(buf, "default %u", &v) && !sscanf(buf, "%u", &v))
  			return -EINVAL;
  
  		if (v < CGROUP_WEIGHT_MIN || v > CGROUP_WEIGHT_MAX)
  			return -EINVAL;
  
  		spin_lock(&blkcg->lock);
bd0adb91a   Tejun Heo   blk-iocost: use W...
2954
  		iocc->dfl_weight = v * WEIGHT_ONE;
7caa47151   Tejun Heo   blkcg: implement ...
2955
2956
2957
2958
2959
  		hlist_for_each_entry(blkg, &blkcg->blkg_list, blkcg_node) {
  			struct ioc_gq *iocg = blkg_to_iocg(blkg);
  
  			if (iocg) {
  				spin_lock_irq(&iocg->ioc->lock);
b0853ab4a   Tejun Heo   blk-iocost: revam...
2960
2961
  				ioc_now(iocg->ioc, &now);
  				weight_updated(iocg, &now);
7caa47151   Tejun Heo   blkcg: implement ...
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
  				spin_unlock_irq(&iocg->ioc->lock);
  			}
  		}
  		spin_unlock(&blkcg->lock);
  
  		return nbytes;
  	}
  
  	ret = blkg_conf_prep(blkcg, &blkcg_policy_iocost, buf, &ctx);
  	if (ret)
  		return ret;
  
  	iocg = blkg_to_iocg(ctx.blkg);
  
  	if (!strncmp(ctx.body, "default", 7)) {
  		v = 0;
  	} else {
  		if (!sscanf(ctx.body, "%u", &v))
  			goto einval;
  		if (v < CGROUP_WEIGHT_MIN || v > CGROUP_WEIGHT_MAX)
  			goto einval;
  	}
41591a51f   Dan Carpenter   iocost: don't nes...
2984
  	spin_lock(&iocg->ioc->lock);
bd0adb91a   Tejun Heo   blk-iocost: use W...
2985
  	iocg->cfg_weight = v * WEIGHT_ONE;
b0853ab4a   Tejun Heo   blk-iocost: revam...
2986
2987
  	ioc_now(iocg->ioc, &now);
  	weight_updated(iocg, &now);
41591a51f   Dan Carpenter   iocost: don't nes...
2988
  	spin_unlock(&iocg->ioc->lock);
7caa47151   Tejun Heo   blkcg: implement ...
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
  
  	blkg_conf_finish(&ctx);
  	return nbytes;
  
  einval:
  	blkg_conf_finish(&ctx);
  	return -EINVAL;
  }
  
  static u64 ioc_qos_prfill(struct seq_file *sf, struct blkg_policy_data *pd,
  			  int off)
  {
  	const char *dname = blkg_dev_name(pd->blkg);
  	struct ioc *ioc = pd_to_iocg(pd)->ioc;
  
  	if (!dname)
  		return 0;
  
  	seq_printf(sf, "%s enable=%d ctrl=%s rpct=%u.%02u rlat=%u wpct=%u.%02u wlat=%u min=%u.%02u max=%u.%02u
  ",
  		   dname, ioc->enabled, ioc->user_qos_params ? "user" : "auto",
  		   ioc->params.qos[QOS_RPPM] / 10000,
  		   ioc->params.qos[QOS_RPPM] % 10000 / 100,
  		   ioc->params.qos[QOS_RLAT],
  		   ioc->params.qos[QOS_WPPM] / 10000,
  		   ioc->params.qos[QOS_WPPM] % 10000 / 100,
  		   ioc->params.qos[QOS_WLAT],
  		   ioc->params.qos[QOS_MIN] / 10000,
  		   ioc->params.qos[QOS_MIN] % 10000 / 100,
  		   ioc->params.qos[QOS_MAX] / 10000,
  		   ioc->params.qos[QOS_MAX] % 10000 / 100);
  	return 0;
  }
  
  static int ioc_qos_show(struct seq_file *sf, void *v)
  {
  	struct blkcg *blkcg = css_to_blkcg(seq_css(sf));
  
  	blkcg_print_blkgs(sf, blkcg, ioc_qos_prfill,
  			  &blkcg_policy_iocost, seq_cft(sf)->private, false);
  	return 0;
  }
  
  static const match_table_t qos_ctrl_tokens = {
  	{ QOS_ENABLE,		"enable=%u"	},
  	{ QOS_CTRL,		"ctrl=%s"	},
  	{ NR_QOS_CTRL_PARAMS,	NULL		},
  };
  
  static const match_table_t qos_tokens = {
  	{ QOS_RPPM,		"rpct=%s"	},
  	{ QOS_RLAT,		"rlat=%u"	},
  	{ QOS_WPPM,		"wpct=%s"	},
  	{ QOS_WLAT,		"wlat=%u"	},
  	{ QOS_MIN,		"min=%s"	},
  	{ QOS_MAX,		"max=%s"	},
  	{ NR_QOS_PARAMS,	NULL		},
  };
  
  static ssize_t ioc_qos_write(struct kernfs_open_file *of, char *input,
  			     size_t nbytes, loff_t off)
  {
22ae8ce8b   Christoph Hellwig   block: simplify b...
3051
  	struct block_device *bdev;
7caa47151   Tejun Heo   blkcg: implement ...
3052
3053
3054
3055
3056
  	struct ioc *ioc;
  	u32 qos[NR_QOS_PARAMS];
  	bool enable, user;
  	char *p;
  	int ret;
22ae8ce8b   Christoph Hellwig   block: simplify b...
3057
3058
3059
  	bdev = blkcg_conf_open_bdev(&input);
  	if (IS_ERR(bdev))
  		return PTR_ERR(bdev);
7caa47151   Tejun Heo   blkcg: implement ...
3060

22ae8ce8b   Christoph Hellwig   block: simplify b...
3061
  	ioc = q_to_ioc(bdev->bd_disk->queue);
7caa47151   Tejun Heo   blkcg: implement ...
3062
  	if (!ioc) {
22ae8ce8b   Christoph Hellwig   block: simplify b...
3063
  		ret = blk_iocost_init(bdev->bd_disk->queue);
7caa47151   Tejun Heo   blkcg: implement ...
3064
3065
  		if (ret)
  			goto err;
22ae8ce8b   Christoph Hellwig   block: simplify b...
3066
  		ioc = q_to_ioc(bdev->bd_disk->queue);
7caa47151   Tejun Heo   blkcg: implement ...
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
  	}
  
  	spin_lock_irq(&ioc->lock);
  	memcpy(qos, ioc->params.qos, sizeof(qos));
  	enable = ioc->enabled;
  	user = ioc->user_qos_params;
  	spin_unlock_irq(&ioc->lock);
  
  	while ((p = strsep(&input, " \t
  "))) {
  		substring_t args[MAX_OPT_ARGS];
  		char buf[32];
  		int tok;
  		s64 v;
  
  		if (!*p)
  			continue;
  
  		switch (match_token(p, qos_ctrl_tokens, args)) {
  		case QOS_ENABLE:
  			match_u64(&args[0], &v);
  			enable = v;
  			continue;
  		case QOS_CTRL:
  			match_strlcpy(buf, &args[0], sizeof(buf));
  			if (!strcmp(buf, "auto"))
  				user = false;
  			else if (!strcmp(buf, "user"))
  				user = true;
  			else
  				goto einval;
  			continue;
  		}
  
  		tok = match_token(p, qos_tokens, args);
  		switch (tok) {
  		case QOS_RPPM:
  		case QOS_WPPM:
  			if (match_strlcpy(buf, &args[0], sizeof(buf)) >=
  			    sizeof(buf))
  				goto einval;
  			if (cgroup_parse_float(buf, 2, &v))
  				goto einval;
  			if (v < 0 || v > 10000)
  				goto einval;
  			qos[tok] = v * 100;
  			break;
  		case QOS_RLAT:
  		case QOS_WLAT:
  			if (match_u64(&args[0], &v))
  				goto einval;
  			qos[tok] = v;
  			break;
  		case QOS_MIN:
  		case QOS_MAX:
  			if (match_strlcpy(buf, &args[0], sizeof(buf)) >=
  			    sizeof(buf))
  				goto einval;
  			if (cgroup_parse_float(buf, 2, &v))
  				goto einval;
  			if (v < 0)
  				goto einval;
  			qos[tok] = clamp_t(s64, v * 100,
  					   VRATE_MIN_PPM, VRATE_MAX_PPM);
  			break;
  		default:
  			goto einval;
  		}
  		user = true;
  	}
  
  	if (qos[QOS_MIN] > qos[QOS_MAX])
  		goto einval;
  
  	spin_lock_irq(&ioc->lock);
  
  	if (enable) {
cd006509b   Tejun Heo   blk-iocost: accou...
3144
  		blk_stat_enable_accounting(ioc->rqos.q);
7caa47151   Tejun Heo   blkcg: implement ...
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
  		blk_queue_flag_set(QUEUE_FLAG_RQ_ALLOC_TIME, ioc->rqos.q);
  		ioc->enabled = true;
  	} else {
  		blk_queue_flag_clear(QUEUE_FLAG_RQ_ALLOC_TIME, ioc->rqos.q);
  		ioc->enabled = false;
  	}
  
  	if (user) {
  		memcpy(ioc->params.qos, qos, sizeof(qos));
  		ioc->user_qos_params = true;
  	} else {
  		ioc->user_qos_params = false;
  	}
  
  	ioc_refresh_params(ioc, true);
  	spin_unlock_irq(&ioc->lock);
22ae8ce8b   Christoph Hellwig   block: simplify b...
3161
  	blkdev_put_no_open(bdev);
7caa47151   Tejun Heo   blkcg: implement ...
3162
3163
3164
3165
  	return nbytes;
  einval:
  	ret = -EINVAL;
  err:
22ae8ce8b   Christoph Hellwig   block: simplify b...
3166
  	blkdev_put_no_open(bdev);
7caa47151   Tejun Heo   blkcg: implement ...
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
  	return ret;
  }
  
  static u64 ioc_cost_model_prfill(struct seq_file *sf,
  				 struct blkg_policy_data *pd, int off)
  {
  	const char *dname = blkg_dev_name(pd->blkg);
  	struct ioc *ioc = pd_to_iocg(pd)->ioc;
  	u64 *u = ioc->params.i_lcoefs;
  
  	if (!dname)
  		return 0;
  
  	seq_printf(sf, "%s ctrl=%s model=linear "
  		   "rbps=%llu rseqiops=%llu rrandiops=%llu "
  		   "wbps=%llu wseqiops=%llu wrandiops=%llu
  ",
  		   dname, ioc->user_cost_model ? "user" : "auto",
  		   u[I_LCOEF_RBPS], u[I_LCOEF_RSEQIOPS], u[I_LCOEF_RRANDIOPS],
  		   u[I_LCOEF_WBPS], u[I_LCOEF_WSEQIOPS], u[I_LCOEF_WRANDIOPS]);
  	return 0;
  }
  
  static int ioc_cost_model_show(struct seq_file *sf, void *v)
  {
  	struct blkcg *blkcg = css_to_blkcg(seq_css(sf));
  
  	blkcg_print_blkgs(sf, blkcg, ioc_cost_model_prfill,
  			  &blkcg_policy_iocost, seq_cft(sf)->private, false);
  	return 0;
  }
  
  static const match_table_t cost_ctrl_tokens = {
  	{ COST_CTRL,		"ctrl=%s"	},
  	{ COST_MODEL,		"model=%s"	},
  	{ NR_COST_CTRL_PARAMS,	NULL		},
  };
  
  static const match_table_t i_lcoef_tokens = {
  	{ I_LCOEF_RBPS,		"rbps=%u"	},
  	{ I_LCOEF_RSEQIOPS,	"rseqiops=%u"	},
  	{ I_LCOEF_RRANDIOPS,	"rrandiops=%u"	},
  	{ I_LCOEF_WBPS,		"wbps=%u"	},
  	{ I_LCOEF_WSEQIOPS,	"wseqiops=%u"	},
  	{ I_LCOEF_WRANDIOPS,	"wrandiops=%u"	},
  	{ NR_I_LCOEFS,		NULL		},
  };
  
  static ssize_t ioc_cost_model_write(struct kernfs_open_file *of, char *input,
  				    size_t nbytes, loff_t off)
  {
22ae8ce8b   Christoph Hellwig   block: simplify b...
3218
  	struct block_device *bdev;
7caa47151   Tejun Heo   blkcg: implement ...
3219
3220
3221
3222
3223
  	struct ioc *ioc;
  	u64 u[NR_I_LCOEFS];
  	bool user;
  	char *p;
  	int ret;
22ae8ce8b   Christoph Hellwig   block: simplify b...
3224
3225
3226
  	bdev = blkcg_conf_open_bdev(&input);
  	if (IS_ERR(bdev))
  		return PTR_ERR(bdev);
7caa47151   Tejun Heo   blkcg: implement ...
3227

22ae8ce8b   Christoph Hellwig   block: simplify b...
3228
  	ioc = q_to_ioc(bdev->bd_disk->queue);
7caa47151   Tejun Heo   blkcg: implement ...
3229
  	if (!ioc) {
22ae8ce8b   Christoph Hellwig   block: simplify b...
3230
  		ret = blk_iocost_init(bdev->bd_disk->queue);
7caa47151   Tejun Heo   blkcg: implement ...
3231
3232
  		if (ret)
  			goto err;
22ae8ce8b   Christoph Hellwig   block: simplify b...
3233
  		ioc = q_to_ioc(bdev->bd_disk->queue);
7caa47151   Tejun Heo   blkcg: implement ...
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
  	}
  
  	spin_lock_irq(&ioc->lock);
  	memcpy(u, ioc->params.i_lcoefs, sizeof(u));
  	user = ioc->user_cost_model;
  	spin_unlock_irq(&ioc->lock);
  
  	while ((p = strsep(&input, " \t
  "))) {
  		substring_t args[MAX_OPT_ARGS];
  		char buf[32];
  		int tok;
  		u64 v;
  
  		if (!*p)
  			continue;
  
  		switch (match_token(p, cost_ctrl_tokens, args)) {
  		case COST_CTRL:
  			match_strlcpy(buf, &args[0], sizeof(buf));
  			if (!strcmp(buf, "auto"))
  				user = false;
  			else if (!strcmp(buf, "user"))
  				user = true;
  			else
  				goto einval;
  			continue;
  		case COST_MODEL:
  			match_strlcpy(buf, &args[0], sizeof(buf));
  			if (strcmp(buf, "linear"))
  				goto einval;
  			continue;
  		}
  
  		tok = match_token(p, i_lcoef_tokens, args);
  		if (tok == NR_I_LCOEFS)
  			goto einval;
  		if (match_u64(&args[0], &v))
  			goto einval;
  		u[tok] = v;
  		user = true;
  	}
  
  	spin_lock_irq(&ioc->lock);
  	if (user) {
  		memcpy(ioc->params.i_lcoefs, u, sizeof(u));
  		ioc->user_cost_model = true;
  	} else {
  		ioc->user_cost_model = false;
  	}
  	ioc_refresh_params(ioc, true);
  	spin_unlock_irq(&ioc->lock);
22ae8ce8b   Christoph Hellwig   block: simplify b...
3286
  	blkdev_put_no_open(bdev);
7caa47151   Tejun Heo   blkcg: implement ...
3287
3288
3289
3290
3291
  	return nbytes;
  
  einval:
  	ret = -EINVAL;
  err:
22ae8ce8b   Christoph Hellwig   block: simplify b...
3292
  	blkdev_put_no_open(bdev);
7caa47151   Tejun Heo   blkcg: implement ...
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
  	return ret;
  }
  
  static struct cftype ioc_files[] = {
  	{
  		.name = "weight",
  		.flags = CFTYPE_NOT_ON_ROOT,
  		.seq_show = ioc_weight_show,
  		.write = ioc_weight_write,
  	},
  	{
  		.name = "cost.qos",
  		.flags = CFTYPE_ONLY_ON_ROOT,
  		.seq_show = ioc_qos_show,
  		.write = ioc_qos_write,
  	},
  	{
  		.name = "cost.model",
  		.flags = CFTYPE_ONLY_ON_ROOT,
  		.seq_show = ioc_cost_model_show,
  		.write = ioc_cost_model_write,
  	},
  	{}
  };
  
  static struct blkcg_policy blkcg_policy_iocost = {
  	.dfl_cftypes	= ioc_files,
  	.cpd_alloc_fn	= ioc_cpd_alloc,
  	.cpd_free_fn	= ioc_cpd_free,
  	.pd_alloc_fn	= ioc_pd_alloc,
  	.pd_init_fn	= ioc_pd_init,
  	.pd_free_fn	= ioc_pd_free,
97eb19751   Tejun Heo   blk-iocost: add a...
3325
  	.pd_stat_fn	= ioc_pd_stat,
7caa47151   Tejun Heo   blkcg: implement ...
3326
3327
3328
3329
3330
3331
3332
3333
3334
  };
  
  static int __init ioc_init(void)
  {
  	return blkcg_policy_register(&blkcg_policy_iocost);
  }
  
  static void __exit ioc_exit(void)
  {
fa1c3eaf4   Baolin Wang   block: Remove red...
3335
  	blkcg_policy_unregister(&blkcg_policy_iocost);
7caa47151   Tejun Heo   blkcg: implement ...
3336
3337
3338
3339
  }
  
  module_init(ioc_init);
  module_exit(ioc_exit);