• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Interface for controlling IO bandwidth on a request queue
4  *
5  * Copyright (C) 2010 Vivek Goyal <vgoyal@redhat.com>
6  */
7 
8 #include <linux/module.h>
9 #include <linux/slab.h>
10 #include <linux/blkdev.h>
11 #include <linux/bio.h>
12 #include <linux/blktrace_api.h>
13 #include <linux/blk-cgroup.h>
14 #include <linux/delay.h>
15 #include "blk.h"
16 #include "blk-cgroup-rwstat.h"
17 
18 /* Max dispatch from a group in 1 round */
19 #define THROTL_GRP_QUANTUM 8
20 
21 /* Total max dispatch from all groups in one round */
22 #define THROTL_QUANTUM 32
23 
24 /* Throttling is performed over a slice and after that slice is renewed */
25 #define DFL_THROTL_SLICE_HD (HZ / 10)
26 #define DFL_THROTL_SLICE_SSD (HZ / 50)
27 #define MAX_THROTL_SLICE (HZ)
28 #define MAX_IDLE_TIME (5L * 1000 * 1000) /* 5 s */
29 #define MIN_THROTL_BPS (320 * 1024)
30 #define MIN_THROTL_IOPS (10)
31 #define DFL_LATENCY_TARGET (-1L)
32 #define DFL_IDLE_THRESHOLD (0)
33 #define DFL_HD_BASELINE_LATENCY (4000L) /* 4ms */
34 #define LATENCY_FILTERED_SSD (0)
35 /*
36  * For HD, very small latency comes from sequential IO. Such IO is helpless to
37  * help determine if its IO is impacted by others, hence we ignore the IO
38  */
39 #define LATENCY_FILTERED_HD (1000L) /* 1ms */
40 
41 static struct blkcg_policy blkcg_policy_throtl;
42 
43 /* A workqueue to queue throttle related work */
44 static struct workqueue_struct *kthrotld_workqueue;
45 
46 /*
47  * To implement hierarchical throttling, throtl_grps form a tree and bios
48  * are dispatched upwards level by level until they reach the top and get
49  * issued.  When dispatching bios from the children and local group at each
50  * level, if the bios are dispatched into a single bio_list, there's a risk
51  * of a local or child group which can queue many bios at once filling up
52  * the list starving others.
53  *
54  * To avoid such starvation, dispatched bios are queued separately
55  * according to where they came from.  When they are again dispatched to
56  * the parent, they're popped in round-robin order so that no single source
57  * hogs the dispatch window.
58  *
59  * throtl_qnode is used to keep the queued bios separated by their sources.
60  * Bios are queued to throtl_qnode which in turn is queued to
61  * throtl_service_queue and then dispatched in round-robin order.
62  *
63  * It's also used to track the reference counts on blkg's.  A qnode always
64  * belongs to a throtl_grp and gets queued on itself or the parent, so
65  * incrementing the reference of the associated throtl_grp when a qnode is
66  * queued and decrementing when dequeued is enough to keep the whole blkg
67  * tree pinned while bios are in flight.
68  */
69 struct throtl_qnode {
70 	struct list_head	node;		/* service_queue->queued[] */
71 	struct bio_list		bios;		/* queued bios */
72 	struct throtl_grp	*tg;		/* tg this qnode belongs to */
73 };
74 
75 struct throtl_service_queue {
76 	struct throtl_service_queue *parent_sq;	/* the parent service_queue */
77 
78 	/*
79 	 * Bios queued directly to this service_queue or dispatched from
80 	 * children throtl_grp's.
81 	 */
82 	struct list_head	queued[2];	/* throtl_qnode [READ/WRITE] */
83 	unsigned int		nr_queued[2];	/* number of queued bios */
84 
85 	/*
86 	 * RB tree of active children throtl_grp's, which are sorted by
87 	 * their ->disptime.
88 	 */
89 	struct rb_root_cached	pending_tree;	/* RB tree of active tgs */
90 	unsigned int		nr_pending;	/* # queued in the tree */
91 	unsigned long		first_pending_disptime;	/* disptime of the first tg */
92 	struct timer_list	pending_timer;	/* fires on first_pending_disptime */
93 };
94 
95 enum tg_state_flags {
96 	THROTL_TG_PENDING	= 1 << 0,	/* on parent's pending tree */
97 	THROTL_TG_WAS_EMPTY	= 1 << 1,	/* bio_lists[] became non-empty */
98 };
99 
100 #define rb_entry_tg(node)	rb_entry((node), struct throtl_grp, rb_node)
101 
102 enum {
103 	LIMIT_LOW,
104 	LIMIT_MAX,
105 	LIMIT_CNT,
106 };
107 
108 struct throtl_grp {
109 	/* must be the first member */
110 	struct blkg_policy_data pd;
111 
112 	/* active throtl group service_queue member */
113 	struct rb_node rb_node;
114 
115 	/* throtl_data this group belongs to */
116 	struct throtl_data *td;
117 
118 	/* this group's service queue */
119 	struct throtl_service_queue service_queue;
120 
121 	/*
122 	 * qnode_on_self is used when bios are directly queued to this
123 	 * throtl_grp so that local bios compete fairly with bios
124 	 * dispatched from children.  qnode_on_parent is used when bios are
125 	 * dispatched from this throtl_grp into its parent and will compete
126 	 * with the sibling qnode_on_parents and the parent's
127 	 * qnode_on_self.
128 	 */
129 	struct throtl_qnode qnode_on_self[2];
130 	struct throtl_qnode qnode_on_parent[2];
131 
132 	/*
133 	 * Dispatch time in jiffies. This is the estimated time when group
134 	 * will unthrottle and is ready to dispatch more bio. It is used as
135 	 * key to sort active groups in service tree.
136 	 */
137 	unsigned long disptime;
138 
139 	unsigned int flags;
140 
141 	/* are there any throtl rules between this group and td? */
142 	bool has_rules[2];
143 
144 	/* internally used bytes per second rate limits */
145 	uint64_t bps[2][LIMIT_CNT];
146 	/* user configured bps limits */
147 	uint64_t bps_conf[2][LIMIT_CNT];
148 
149 	/* internally used IOPS limits */
150 	unsigned int iops[2][LIMIT_CNT];
151 	/* user configured IOPS limits */
152 	unsigned int iops_conf[2][LIMIT_CNT];
153 
154 	/* Number of bytes dispatched in current slice */
155 	uint64_t bytes_disp[2];
156 	/* Number of bio's dispatched in current slice */
157 	unsigned int io_disp[2];
158 
159 	unsigned long last_low_overflow_time[2];
160 
161 	uint64_t last_bytes_disp[2];
162 	unsigned int last_io_disp[2];
163 
164 	unsigned long last_check_time;
165 
166 	unsigned long latency_target; /* us */
167 	unsigned long latency_target_conf; /* us */
168 	/* When did we start a new slice */
169 	unsigned long slice_start[2];
170 	unsigned long slice_end[2];
171 
172 	unsigned long last_finish_time; /* ns / 1024 */
173 	unsigned long checked_last_finish_time; /* ns / 1024 */
174 	unsigned long avg_idletime; /* ns / 1024 */
175 	unsigned long idletime_threshold; /* us */
176 	unsigned long idletime_threshold_conf; /* us */
177 
178 	unsigned int bio_cnt; /* total bios */
179 	unsigned int bad_bio_cnt; /* bios exceeding latency threshold */
180 	unsigned long bio_cnt_reset_time;
181 
182 	atomic_t io_split_cnt[2];
183 	atomic_t last_io_split_cnt[2];
184 
185 	struct blkg_rwstat stat_bytes;
186 	struct blkg_rwstat stat_ios;
187 };
188 
189 /* We measure latency for request size from <= 4k to >= 1M */
190 #define LATENCY_BUCKET_SIZE 9
191 
192 struct latency_bucket {
193 	unsigned long total_latency; /* ns / 1024 */
194 	int samples;
195 };
196 
197 struct avg_latency_bucket {
198 	unsigned long latency; /* ns / 1024 */
199 	bool valid;
200 };
201 
202 struct throtl_data
203 {
204 	/* service tree for active throtl groups */
205 	struct throtl_service_queue service_queue;
206 
207 	struct request_queue *queue;
208 
209 	/* Total Number of queued bios on READ and WRITE lists */
210 	unsigned int nr_queued[2];
211 
212 	unsigned int throtl_slice;
213 
214 	/* Work for dispatching throttled bios */
215 	struct work_struct dispatch_work;
216 	unsigned int limit_index;
217 	bool limit_valid[LIMIT_CNT];
218 
219 	unsigned long low_upgrade_time;
220 	unsigned long low_downgrade_time;
221 
222 	unsigned int scale;
223 
224 	struct latency_bucket tmp_buckets[2][LATENCY_BUCKET_SIZE];
225 	struct avg_latency_bucket avg_buckets[2][LATENCY_BUCKET_SIZE];
226 	struct latency_bucket __percpu *latency_buckets[2];
227 	unsigned long last_calculate_time;
228 	unsigned long filtered_latency;
229 
230 	bool track_bio_latency;
231 };
232 
233 static void throtl_pending_timer_fn(struct timer_list *t);
234 
pd_to_tg(struct blkg_policy_data * pd)235 static inline struct throtl_grp *pd_to_tg(struct blkg_policy_data *pd)
236 {
237 	return pd ? container_of(pd, struct throtl_grp, pd) : NULL;
238 }
239 
blkg_to_tg(struct blkcg_gq * blkg)240 static inline struct throtl_grp *blkg_to_tg(struct blkcg_gq *blkg)
241 {
242 	return pd_to_tg(blkg_to_pd(blkg, &blkcg_policy_throtl));
243 }
244 
tg_to_blkg(struct throtl_grp * tg)245 static inline struct blkcg_gq *tg_to_blkg(struct throtl_grp *tg)
246 {
247 	return pd_to_blkg(&tg->pd);
248 }
249 
250 /**
251  * sq_to_tg - return the throl_grp the specified service queue belongs to
252  * @sq: the throtl_service_queue of interest
253  *
254  * Return the throtl_grp @sq belongs to.  If @sq is the top-level one
255  * embedded in throtl_data, %NULL is returned.
256  */
sq_to_tg(struct throtl_service_queue * sq)257 static struct throtl_grp *sq_to_tg(struct throtl_service_queue *sq)
258 {
259 	if (sq && sq->parent_sq)
260 		return container_of(sq, struct throtl_grp, service_queue);
261 	else
262 		return NULL;
263 }
264 
265 /**
266  * sq_to_td - return throtl_data the specified service queue belongs to
267  * @sq: the throtl_service_queue of interest
268  *
269  * A service_queue can be embedded in either a throtl_grp or throtl_data.
270  * Determine the associated throtl_data accordingly and return it.
271  */
sq_to_td(struct throtl_service_queue * sq)272 static struct throtl_data *sq_to_td(struct throtl_service_queue *sq)
273 {
274 	struct throtl_grp *tg = sq_to_tg(sq);
275 
276 	if (tg)
277 		return tg->td;
278 	else
279 		return container_of(sq, struct throtl_data, service_queue);
280 }
281 
282 /*
283  * cgroup's limit in LIMIT_MAX is scaled if low limit is set. This scale is to
284  * make the IO dispatch more smooth.
285  * Scale up: linearly scale up according to lapsed time since upgrade. For
286  *           every throtl_slice, the limit scales up 1/2 .low limit till the
287  *           limit hits .max limit
288  * Scale down: exponentially scale down if a cgroup doesn't hit its .low limit
289  */
throtl_adjusted_limit(uint64_t low,struct throtl_data * td)290 static uint64_t throtl_adjusted_limit(uint64_t low, struct throtl_data *td)
291 {
292 	/* arbitrary value to avoid too big scale */
293 	if (td->scale < 4096 && time_after_eq(jiffies,
294 	    td->low_upgrade_time + td->scale * td->throtl_slice))
295 		td->scale = (jiffies - td->low_upgrade_time) / td->throtl_slice;
296 
297 	return low + (low >> 1) * td->scale;
298 }
299 
tg_bps_limit(struct throtl_grp * tg,int rw)300 static uint64_t tg_bps_limit(struct throtl_grp *tg, int rw)
301 {
302 	struct blkcg_gq *blkg = tg_to_blkg(tg);
303 	struct throtl_data *td;
304 	uint64_t ret;
305 
306 	if (cgroup_subsys_on_dfl(io_cgrp_subsys) && !blkg->parent)
307 		return U64_MAX;
308 
309 	td = tg->td;
310 	ret = tg->bps[rw][td->limit_index];
311 	if (ret == 0 && td->limit_index == LIMIT_LOW) {
312 		/* intermediate node or iops isn't 0 */
313 		if (!list_empty(&blkg->blkcg->css.children) ||
314 		    tg->iops[rw][td->limit_index])
315 			return U64_MAX;
316 		else
317 			return MIN_THROTL_BPS;
318 	}
319 
320 	if (td->limit_index == LIMIT_MAX && tg->bps[rw][LIMIT_LOW] &&
321 	    tg->bps[rw][LIMIT_LOW] != tg->bps[rw][LIMIT_MAX]) {
322 		uint64_t adjusted;
323 
324 		adjusted = throtl_adjusted_limit(tg->bps[rw][LIMIT_LOW], td);
325 		ret = min(tg->bps[rw][LIMIT_MAX], adjusted);
326 	}
327 	return ret;
328 }
329 
tg_iops_limit(struct throtl_grp * tg,int rw)330 static unsigned int tg_iops_limit(struct throtl_grp *tg, int rw)
331 {
332 	struct blkcg_gq *blkg = tg_to_blkg(tg);
333 	struct throtl_data *td;
334 	unsigned int ret;
335 
336 	if (cgroup_subsys_on_dfl(io_cgrp_subsys) && !blkg->parent)
337 		return UINT_MAX;
338 
339 	td = tg->td;
340 	ret = tg->iops[rw][td->limit_index];
341 	if (ret == 0 && tg->td->limit_index == LIMIT_LOW) {
342 		/* intermediate node or bps isn't 0 */
343 		if (!list_empty(&blkg->blkcg->css.children) ||
344 		    tg->bps[rw][td->limit_index])
345 			return UINT_MAX;
346 		else
347 			return MIN_THROTL_IOPS;
348 	}
349 
350 	if (td->limit_index == LIMIT_MAX && tg->iops[rw][LIMIT_LOW] &&
351 	    tg->iops[rw][LIMIT_LOW] != tg->iops[rw][LIMIT_MAX]) {
352 		uint64_t adjusted;
353 
354 		adjusted = throtl_adjusted_limit(tg->iops[rw][LIMIT_LOW], td);
355 		if (adjusted > UINT_MAX)
356 			adjusted = UINT_MAX;
357 		ret = min_t(unsigned int, tg->iops[rw][LIMIT_MAX], adjusted);
358 	}
359 	return ret;
360 }
361 
362 #define request_bucket_index(sectors) \
363 	clamp_t(int, order_base_2(sectors) - 3, 0, LATENCY_BUCKET_SIZE - 1)
364 
365 /**
366  * throtl_log - log debug message via blktrace
367  * @sq: the service_queue being reported
368  * @fmt: printf format string
369  * @args: printf args
370  *
371  * The messages are prefixed with "throtl BLKG_NAME" if @sq belongs to a
372  * throtl_grp; otherwise, just "throtl".
373  */
374 #define throtl_log(sq, fmt, args...)	do {				\
375 	struct throtl_grp *__tg = sq_to_tg((sq));			\
376 	struct throtl_data *__td = sq_to_td((sq));			\
377 									\
378 	(void)__td;							\
379 	if (likely(!blk_trace_note_message_enabled(__td->queue)))	\
380 		break;							\
381 	if ((__tg)) {							\
382 		blk_add_cgroup_trace_msg(__td->queue,			\
383 			tg_to_blkg(__tg)->blkcg, "throtl " fmt, ##args);\
384 	} else {							\
385 		blk_add_trace_msg(__td->queue, "throtl " fmt, ##args);	\
386 	}								\
387 } while (0)
388 
throtl_bio_data_size(struct bio * bio)389 static inline unsigned int throtl_bio_data_size(struct bio *bio)
390 {
391 	/* assume it's one sector */
392 	if (unlikely(bio_op(bio) == REQ_OP_DISCARD))
393 		return 512;
394 	return bio->bi_iter.bi_size;
395 }
396 
throtl_qnode_init(struct throtl_qnode * qn,struct throtl_grp * tg)397 static void throtl_qnode_init(struct throtl_qnode *qn, struct throtl_grp *tg)
398 {
399 	INIT_LIST_HEAD(&qn->node);
400 	bio_list_init(&qn->bios);
401 	qn->tg = tg;
402 }
403 
404 /**
405  * throtl_qnode_add_bio - add a bio to a throtl_qnode and activate it
406  * @bio: bio being added
407  * @qn: qnode to add bio to
408  * @queued: the service_queue->queued[] list @qn belongs to
409  *
410  * Add @bio to @qn and put @qn on @queued if it's not already on.
411  * @qn->tg's reference count is bumped when @qn is activated.  See the
412  * comment on top of throtl_qnode definition for details.
413  */
throtl_qnode_add_bio(struct bio * bio,struct throtl_qnode * qn,struct list_head * queued)414 static void throtl_qnode_add_bio(struct bio *bio, struct throtl_qnode *qn,
415 				 struct list_head *queued)
416 {
417 	bio_list_add(&qn->bios, bio);
418 	if (list_empty(&qn->node)) {
419 		list_add_tail(&qn->node, queued);
420 		blkg_get(tg_to_blkg(qn->tg));
421 	}
422 }
423 
424 /**
425  * throtl_peek_queued - peek the first bio on a qnode list
426  * @queued: the qnode list to peek
427  */
throtl_peek_queued(struct list_head * queued)428 static struct bio *throtl_peek_queued(struct list_head *queued)
429 {
430 	struct throtl_qnode *qn;
431 	struct bio *bio;
432 
433 	if (list_empty(queued))
434 		return NULL;
435 
436 	qn = list_first_entry(queued, struct throtl_qnode, node);
437 	bio = bio_list_peek(&qn->bios);
438 	WARN_ON_ONCE(!bio);
439 	return bio;
440 }
441 
442 /**
443  * throtl_pop_queued - pop the first bio form a qnode list
444  * @queued: the qnode list to pop a bio from
445  * @tg_to_put: optional out argument for throtl_grp to put
446  *
447  * Pop the first bio from the qnode list @queued.  After popping, the first
448  * qnode is removed from @queued if empty or moved to the end of @queued so
449  * that the popping order is round-robin.
450  *
451  * When the first qnode is removed, its associated throtl_grp should be put
452  * too.  If @tg_to_put is NULL, this function automatically puts it;
453  * otherwise, *@tg_to_put is set to the throtl_grp to put and the caller is
454  * responsible for putting it.
455  */
throtl_pop_queued(struct list_head * queued,struct throtl_grp ** tg_to_put)456 static struct bio *throtl_pop_queued(struct list_head *queued,
457 				     struct throtl_grp **tg_to_put)
458 {
459 	struct throtl_qnode *qn;
460 	struct bio *bio;
461 
462 	if (list_empty(queued))
463 		return NULL;
464 
465 	qn = list_first_entry(queued, struct throtl_qnode, node);
466 	bio = bio_list_pop(&qn->bios);
467 	WARN_ON_ONCE(!bio);
468 
469 	if (bio_list_empty(&qn->bios)) {
470 		list_del_init(&qn->node);
471 		if (tg_to_put)
472 			*tg_to_put = qn->tg;
473 		else
474 			blkg_put(tg_to_blkg(qn->tg));
475 	} else {
476 		list_move_tail(&qn->node, queued);
477 	}
478 
479 	return bio;
480 }
481 
482 /* init a service_queue, assumes the caller zeroed it */
throtl_service_queue_init(struct throtl_service_queue * sq)483 static void throtl_service_queue_init(struct throtl_service_queue *sq)
484 {
485 	INIT_LIST_HEAD(&sq->queued[0]);
486 	INIT_LIST_HEAD(&sq->queued[1]);
487 	sq->pending_tree = RB_ROOT_CACHED;
488 	timer_setup(&sq->pending_timer, throtl_pending_timer_fn, 0);
489 }
490 
throtl_pd_alloc(gfp_t gfp,struct request_queue * q,struct blkcg * blkcg)491 static struct blkg_policy_data *throtl_pd_alloc(gfp_t gfp,
492 						struct request_queue *q,
493 						struct blkcg *blkcg)
494 {
495 	struct throtl_grp *tg;
496 	int rw;
497 
498 	tg = kzalloc_node(sizeof(*tg), gfp, q->node);
499 	if (!tg)
500 		return NULL;
501 
502 	if (blkg_rwstat_init(&tg->stat_bytes, gfp))
503 		goto err_free_tg;
504 
505 	if (blkg_rwstat_init(&tg->stat_ios, gfp))
506 		goto err_exit_stat_bytes;
507 
508 	throtl_service_queue_init(&tg->service_queue);
509 
510 	for (rw = READ; rw <= WRITE; rw++) {
511 		throtl_qnode_init(&tg->qnode_on_self[rw], tg);
512 		throtl_qnode_init(&tg->qnode_on_parent[rw], tg);
513 	}
514 
515 	RB_CLEAR_NODE(&tg->rb_node);
516 	tg->bps[READ][LIMIT_MAX] = U64_MAX;
517 	tg->bps[WRITE][LIMIT_MAX] = U64_MAX;
518 	tg->iops[READ][LIMIT_MAX] = UINT_MAX;
519 	tg->iops[WRITE][LIMIT_MAX] = UINT_MAX;
520 	tg->bps_conf[READ][LIMIT_MAX] = U64_MAX;
521 	tg->bps_conf[WRITE][LIMIT_MAX] = U64_MAX;
522 	tg->iops_conf[READ][LIMIT_MAX] = UINT_MAX;
523 	tg->iops_conf[WRITE][LIMIT_MAX] = UINT_MAX;
524 	/* LIMIT_LOW will have default value 0 */
525 
526 	tg->latency_target = DFL_LATENCY_TARGET;
527 	tg->latency_target_conf = DFL_LATENCY_TARGET;
528 	tg->idletime_threshold = DFL_IDLE_THRESHOLD;
529 	tg->idletime_threshold_conf = DFL_IDLE_THRESHOLD;
530 
531 	return &tg->pd;
532 
533 err_exit_stat_bytes:
534 	blkg_rwstat_exit(&tg->stat_bytes);
535 err_free_tg:
536 	kfree(tg);
537 	return NULL;
538 }
539 
throtl_pd_init(struct blkg_policy_data * pd)540 static void throtl_pd_init(struct blkg_policy_data *pd)
541 {
542 	struct throtl_grp *tg = pd_to_tg(pd);
543 	struct blkcg_gq *blkg = tg_to_blkg(tg);
544 	struct throtl_data *td = blkg->q->td;
545 	struct throtl_service_queue *sq = &tg->service_queue;
546 
547 	/*
548 	 * If on the default hierarchy, we switch to properly hierarchical
549 	 * behavior where limits on a given throtl_grp are applied to the
550 	 * whole subtree rather than just the group itself.  e.g. If 16M
551 	 * read_bps limit is set on the root group, the whole system can't
552 	 * exceed 16M for the device.
553 	 *
554 	 * If not on the default hierarchy, the broken flat hierarchy
555 	 * behavior is retained where all throtl_grps are treated as if
556 	 * they're all separate root groups right below throtl_data.
557 	 * Limits of a group don't interact with limits of other groups
558 	 * regardless of the position of the group in the hierarchy.
559 	 */
560 	sq->parent_sq = &td->service_queue;
561 	if (cgroup_subsys_on_dfl(io_cgrp_subsys) && blkg->parent)
562 		sq->parent_sq = &blkg_to_tg(blkg->parent)->service_queue;
563 	tg->td = td;
564 }
565 
566 /*
567  * Set has_rules[] if @tg or any of its parents have limits configured.
568  * This doesn't require walking up to the top of the hierarchy as the
569  * parent's has_rules[] is guaranteed to be correct.
570  */
tg_update_has_rules(struct throtl_grp * tg)571 static void tg_update_has_rules(struct throtl_grp *tg)
572 {
573 	struct throtl_grp *parent_tg = sq_to_tg(tg->service_queue.parent_sq);
574 	struct throtl_data *td = tg->td;
575 	int rw;
576 
577 	for (rw = READ; rw <= WRITE; rw++)
578 		tg->has_rules[rw] = (parent_tg && parent_tg->has_rules[rw]) ||
579 			(td->limit_valid[td->limit_index] &&
580 			 (tg_bps_limit(tg, rw) != U64_MAX ||
581 			  tg_iops_limit(tg, rw) != UINT_MAX));
582 }
583 
throtl_pd_online(struct blkg_policy_data * pd)584 static void throtl_pd_online(struct blkg_policy_data *pd)
585 {
586 	struct throtl_grp *tg = pd_to_tg(pd);
587 	/*
588 	 * We don't want new groups to escape the limits of its ancestors.
589 	 * Update has_rules[] after a new group is brought online.
590 	 */
591 	tg_update_has_rules(tg);
592 }
593 
blk_throtl_update_limit_valid(struct throtl_data * td)594 static void blk_throtl_update_limit_valid(struct throtl_data *td)
595 {
596 	struct cgroup_subsys_state *pos_css;
597 	struct blkcg_gq *blkg;
598 	bool low_valid = false;
599 
600 	rcu_read_lock();
601 	blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg) {
602 		struct throtl_grp *tg = blkg_to_tg(blkg);
603 
604 		if (tg->bps[READ][LIMIT_LOW] || tg->bps[WRITE][LIMIT_LOW] ||
605 		    tg->iops[READ][LIMIT_LOW] || tg->iops[WRITE][LIMIT_LOW]) {
606 			low_valid = true;
607 			break;
608 		}
609 	}
610 	rcu_read_unlock();
611 
612 	td->limit_valid[LIMIT_LOW] = low_valid;
613 }
614 
615 static void throtl_upgrade_state(struct throtl_data *td);
throtl_pd_offline(struct blkg_policy_data * pd)616 static void throtl_pd_offline(struct blkg_policy_data *pd)
617 {
618 	struct throtl_grp *tg = pd_to_tg(pd);
619 
620 	tg->bps[READ][LIMIT_LOW] = 0;
621 	tg->bps[WRITE][LIMIT_LOW] = 0;
622 	tg->iops[READ][LIMIT_LOW] = 0;
623 	tg->iops[WRITE][LIMIT_LOW] = 0;
624 
625 	blk_throtl_update_limit_valid(tg->td);
626 
627 	if (!tg->td->limit_valid[tg->td->limit_index])
628 		throtl_upgrade_state(tg->td);
629 }
630 
throtl_pd_free(struct blkg_policy_data * pd)631 static void throtl_pd_free(struct blkg_policy_data *pd)
632 {
633 	struct throtl_grp *tg = pd_to_tg(pd);
634 
635 	del_timer_sync(&tg->service_queue.pending_timer);
636 	blkg_rwstat_exit(&tg->stat_bytes);
637 	blkg_rwstat_exit(&tg->stat_ios);
638 	kfree(tg);
639 }
640 
641 static struct throtl_grp *
throtl_rb_first(struct throtl_service_queue * parent_sq)642 throtl_rb_first(struct throtl_service_queue *parent_sq)
643 {
644 	struct rb_node *n;
645 
646 	n = rb_first_cached(&parent_sq->pending_tree);
647 	WARN_ON_ONCE(!n);
648 	if (!n)
649 		return NULL;
650 	return rb_entry_tg(n);
651 }
652 
throtl_rb_erase(struct rb_node * n,struct throtl_service_queue * parent_sq)653 static void throtl_rb_erase(struct rb_node *n,
654 			    struct throtl_service_queue *parent_sq)
655 {
656 	rb_erase_cached(n, &parent_sq->pending_tree);
657 	RB_CLEAR_NODE(n);
658 	--parent_sq->nr_pending;
659 }
660 
update_min_dispatch_time(struct throtl_service_queue * parent_sq)661 static void update_min_dispatch_time(struct throtl_service_queue *parent_sq)
662 {
663 	struct throtl_grp *tg;
664 
665 	tg = throtl_rb_first(parent_sq);
666 	if (!tg)
667 		return;
668 
669 	parent_sq->first_pending_disptime = tg->disptime;
670 }
671 
tg_service_queue_add(struct throtl_grp * tg)672 static void tg_service_queue_add(struct throtl_grp *tg)
673 {
674 	struct throtl_service_queue *parent_sq = tg->service_queue.parent_sq;
675 	struct rb_node **node = &parent_sq->pending_tree.rb_root.rb_node;
676 	struct rb_node *parent = NULL;
677 	struct throtl_grp *__tg;
678 	unsigned long key = tg->disptime;
679 	bool leftmost = true;
680 
681 	while (*node != NULL) {
682 		parent = *node;
683 		__tg = rb_entry_tg(parent);
684 
685 		if (time_before(key, __tg->disptime))
686 			node = &parent->rb_left;
687 		else {
688 			node = &parent->rb_right;
689 			leftmost = false;
690 		}
691 	}
692 
693 	rb_link_node(&tg->rb_node, parent, node);
694 	rb_insert_color_cached(&tg->rb_node, &parent_sq->pending_tree,
695 			       leftmost);
696 }
697 
throtl_enqueue_tg(struct throtl_grp * tg)698 static void throtl_enqueue_tg(struct throtl_grp *tg)
699 {
700 	if (!(tg->flags & THROTL_TG_PENDING)) {
701 		tg_service_queue_add(tg);
702 		tg->flags |= THROTL_TG_PENDING;
703 		tg->service_queue.parent_sq->nr_pending++;
704 	}
705 }
706 
throtl_dequeue_tg(struct throtl_grp * tg)707 static void throtl_dequeue_tg(struct throtl_grp *tg)
708 {
709 	if (tg->flags & THROTL_TG_PENDING) {
710 		throtl_rb_erase(&tg->rb_node, tg->service_queue.parent_sq);
711 		tg->flags &= ~THROTL_TG_PENDING;
712 	}
713 }
714 
715 /* Call with queue lock held */
throtl_schedule_pending_timer(struct throtl_service_queue * sq,unsigned long expires)716 static void throtl_schedule_pending_timer(struct throtl_service_queue *sq,
717 					  unsigned long expires)
718 {
719 	unsigned long max_expire = jiffies + 8 * sq_to_td(sq)->throtl_slice;
720 
721 	/*
722 	 * Since we are adjusting the throttle limit dynamically, the sleep
723 	 * time calculated according to previous limit might be invalid. It's
724 	 * possible the cgroup sleep time is very long and no other cgroups
725 	 * have IO running so notify the limit changes. Make sure the cgroup
726 	 * doesn't sleep too long to avoid the missed notification.
727 	 */
728 	if (time_after(expires, max_expire))
729 		expires = max_expire;
730 	mod_timer(&sq->pending_timer, expires);
731 	throtl_log(sq, "schedule timer. delay=%lu jiffies=%lu",
732 		   expires - jiffies, jiffies);
733 }
734 
735 /**
736  * throtl_schedule_next_dispatch - schedule the next dispatch cycle
737  * @sq: the service_queue to schedule dispatch for
738  * @force: force scheduling
739  *
740  * Arm @sq->pending_timer so that the next dispatch cycle starts on the
741  * dispatch time of the first pending child.  Returns %true if either timer
742  * is armed or there's no pending child left.  %false if the current
743  * dispatch window is still open and the caller should continue
744  * dispatching.
745  *
746  * If @force is %true, the dispatch timer is always scheduled and this
747  * function is guaranteed to return %true.  This is to be used when the
748  * caller can't dispatch itself and needs to invoke pending_timer
749  * unconditionally.  Note that forced scheduling is likely to induce short
750  * delay before dispatch starts even if @sq->first_pending_disptime is not
751  * in the future and thus shouldn't be used in hot paths.
752  */
throtl_schedule_next_dispatch(struct throtl_service_queue * sq,bool force)753 static bool throtl_schedule_next_dispatch(struct throtl_service_queue *sq,
754 					  bool force)
755 {
756 	/* any pending children left? */
757 	if (!sq->nr_pending)
758 		return true;
759 
760 	update_min_dispatch_time(sq);
761 
762 	/* is the next dispatch time in the future? */
763 	if (force || time_after(sq->first_pending_disptime, jiffies)) {
764 		throtl_schedule_pending_timer(sq, sq->first_pending_disptime);
765 		return true;
766 	}
767 
768 	/* tell the caller to continue dispatching */
769 	return false;
770 }
771 
throtl_start_new_slice_with_credit(struct throtl_grp * tg,bool rw,unsigned long start)772 static inline void throtl_start_new_slice_with_credit(struct throtl_grp *tg,
773 		bool rw, unsigned long start)
774 {
775 	tg->bytes_disp[rw] = 0;
776 	tg->io_disp[rw] = 0;
777 
778 	atomic_set(&tg->io_split_cnt[rw], 0);
779 
780 	/*
781 	 * Previous slice has expired. We must have trimmed it after last
782 	 * bio dispatch. That means since start of last slice, we never used
783 	 * that bandwidth. Do try to make use of that bandwidth while giving
784 	 * credit.
785 	 */
786 	if (time_after_eq(start, tg->slice_start[rw]))
787 		tg->slice_start[rw] = start;
788 
789 	tg->slice_end[rw] = jiffies + tg->td->throtl_slice;
790 	throtl_log(&tg->service_queue,
791 		   "[%c] new slice with credit start=%lu end=%lu jiffies=%lu",
792 		   rw == READ ? 'R' : 'W', tg->slice_start[rw],
793 		   tg->slice_end[rw], jiffies);
794 }
795 
throtl_start_new_slice(struct throtl_grp * tg,bool rw)796 static inline void throtl_start_new_slice(struct throtl_grp *tg, bool rw)
797 {
798 	tg->bytes_disp[rw] = 0;
799 	tg->io_disp[rw] = 0;
800 	tg->slice_start[rw] = jiffies;
801 	tg->slice_end[rw] = jiffies + tg->td->throtl_slice;
802 
803 	atomic_set(&tg->io_split_cnt[rw], 0);
804 
805 	throtl_log(&tg->service_queue,
806 		   "[%c] new slice start=%lu end=%lu jiffies=%lu",
807 		   rw == READ ? 'R' : 'W', tg->slice_start[rw],
808 		   tg->slice_end[rw], jiffies);
809 }
810 
throtl_set_slice_end(struct throtl_grp * tg,bool rw,unsigned long jiffy_end)811 static inline void throtl_set_slice_end(struct throtl_grp *tg, bool rw,
812 					unsigned long jiffy_end)
813 {
814 	tg->slice_end[rw] = roundup(jiffy_end, tg->td->throtl_slice);
815 }
816 
throtl_extend_slice(struct throtl_grp * tg,bool rw,unsigned long jiffy_end)817 static inline void throtl_extend_slice(struct throtl_grp *tg, bool rw,
818 				       unsigned long jiffy_end)
819 {
820 	throtl_set_slice_end(tg, rw, jiffy_end);
821 	throtl_log(&tg->service_queue,
822 		   "[%c] extend slice start=%lu end=%lu jiffies=%lu",
823 		   rw == READ ? 'R' : 'W', tg->slice_start[rw],
824 		   tg->slice_end[rw], jiffies);
825 }
826 
827 /* Determine if previously allocated or extended slice is complete or not */
throtl_slice_used(struct throtl_grp * tg,bool rw)828 static bool throtl_slice_used(struct throtl_grp *tg, bool rw)
829 {
830 	if (time_in_range(jiffies, tg->slice_start[rw], tg->slice_end[rw]))
831 		return false;
832 
833 	return true;
834 }
835 
836 /* Trim the used slices and adjust slice start accordingly */
throtl_trim_slice(struct throtl_grp * tg,bool rw)837 static inline void throtl_trim_slice(struct throtl_grp *tg, bool rw)
838 {
839 	unsigned long nr_slices, time_elapsed, io_trim;
840 	u64 bytes_trim, tmp;
841 
842 	BUG_ON(time_before(tg->slice_end[rw], tg->slice_start[rw]));
843 
844 	/*
845 	 * If bps are unlimited (-1), then time slice don't get
846 	 * renewed. Don't try to trim the slice if slice is used. A new
847 	 * slice will start when appropriate.
848 	 */
849 	if (throtl_slice_used(tg, rw))
850 		return;
851 
852 	/*
853 	 * A bio has been dispatched. Also adjust slice_end. It might happen
854 	 * that initially cgroup limit was very low resulting in high
855 	 * slice_end, but later limit was bumped up and bio was dispatched
856 	 * sooner, then we need to reduce slice_end. A high bogus slice_end
857 	 * is bad because it does not allow new slice to start.
858 	 */
859 
860 	throtl_set_slice_end(tg, rw, jiffies + tg->td->throtl_slice);
861 
862 	time_elapsed = jiffies - tg->slice_start[rw];
863 
864 	nr_slices = time_elapsed / tg->td->throtl_slice;
865 
866 	if (!nr_slices)
867 		return;
868 	tmp = tg_bps_limit(tg, rw) * tg->td->throtl_slice * nr_slices;
869 	do_div(tmp, HZ);
870 	bytes_trim = tmp;
871 
872 	io_trim = (tg_iops_limit(tg, rw) * tg->td->throtl_slice * nr_slices) /
873 		HZ;
874 
875 	if (!bytes_trim && !io_trim)
876 		return;
877 
878 	if (tg->bytes_disp[rw] >= bytes_trim)
879 		tg->bytes_disp[rw] -= bytes_trim;
880 	else
881 		tg->bytes_disp[rw] = 0;
882 
883 	if (tg->io_disp[rw] >= io_trim)
884 		tg->io_disp[rw] -= io_trim;
885 	else
886 		tg->io_disp[rw] = 0;
887 
888 	tg->slice_start[rw] += nr_slices * tg->td->throtl_slice;
889 
890 	throtl_log(&tg->service_queue,
891 		   "[%c] trim slice nr=%lu bytes=%llu io=%lu start=%lu end=%lu jiffies=%lu",
892 		   rw == READ ? 'R' : 'W', nr_slices, bytes_trim, io_trim,
893 		   tg->slice_start[rw], tg->slice_end[rw], jiffies);
894 }
895 
tg_with_in_iops_limit(struct throtl_grp * tg,struct bio * bio,u32 iops_limit,unsigned long * wait)896 static bool tg_with_in_iops_limit(struct throtl_grp *tg, struct bio *bio,
897 				  u32 iops_limit, unsigned long *wait)
898 {
899 	bool rw = bio_data_dir(bio);
900 	unsigned int io_allowed;
901 	unsigned long jiffy_elapsed, jiffy_wait, jiffy_elapsed_rnd;
902 	u64 tmp;
903 
904 	if (iops_limit == UINT_MAX) {
905 		if (wait)
906 			*wait = 0;
907 		return true;
908 	}
909 
910 	jiffy_elapsed = jiffies - tg->slice_start[rw];
911 
912 	/* Round up to the next throttle slice, wait time must be nonzero */
913 	jiffy_elapsed_rnd = roundup(jiffy_elapsed + 1, tg->td->throtl_slice);
914 
915 	/*
916 	 * jiffy_elapsed_rnd should not be a big value as minimum iops can be
917 	 * 1 then at max jiffy elapsed should be equivalent of 1 second as we
918 	 * will allow dispatch after 1 second and after that slice should
919 	 * have been trimmed.
920 	 */
921 
922 	tmp = (u64)iops_limit * jiffy_elapsed_rnd;
923 	do_div(tmp, HZ);
924 
925 	if (tmp > UINT_MAX)
926 		io_allowed = UINT_MAX;
927 	else
928 		io_allowed = tmp;
929 
930 	if (tg->io_disp[rw] + 1 <= io_allowed) {
931 		if (wait)
932 			*wait = 0;
933 		return true;
934 	}
935 
936 	/* Calc approx time to dispatch */
937 	jiffy_wait = jiffy_elapsed_rnd - jiffy_elapsed;
938 
939 	if (wait)
940 		*wait = jiffy_wait;
941 	return false;
942 }
943 
tg_with_in_bps_limit(struct throtl_grp * tg,struct bio * bio,u64 bps_limit,unsigned long * wait)944 static bool tg_with_in_bps_limit(struct throtl_grp *tg, struct bio *bio,
945 				 u64 bps_limit, unsigned long *wait)
946 {
947 	bool rw = bio_data_dir(bio);
948 	u64 bytes_allowed, extra_bytes, tmp;
949 	unsigned long jiffy_elapsed, jiffy_wait, jiffy_elapsed_rnd;
950 	unsigned int bio_size = throtl_bio_data_size(bio);
951 
952 	if (bps_limit == U64_MAX) {
953 		if (wait)
954 			*wait = 0;
955 		return true;
956 	}
957 
958 	jiffy_elapsed = jiffy_elapsed_rnd = jiffies - tg->slice_start[rw];
959 
960 	/* Slice has just started. Consider one slice interval */
961 	if (!jiffy_elapsed)
962 		jiffy_elapsed_rnd = tg->td->throtl_slice;
963 
964 	jiffy_elapsed_rnd = roundup(jiffy_elapsed_rnd, tg->td->throtl_slice);
965 
966 	tmp = bps_limit * jiffy_elapsed_rnd;
967 	do_div(tmp, HZ);
968 	bytes_allowed = tmp;
969 
970 	if (tg->bytes_disp[rw] + bio_size <= bytes_allowed) {
971 		if (wait)
972 			*wait = 0;
973 		return true;
974 	}
975 
976 	/* Calc approx time to dispatch */
977 	extra_bytes = tg->bytes_disp[rw] + bio_size - bytes_allowed;
978 	jiffy_wait = div64_u64(extra_bytes * HZ, bps_limit);
979 
980 	if (!jiffy_wait)
981 		jiffy_wait = 1;
982 
983 	/*
984 	 * This wait time is without taking into consideration the rounding
985 	 * up we did. Add that time also.
986 	 */
987 	jiffy_wait = jiffy_wait + (jiffy_elapsed_rnd - jiffy_elapsed);
988 	if (wait)
989 		*wait = jiffy_wait;
990 	return false;
991 }
992 
993 /*
994  * Returns whether one can dispatch a bio or not. Also returns approx number
995  * of jiffies to wait before this bio is with-in IO rate and can be dispatched
996  */
tg_may_dispatch(struct throtl_grp * tg,struct bio * bio,unsigned long * wait)997 static bool tg_may_dispatch(struct throtl_grp *tg, struct bio *bio,
998 			    unsigned long *wait)
999 {
1000 	bool rw = bio_data_dir(bio);
1001 	unsigned long bps_wait = 0, iops_wait = 0, max_wait = 0;
1002 	u64 bps_limit = tg_bps_limit(tg, rw);
1003 	u32 iops_limit = tg_iops_limit(tg, rw);
1004 
1005 	/*
1006  	 * Currently whole state machine of group depends on first bio
1007 	 * queued in the group bio list. So one should not be calling
1008 	 * this function with a different bio if there are other bios
1009 	 * queued.
1010 	 */
1011 	BUG_ON(tg->service_queue.nr_queued[rw] &&
1012 	       bio != throtl_peek_queued(&tg->service_queue.queued[rw]));
1013 
1014 	/* If tg->bps = -1, then BW is unlimited */
1015 	if (bps_limit == U64_MAX && iops_limit == UINT_MAX) {
1016 		if (wait)
1017 			*wait = 0;
1018 		return true;
1019 	}
1020 
1021 	/*
1022 	 * If previous slice expired, start a new one otherwise renew/extend
1023 	 * existing slice to make sure it is at least throtl_slice interval
1024 	 * long since now. New slice is started only for empty throttle group.
1025 	 * If there is queued bio, that means there should be an active
1026 	 * slice and it should be extended instead.
1027 	 */
1028 	if (throtl_slice_used(tg, rw) && !(tg->service_queue.nr_queued[rw]))
1029 		throtl_start_new_slice(tg, rw);
1030 	else {
1031 		if (time_before(tg->slice_end[rw],
1032 		    jiffies + tg->td->throtl_slice))
1033 			throtl_extend_slice(tg, rw,
1034 				jiffies + tg->td->throtl_slice);
1035 	}
1036 
1037 	if (iops_limit != UINT_MAX)
1038 		tg->io_disp[rw] += atomic_xchg(&tg->io_split_cnt[rw], 0);
1039 
1040 	if (tg_with_in_bps_limit(tg, bio, bps_limit, &bps_wait) &&
1041 	    tg_with_in_iops_limit(tg, bio, iops_limit, &iops_wait)) {
1042 		if (wait)
1043 			*wait = 0;
1044 		return true;
1045 	}
1046 
1047 	max_wait = max(bps_wait, iops_wait);
1048 
1049 	if (wait)
1050 		*wait = max_wait;
1051 
1052 	if (time_before(tg->slice_end[rw], jiffies + max_wait))
1053 		throtl_extend_slice(tg, rw, jiffies + max_wait);
1054 
1055 	return false;
1056 }
1057 
throtl_charge_bio(struct throtl_grp * tg,struct bio * bio)1058 static void throtl_charge_bio(struct throtl_grp *tg, struct bio *bio)
1059 {
1060 	bool rw = bio_data_dir(bio);
1061 	unsigned int bio_size = throtl_bio_data_size(bio);
1062 
1063 	/* Charge the bio to the group */
1064 	tg->bytes_disp[rw] += bio_size;
1065 	tg->io_disp[rw]++;
1066 	tg->last_bytes_disp[rw] += bio_size;
1067 	tg->last_io_disp[rw]++;
1068 
1069 	/*
1070 	 * BIO_THROTTLED is used to prevent the same bio to be throttled
1071 	 * more than once as a throttled bio will go through blk-throtl the
1072 	 * second time when it eventually gets issued.  Set it when a bio
1073 	 * is being charged to a tg.
1074 	 */
1075 	if (!bio_flagged(bio, BIO_THROTTLED))
1076 		bio_set_flag(bio, BIO_THROTTLED);
1077 }
1078 
1079 /**
1080  * throtl_add_bio_tg - add a bio to the specified throtl_grp
1081  * @bio: bio to add
1082  * @qn: qnode to use
1083  * @tg: the target throtl_grp
1084  *
1085  * Add @bio to @tg's service_queue using @qn.  If @qn is not specified,
1086  * tg->qnode_on_self[] is used.
1087  */
throtl_add_bio_tg(struct bio * bio,struct throtl_qnode * qn,struct throtl_grp * tg)1088 static void throtl_add_bio_tg(struct bio *bio, struct throtl_qnode *qn,
1089 			      struct throtl_grp *tg)
1090 {
1091 	struct throtl_service_queue *sq = &tg->service_queue;
1092 	bool rw = bio_data_dir(bio);
1093 
1094 	if (!qn)
1095 		qn = &tg->qnode_on_self[rw];
1096 
1097 	/*
1098 	 * If @tg doesn't currently have any bios queued in the same
1099 	 * direction, queueing @bio can change when @tg should be
1100 	 * dispatched.  Mark that @tg was empty.  This is automatically
1101 	 * cleared on the next tg_update_disptime().
1102 	 */
1103 	if (!sq->nr_queued[rw])
1104 		tg->flags |= THROTL_TG_WAS_EMPTY;
1105 
1106 	throtl_qnode_add_bio(bio, qn, &sq->queued[rw]);
1107 
1108 	sq->nr_queued[rw]++;
1109 	throtl_enqueue_tg(tg);
1110 }
1111 
tg_update_disptime(struct throtl_grp * tg)1112 static void tg_update_disptime(struct throtl_grp *tg)
1113 {
1114 	struct throtl_service_queue *sq = &tg->service_queue;
1115 	unsigned long read_wait = -1, write_wait = -1, min_wait = -1, disptime;
1116 	struct bio *bio;
1117 
1118 	bio = throtl_peek_queued(&sq->queued[READ]);
1119 	if (bio)
1120 		tg_may_dispatch(tg, bio, &read_wait);
1121 
1122 	bio = throtl_peek_queued(&sq->queued[WRITE]);
1123 	if (bio)
1124 		tg_may_dispatch(tg, bio, &write_wait);
1125 
1126 	min_wait = min(read_wait, write_wait);
1127 	disptime = jiffies + min_wait;
1128 
1129 	/* Update dispatch time */
1130 	throtl_dequeue_tg(tg);
1131 	tg->disptime = disptime;
1132 	throtl_enqueue_tg(tg);
1133 
1134 	/* see throtl_add_bio_tg() */
1135 	tg->flags &= ~THROTL_TG_WAS_EMPTY;
1136 }
1137 
start_parent_slice_with_credit(struct throtl_grp * child_tg,struct throtl_grp * parent_tg,bool rw)1138 static void start_parent_slice_with_credit(struct throtl_grp *child_tg,
1139 					struct throtl_grp *parent_tg, bool rw)
1140 {
1141 	if (throtl_slice_used(parent_tg, rw)) {
1142 		throtl_start_new_slice_with_credit(parent_tg, rw,
1143 				child_tg->slice_start[rw]);
1144 	}
1145 
1146 }
1147 
tg_dispatch_one_bio(struct throtl_grp * tg,bool rw)1148 static void tg_dispatch_one_bio(struct throtl_grp *tg, bool rw)
1149 {
1150 	struct throtl_service_queue *sq = &tg->service_queue;
1151 	struct throtl_service_queue *parent_sq = sq->parent_sq;
1152 	struct throtl_grp *parent_tg = sq_to_tg(parent_sq);
1153 	struct throtl_grp *tg_to_put = NULL;
1154 	struct bio *bio;
1155 
1156 	/*
1157 	 * @bio is being transferred from @tg to @parent_sq.  Popping a bio
1158 	 * from @tg may put its reference and @parent_sq might end up
1159 	 * getting released prematurely.  Remember the tg to put and put it
1160 	 * after @bio is transferred to @parent_sq.
1161 	 */
1162 	bio = throtl_pop_queued(&sq->queued[rw], &tg_to_put);
1163 	sq->nr_queued[rw]--;
1164 
1165 	throtl_charge_bio(tg, bio);
1166 
1167 	/*
1168 	 * If our parent is another tg, we just need to transfer @bio to
1169 	 * the parent using throtl_add_bio_tg().  If our parent is
1170 	 * @td->service_queue, @bio is ready to be issued.  Put it on its
1171 	 * bio_lists[] and decrease total number queued.  The caller is
1172 	 * responsible for issuing these bios.
1173 	 */
1174 	if (parent_tg) {
1175 		throtl_add_bio_tg(bio, &tg->qnode_on_parent[rw], parent_tg);
1176 		start_parent_slice_with_credit(tg, parent_tg, rw);
1177 	} else {
1178 		throtl_qnode_add_bio(bio, &tg->qnode_on_parent[rw],
1179 				     &parent_sq->queued[rw]);
1180 		BUG_ON(tg->td->nr_queued[rw] <= 0);
1181 		tg->td->nr_queued[rw]--;
1182 	}
1183 
1184 	throtl_trim_slice(tg, rw);
1185 
1186 	if (tg_to_put)
1187 		blkg_put(tg_to_blkg(tg_to_put));
1188 }
1189 
throtl_dispatch_tg(struct throtl_grp * tg)1190 static int throtl_dispatch_tg(struct throtl_grp *tg)
1191 {
1192 	struct throtl_service_queue *sq = &tg->service_queue;
1193 	unsigned int nr_reads = 0, nr_writes = 0;
1194 	unsigned int max_nr_reads = THROTL_GRP_QUANTUM * 3 / 4;
1195 	unsigned int max_nr_writes = THROTL_GRP_QUANTUM - max_nr_reads;
1196 	struct bio *bio;
1197 
1198 	/* Try to dispatch 75% READS and 25% WRITES */
1199 
1200 	while ((bio = throtl_peek_queued(&sq->queued[READ])) &&
1201 	       tg_may_dispatch(tg, bio, NULL)) {
1202 
1203 		tg_dispatch_one_bio(tg, bio_data_dir(bio));
1204 		nr_reads++;
1205 
1206 		if (nr_reads >= max_nr_reads)
1207 			break;
1208 	}
1209 
1210 	while ((bio = throtl_peek_queued(&sq->queued[WRITE])) &&
1211 	       tg_may_dispatch(tg, bio, NULL)) {
1212 
1213 		tg_dispatch_one_bio(tg, bio_data_dir(bio));
1214 		nr_writes++;
1215 
1216 		if (nr_writes >= max_nr_writes)
1217 			break;
1218 	}
1219 
1220 	return nr_reads + nr_writes;
1221 }
1222 
throtl_select_dispatch(struct throtl_service_queue * parent_sq)1223 static int throtl_select_dispatch(struct throtl_service_queue *parent_sq)
1224 {
1225 	unsigned int nr_disp = 0;
1226 
1227 	while (1) {
1228 		struct throtl_grp *tg;
1229 		struct throtl_service_queue *sq;
1230 
1231 		if (!parent_sq->nr_pending)
1232 			break;
1233 
1234 		tg = throtl_rb_first(parent_sq);
1235 		if (!tg)
1236 			break;
1237 
1238 		if (time_before(jiffies, tg->disptime))
1239 			break;
1240 
1241 		throtl_dequeue_tg(tg);
1242 
1243 		nr_disp += throtl_dispatch_tg(tg);
1244 
1245 		sq = &tg->service_queue;
1246 		if (sq->nr_queued[0] || sq->nr_queued[1])
1247 			tg_update_disptime(tg);
1248 
1249 		if (nr_disp >= THROTL_QUANTUM)
1250 			break;
1251 	}
1252 
1253 	return nr_disp;
1254 }
1255 
1256 static bool throtl_can_upgrade(struct throtl_data *td,
1257 	struct throtl_grp *this_tg);
1258 /**
1259  * throtl_pending_timer_fn - timer function for service_queue->pending_timer
1260  * @t: the pending_timer member of the throtl_service_queue being serviced
1261  *
1262  * This timer is armed when a child throtl_grp with active bio's become
1263  * pending and queued on the service_queue's pending_tree and expires when
1264  * the first child throtl_grp should be dispatched.  This function
1265  * dispatches bio's from the children throtl_grps to the parent
1266  * service_queue.
1267  *
1268  * If the parent's parent is another throtl_grp, dispatching is propagated
1269  * by either arming its pending_timer or repeating dispatch directly.  If
1270  * the top-level service_tree is reached, throtl_data->dispatch_work is
1271  * kicked so that the ready bio's are issued.
1272  */
throtl_pending_timer_fn(struct timer_list * t)1273 static void throtl_pending_timer_fn(struct timer_list *t)
1274 {
1275 	struct throtl_service_queue *sq = from_timer(sq, t, pending_timer);
1276 	struct throtl_grp *tg = sq_to_tg(sq);
1277 	struct throtl_data *td = sq_to_td(sq);
1278 	struct request_queue *q = td->queue;
1279 	struct throtl_service_queue *parent_sq;
1280 	bool dispatched;
1281 	int ret;
1282 
1283 	spin_lock_irq(&q->queue_lock);
1284 	if (throtl_can_upgrade(td, NULL))
1285 		throtl_upgrade_state(td);
1286 
1287 again:
1288 	parent_sq = sq->parent_sq;
1289 	dispatched = false;
1290 
1291 	while (true) {
1292 		throtl_log(sq, "dispatch nr_queued=%u read=%u write=%u",
1293 			   sq->nr_queued[READ] + sq->nr_queued[WRITE],
1294 			   sq->nr_queued[READ], sq->nr_queued[WRITE]);
1295 
1296 		ret = throtl_select_dispatch(sq);
1297 		if (ret) {
1298 			throtl_log(sq, "bios disp=%u", ret);
1299 			dispatched = true;
1300 		}
1301 
1302 		if (throtl_schedule_next_dispatch(sq, false))
1303 			break;
1304 
1305 		/* this dispatch windows is still open, relax and repeat */
1306 		spin_unlock_irq(&q->queue_lock);
1307 		cpu_relax();
1308 		spin_lock_irq(&q->queue_lock);
1309 	}
1310 
1311 	if (!dispatched)
1312 		goto out_unlock;
1313 
1314 	if (parent_sq) {
1315 		/* @parent_sq is another throl_grp, propagate dispatch */
1316 		if (tg->flags & THROTL_TG_WAS_EMPTY) {
1317 			tg_update_disptime(tg);
1318 			if (!throtl_schedule_next_dispatch(parent_sq, false)) {
1319 				/* window is already open, repeat dispatching */
1320 				sq = parent_sq;
1321 				tg = sq_to_tg(sq);
1322 				goto again;
1323 			}
1324 		}
1325 	} else {
1326 		/* reached the top-level, queue issuing */
1327 		queue_work(kthrotld_workqueue, &td->dispatch_work);
1328 	}
1329 out_unlock:
1330 	spin_unlock_irq(&q->queue_lock);
1331 }
1332 
1333 /**
1334  * blk_throtl_dispatch_work_fn - work function for throtl_data->dispatch_work
1335  * @work: work item being executed
1336  *
1337  * This function is queued for execution when bios reach the bio_lists[]
1338  * of throtl_data->service_queue.  Those bios are ready and issued by this
1339  * function.
1340  */
blk_throtl_dispatch_work_fn(struct work_struct * work)1341 static void blk_throtl_dispatch_work_fn(struct work_struct *work)
1342 {
1343 	struct throtl_data *td = container_of(work, struct throtl_data,
1344 					      dispatch_work);
1345 	struct throtl_service_queue *td_sq = &td->service_queue;
1346 	struct request_queue *q = td->queue;
1347 	struct bio_list bio_list_on_stack;
1348 	struct bio *bio;
1349 	struct blk_plug plug;
1350 	int rw;
1351 
1352 	bio_list_init(&bio_list_on_stack);
1353 
1354 	spin_lock_irq(&q->queue_lock);
1355 	for (rw = READ; rw <= WRITE; rw++)
1356 		while ((bio = throtl_pop_queued(&td_sq->queued[rw], NULL)))
1357 			bio_list_add(&bio_list_on_stack, bio);
1358 	spin_unlock_irq(&q->queue_lock);
1359 
1360 	if (!bio_list_empty(&bio_list_on_stack)) {
1361 		blk_start_plug(&plug);
1362 		while ((bio = bio_list_pop(&bio_list_on_stack)))
1363 			submit_bio_noacct(bio);
1364 		blk_finish_plug(&plug);
1365 	}
1366 }
1367 
tg_prfill_conf_u64(struct seq_file * sf,struct blkg_policy_data * pd,int off)1368 static u64 tg_prfill_conf_u64(struct seq_file *sf, struct blkg_policy_data *pd,
1369 			      int off)
1370 {
1371 	struct throtl_grp *tg = pd_to_tg(pd);
1372 	u64 v = *(u64 *)((void *)tg + off);
1373 
1374 	if (v == U64_MAX)
1375 		return 0;
1376 	return __blkg_prfill_u64(sf, pd, v);
1377 }
1378 
tg_prfill_conf_uint(struct seq_file * sf,struct blkg_policy_data * pd,int off)1379 static u64 tg_prfill_conf_uint(struct seq_file *sf, struct blkg_policy_data *pd,
1380 			       int off)
1381 {
1382 	struct throtl_grp *tg = pd_to_tg(pd);
1383 	unsigned int v = *(unsigned int *)((void *)tg + off);
1384 
1385 	if (v == UINT_MAX)
1386 		return 0;
1387 	return __blkg_prfill_u64(sf, pd, v);
1388 }
1389 
tg_print_conf_u64(struct seq_file * sf,void * v)1390 static int tg_print_conf_u64(struct seq_file *sf, void *v)
1391 {
1392 	blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_conf_u64,
1393 			  &blkcg_policy_throtl, seq_cft(sf)->private, false);
1394 	return 0;
1395 }
1396 
tg_print_conf_uint(struct seq_file * sf,void * v)1397 static int tg_print_conf_uint(struct seq_file *sf, void *v)
1398 {
1399 	blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_conf_uint,
1400 			  &blkcg_policy_throtl, seq_cft(sf)->private, false);
1401 	return 0;
1402 }
1403 
tg_conf_updated(struct throtl_grp * tg,bool global)1404 static void tg_conf_updated(struct throtl_grp *tg, bool global)
1405 {
1406 	struct throtl_service_queue *sq = &tg->service_queue;
1407 	struct cgroup_subsys_state *pos_css;
1408 	struct blkcg_gq *blkg;
1409 
1410 	throtl_log(&tg->service_queue,
1411 		   "limit change rbps=%llu wbps=%llu riops=%u wiops=%u",
1412 		   tg_bps_limit(tg, READ), tg_bps_limit(tg, WRITE),
1413 		   tg_iops_limit(tg, READ), tg_iops_limit(tg, WRITE));
1414 
1415 	/*
1416 	 * Update has_rules[] flags for the updated tg's subtree.  A tg is
1417 	 * considered to have rules if either the tg itself or any of its
1418 	 * ancestors has rules.  This identifies groups without any
1419 	 * restrictions in the whole hierarchy and allows them to bypass
1420 	 * blk-throttle.
1421 	 */
1422 	blkg_for_each_descendant_pre(blkg, pos_css,
1423 			global ? tg->td->queue->root_blkg : tg_to_blkg(tg)) {
1424 		struct throtl_grp *this_tg = blkg_to_tg(blkg);
1425 		struct throtl_grp *parent_tg;
1426 
1427 		tg_update_has_rules(this_tg);
1428 		/* ignore root/second level */
1429 		if (!cgroup_subsys_on_dfl(io_cgrp_subsys) || !blkg->parent ||
1430 		    !blkg->parent->parent)
1431 			continue;
1432 		parent_tg = blkg_to_tg(blkg->parent);
1433 		/*
1434 		 * make sure all children has lower idle time threshold and
1435 		 * higher latency target
1436 		 */
1437 		this_tg->idletime_threshold = min(this_tg->idletime_threshold,
1438 				parent_tg->idletime_threshold);
1439 		this_tg->latency_target = max(this_tg->latency_target,
1440 				parent_tg->latency_target);
1441 	}
1442 
1443 	/*
1444 	 * We're already holding queue_lock and know @tg is valid.  Let's
1445 	 * apply the new config directly.
1446 	 *
1447 	 * Restart the slices for both READ and WRITES. It might happen
1448 	 * that a group's limit are dropped suddenly and we don't want to
1449 	 * account recently dispatched IO with new low rate.
1450 	 */
1451 	throtl_start_new_slice(tg, READ);
1452 	throtl_start_new_slice(tg, WRITE);
1453 
1454 	if (tg->flags & THROTL_TG_PENDING) {
1455 		tg_update_disptime(tg);
1456 		throtl_schedule_next_dispatch(sq->parent_sq, true);
1457 	}
1458 }
1459 
throtl_check_init_done(struct request_queue * q)1460 static inline int throtl_check_init_done(struct request_queue *q)
1461 {
1462 	if (test_bit(QUEUE_FLAG_THROTL_INIT_DONE, &q->queue_flags))
1463 		return 0;
1464 
1465 	return blk_queue_dying(q) ? -ENODEV : -EBUSY;
1466 }
1467 
1468 /*
1469  * If throtl_check_init_done() return -EBUSY, we should retry after a short
1470  * msleep(), since that throttle init will be completed in blk_register_queue()
1471  * soon.
1472  */
throtl_restart_syscall_when_busy(int errno)1473 static inline int throtl_restart_syscall_when_busy(int errno)
1474 {
1475 	int ret = errno;
1476 
1477 	if (ret == -EBUSY) {
1478 		msleep(10);
1479 		ret = restart_syscall();
1480 	}
1481 
1482 	return ret;
1483 }
1484 
tg_set_conf(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off,bool is_u64)1485 static ssize_t tg_set_conf(struct kernfs_open_file *of,
1486 			   char *buf, size_t nbytes, loff_t off, bool is_u64)
1487 {
1488 	struct blkcg *blkcg = css_to_blkcg(of_css(of));
1489 	struct blkg_conf_ctx ctx;
1490 	struct throtl_grp *tg;
1491 	int ret;
1492 	u64 v;
1493 
1494 	ret = blkg_conf_prep(blkcg, &blkcg_policy_throtl, buf, &ctx);
1495 	if (ret)
1496 		return ret;
1497 
1498 	ret = throtl_check_init_done(ctx.disk->queue);
1499 	if (ret)
1500 		goto out_finish;
1501 
1502 	ret = -EINVAL;
1503 	if (sscanf(ctx.body, "%llu", &v) != 1)
1504 		goto out_finish;
1505 	if (!v)
1506 		v = U64_MAX;
1507 
1508 	tg = blkg_to_tg(ctx.blkg);
1509 
1510 	if (is_u64)
1511 		*(u64 *)((void *)tg + of_cft(of)->private) = v;
1512 	else
1513 		*(unsigned int *)((void *)tg + of_cft(of)->private) = v;
1514 
1515 	tg_conf_updated(tg, false);
1516 	ret = 0;
1517 out_finish:
1518 	blkg_conf_finish(&ctx);
1519 	ret = throtl_restart_syscall_when_busy(ret);
1520 	return ret ?: nbytes;
1521 }
1522 
tg_set_conf_u64(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)1523 static ssize_t tg_set_conf_u64(struct kernfs_open_file *of,
1524 			       char *buf, size_t nbytes, loff_t off)
1525 {
1526 	return tg_set_conf(of, buf, nbytes, off, true);
1527 }
1528 
tg_set_conf_uint(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)1529 static ssize_t tg_set_conf_uint(struct kernfs_open_file *of,
1530 				char *buf, size_t nbytes, loff_t off)
1531 {
1532 	return tg_set_conf(of, buf, nbytes, off, false);
1533 }
1534 
tg_print_rwstat(struct seq_file * sf,void * v)1535 static int tg_print_rwstat(struct seq_file *sf, void *v)
1536 {
1537 	blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1538 			  blkg_prfill_rwstat, &blkcg_policy_throtl,
1539 			  seq_cft(sf)->private, true);
1540 	return 0;
1541 }
1542 
tg_prfill_rwstat_recursive(struct seq_file * sf,struct blkg_policy_data * pd,int off)1543 static u64 tg_prfill_rwstat_recursive(struct seq_file *sf,
1544 				      struct blkg_policy_data *pd, int off)
1545 {
1546 	struct blkg_rwstat_sample sum;
1547 
1548 	blkg_rwstat_recursive_sum(pd_to_blkg(pd), &blkcg_policy_throtl, off,
1549 				  &sum);
1550 	return __blkg_prfill_rwstat(sf, pd, &sum);
1551 }
1552 
tg_print_rwstat_recursive(struct seq_file * sf,void * v)1553 static int tg_print_rwstat_recursive(struct seq_file *sf, void *v)
1554 {
1555 	blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1556 			  tg_prfill_rwstat_recursive, &blkcg_policy_throtl,
1557 			  seq_cft(sf)->private, true);
1558 	return 0;
1559 }
1560 
1561 static struct cftype throtl_legacy_files[] = {
1562 	{
1563 		.name = "throttle.read_bps_device",
1564 		.private = offsetof(struct throtl_grp, bps[READ][LIMIT_MAX]),
1565 		.seq_show = tg_print_conf_u64,
1566 		.write = tg_set_conf_u64,
1567 	},
1568 	{
1569 		.name = "throttle.write_bps_device",
1570 		.private = offsetof(struct throtl_grp, bps[WRITE][LIMIT_MAX]),
1571 		.seq_show = tg_print_conf_u64,
1572 		.write = tg_set_conf_u64,
1573 	},
1574 	{
1575 		.name = "throttle.read_iops_device",
1576 		.private = offsetof(struct throtl_grp, iops[READ][LIMIT_MAX]),
1577 		.seq_show = tg_print_conf_uint,
1578 		.write = tg_set_conf_uint,
1579 	},
1580 	{
1581 		.name = "throttle.write_iops_device",
1582 		.private = offsetof(struct throtl_grp, iops[WRITE][LIMIT_MAX]),
1583 		.seq_show = tg_print_conf_uint,
1584 		.write = tg_set_conf_uint,
1585 	},
1586 	{
1587 		.name = "throttle.io_service_bytes",
1588 		.private = offsetof(struct throtl_grp, stat_bytes),
1589 		.seq_show = tg_print_rwstat,
1590 	},
1591 	{
1592 		.name = "throttle.io_service_bytes_recursive",
1593 		.private = offsetof(struct throtl_grp, stat_bytes),
1594 		.seq_show = tg_print_rwstat_recursive,
1595 	},
1596 	{
1597 		.name = "throttle.io_serviced",
1598 		.private = offsetof(struct throtl_grp, stat_ios),
1599 		.seq_show = tg_print_rwstat,
1600 	},
1601 	{
1602 		.name = "throttle.io_serviced_recursive",
1603 		.private = offsetof(struct throtl_grp, stat_ios),
1604 		.seq_show = tg_print_rwstat_recursive,
1605 	},
1606 	{ }	/* terminate */
1607 };
1608 
tg_prfill_limit(struct seq_file * sf,struct blkg_policy_data * pd,int off)1609 static u64 tg_prfill_limit(struct seq_file *sf, struct blkg_policy_data *pd,
1610 			 int off)
1611 {
1612 	struct throtl_grp *tg = pd_to_tg(pd);
1613 	const char *dname = blkg_dev_name(pd->blkg);
1614 	char bufs[4][21] = { "max", "max", "max", "max" };
1615 	u64 bps_dft;
1616 	unsigned int iops_dft;
1617 	char idle_time[26] = "";
1618 	char latency_time[26] = "";
1619 
1620 	if (!dname)
1621 		return 0;
1622 
1623 	if (off == LIMIT_LOW) {
1624 		bps_dft = 0;
1625 		iops_dft = 0;
1626 	} else {
1627 		bps_dft = U64_MAX;
1628 		iops_dft = UINT_MAX;
1629 	}
1630 
1631 	if (tg->bps_conf[READ][off] == bps_dft &&
1632 	    tg->bps_conf[WRITE][off] == bps_dft &&
1633 	    tg->iops_conf[READ][off] == iops_dft &&
1634 	    tg->iops_conf[WRITE][off] == iops_dft &&
1635 	    (off != LIMIT_LOW ||
1636 	     (tg->idletime_threshold_conf == DFL_IDLE_THRESHOLD &&
1637 	      tg->latency_target_conf == DFL_LATENCY_TARGET)))
1638 		return 0;
1639 
1640 	if (tg->bps_conf[READ][off] != U64_MAX)
1641 		snprintf(bufs[0], sizeof(bufs[0]), "%llu",
1642 			tg->bps_conf[READ][off]);
1643 	if (tg->bps_conf[WRITE][off] != U64_MAX)
1644 		snprintf(bufs[1], sizeof(bufs[1]), "%llu",
1645 			tg->bps_conf[WRITE][off]);
1646 	if (tg->iops_conf[READ][off] != UINT_MAX)
1647 		snprintf(bufs[2], sizeof(bufs[2]), "%u",
1648 			tg->iops_conf[READ][off]);
1649 	if (tg->iops_conf[WRITE][off] != UINT_MAX)
1650 		snprintf(bufs[3], sizeof(bufs[3]), "%u",
1651 			tg->iops_conf[WRITE][off]);
1652 	if (off == LIMIT_LOW) {
1653 		if (tg->idletime_threshold_conf == ULONG_MAX)
1654 			strcpy(idle_time, " idle=max");
1655 		else
1656 			snprintf(idle_time, sizeof(idle_time), " idle=%lu",
1657 				tg->idletime_threshold_conf);
1658 
1659 		if (tg->latency_target_conf == ULONG_MAX)
1660 			strcpy(latency_time, " latency=max");
1661 		else
1662 			snprintf(latency_time, sizeof(latency_time),
1663 				" latency=%lu", tg->latency_target_conf);
1664 	}
1665 
1666 	seq_printf(sf, "%s rbps=%s wbps=%s riops=%s wiops=%s%s%s\n",
1667 		   dname, bufs[0], bufs[1], bufs[2], bufs[3], idle_time,
1668 		   latency_time);
1669 	return 0;
1670 }
1671 
tg_print_limit(struct seq_file * sf,void * v)1672 static int tg_print_limit(struct seq_file *sf, void *v)
1673 {
1674 	blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), tg_prfill_limit,
1675 			  &blkcg_policy_throtl, seq_cft(sf)->private, false);
1676 	return 0;
1677 }
1678 
tg_set_limit(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)1679 static ssize_t tg_set_limit(struct kernfs_open_file *of,
1680 			  char *buf, size_t nbytes, loff_t off)
1681 {
1682 	struct blkcg *blkcg = css_to_blkcg(of_css(of));
1683 	struct blkg_conf_ctx ctx;
1684 	struct throtl_grp *tg;
1685 	u64 v[4];
1686 	unsigned long idle_time;
1687 	unsigned long latency_time;
1688 	int ret;
1689 	int index = of_cft(of)->private;
1690 
1691 	ret = blkg_conf_prep(blkcg, &blkcg_policy_throtl, buf, &ctx);
1692 	if (ret)
1693 		return ret;
1694 
1695 	ret = throtl_check_init_done(ctx.disk->queue);
1696 	if (ret)
1697 		goto out_finish;
1698 
1699 	tg = blkg_to_tg(ctx.blkg);
1700 	v[0] = tg->bps_conf[READ][index];
1701 	v[1] = tg->bps_conf[WRITE][index];
1702 	v[2] = tg->iops_conf[READ][index];
1703 	v[3] = tg->iops_conf[WRITE][index];
1704 
1705 	idle_time = tg->idletime_threshold_conf;
1706 	latency_time = tg->latency_target_conf;
1707 	while (true) {
1708 		char tok[27];	/* wiops=18446744073709551616 */
1709 		char *p;
1710 		u64 val = U64_MAX;
1711 		int len;
1712 
1713 		if (sscanf(ctx.body, "%26s%n", tok, &len) != 1)
1714 			break;
1715 		if (tok[0] == '\0')
1716 			break;
1717 		ctx.body += len;
1718 
1719 		ret = -EINVAL;
1720 		p = tok;
1721 		strsep(&p, "=");
1722 		if (!p || (sscanf(p, "%llu", &val) != 1 && strcmp(p, "max")))
1723 			goto out_finish;
1724 
1725 		ret = -ERANGE;
1726 		if (!val)
1727 			goto out_finish;
1728 
1729 		ret = -EINVAL;
1730 		if (!strcmp(tok, "rbps") && val > 1)
1731 			v[0] = val;
1732 		else if (!strcmp(tok, "wbps") && val > 1)
1733 			v[1] = val;
1734 		else if (!strcmp(tok, "riops") && val > 1)
1735 			v[2] = min_t(u64, val, UINT_MAX);
1736 		else if (!strcmp(tok, "wiops") && val > 1)
1737 			v[3] = min_t(u64, val, UINT_MAX);
1738 		else if (off == LIMIT_LOW && !strcmp(tok, "idle"))
1739 			idle_time = val;
1740 		else if (off == LIMIT_LOW && !strcmp(tok, "latency"))
1741 			latency_time = val;
1742 		else
1743 			goto out_finish;
1744 	}
1745 
1746 	tg->bps_conf[READ][index] = v[0];
1747 	tg->bps_conf[WRITE][index] = v[1];
1748 	tg->iops_conf[READ][index] = v[2];
1749 	tg->iops_conf[WRITE][index] = v[3];
1750 
1751 	if (index == LIMIT_MAX) {
1752 		tg->bps[READ][index] = v[0];
1753 		tg->bps[WRITE][index] = v[1];
1754 		tg->iops[READ][index] = v[2];
1755 		tg->iops[WRITE][index] = v[3];
1756 	}
1757 	tg->bps[READ][LIMIT_LOW] = min(tg->bps_conf[READ][LIMIT_LOW],
1758 		tg->bps_conf[READ][LIMIT_MAX]);
1759 	tg->bps[WRITE][LIMIT_LOW] = min(tg->bps_conf[WRITE][LIMIT_LOW],
1760 		tg->bps_conf[WRITE][LIMIT_MAX]);
1761 	tg->iops[READ][LIMIT_LOW] = min(tg->iops_conf[READ][LIMIT_LOW],
1762 		tg->iops_conf[READ][LIMIT_MAX]);
1763 	tg->iops[WRITE][LIMIT_LOW] = min(tg->iops_conf[WRITE][LIMIT_LOW],
1764 		tg->iops_conf[WRITE][LIMIT_MAX]);
1765 	tg->idletime_threshold_conf = idle_time;
1766 	tg->latency_target_conf = latency_time;
1767 
1768 	/* force user to configure all settings for low limit  */
1769 	if (!(tg->bps[READ][LIMIT_LOW] || tg->iops[READ][LIMIT_LOW] ||
1770 	      tg->bps[WRITE][LIMIT_LOW] || tg->iops[WRITE][LIMIT_LOW]) ||
1771 	    tg->idletime_threshold_conf == DFL_IDLE_THRESHOLD ||
1772 	    tg->latency_target_conf == DFL_LATENCY_TARGET) {
1773 		tg->bps[READ][LIMIT_LOW] = 0;
1774 		tg->bps[WRITE][LIMIT_LOW] = 0;
1775 		tg->iops[READ][LIMIT_LOW] = 0;
1776 		tg->iops[WRITE][LIMIT_LOW] = 0;
1777 		tg->idletime_threshold = DFL_IDLE_THRESHOLD;
1778 		tg->latency_target = DFL_LATENCY_TARGET;
1779 	} else if (index == LIMIT_LOW) {
1780 		tg->idletime_threshold = tg->idletime_threshold_conf;
1781 		tg->latency_target = tg->latency_target_conf;
1782 	}
1783 
1784 	blk_throtl_update_limit_valid(tg->td);
1785 	if (tg->td->limit_valid[LIMIT_LOW]) {
1786 		if (index == LIMIT_LOW)
1787 			tg->td->limit_index = LIMIT_LOW;
1788 	} else
1789 		tg->td->limit_index = LIMIT_MAX;
1790 	tg_conf_updated(tg, index == LIMIT_LOW &&
1791 		tg->td->limit_valid[LIMIT_LOW]);
1792 	ret = 0;
1793 out_finish:
1794 	blkg_conf_finish(&ctx);
1795 	ret = throtl_restart_syscall_when_busy(ret);
1796 	return ret ?: nbytes;
1797 }
1798 
1799 static struct cftype throtl_files[] = {
1800 #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
1801 	{
1802 		.name = "low",
1803 		.flags = CFTYPE_NOT_ON_ROOT,
1804 		.seq_show = tg_print_limit,
1805 		.write = tg_set_limit,
1806 		.private = LIMIT_LOW,
1807 	},
1808 #endif
1809 	{
1810 		.name = "max",
1811 		.flags = CFTYPE_NOT_ON_ROOT,
1812 		.seq_show = tg_print_limit,
1813 		.write = tg_set_limit,
1814 		.private = LIMIT_MAX,
1815 	},
1816 	{ }	/* terminate */
1817 };
1818 
throtl_shutdown_wq(struct request_queue * q)1819 static void throtl_shutdown_wq(struct request_queue *q)
1820 {
1821 	struct throtl_data *td = q->td;
1822 
1823 	cancel_work_sync(&td->dispatch_work);
1824 }
1825 
1826 static struct blkcg_policy blkcg_policy_throtl = {
1827 	.dfl_cftypes		= throtl_files,
1828 	.legacy_cftypes		= throtl_legacy_files,
1829 
1830 	.pd_alloc_fn		= throtl_pd_alloc,
1831 	.pd_init_fn		= throtl_pd_init,
1832 	.pd_online_fn		= throtl_pd_online,
1833 	.pd_offline_fn		= throtl_pd_offline,
1834 	.pd_free_fn		= throtl_pd_free,
1835 };
1836 
__tg_last_low_overflow_time(struct throtl_grp * tg)1837 static unsigned long __tg_last_low_overflow_time(struct throtl_grp *tg)
1838 {
1839 	unsigned long rtime = jiffies, wtime = jiffies;
1840 
1841 	if (tg->bps[READ][LIMIT_LOW] || tg->iops[READ][LIMIT_LOW])
1842 		rtime = tg->last_low_overflow_time[READ];
1843 	if (tg->bps[WRITE][LIMIT_LOW] || tg->iops[WRITE][LIMIT_LOW])
1844 		wtime = tg->last_low_overflow_time[WRITE];
1845 	return min(rtime, wtime);
1846 }
1847 
1848 /* tg should not be an intermediate node */
tg_last_low_overflow_time(struct throtl_grp * tg)1849 static unsigned long tg_last_low_overflow_time(struct throtl_grp *tg)
1850 {
1851 	struct throtl_service_queue *parent_sq;
1852 	struct throtl_grp *parent = tg;
1853 	unsigned long ret = __tg_last_low_overflow_time(tg);
1854 
1855 	while (true) {
1856 		parent_sq = parent->service_queue.parent_sq;
1857 		parent = sq_to_tg(parent_sq);
1858 		if (!parent)
1859 			break;
1860 
1861 		/*
1862 		 * The parent doesn't have low limit, it always reaches low
1863 		 * limit. Its overflow time is useless for children
1864 		 */
1865 		if (!parent->bps[READ][LIMIT_LOW] &&
1866 		    !parent->iops[READ][LIMIT_LOW] &&
1867 		    !parent->bps[WRITE][LIMIT_LOW] &&
1868 		    !parent->iops[WRITE][LIMIT_LOW])
1869 			continue;
1870 		if (time_after(__tg_last_low_overflow_time(parent), ret))
1871 			ret = __tg_last_low_overflow_time(parent);
1872 	}
1873 	return ret;
1874 }
1875 
throtl_tg_is_idle(struct throtl_grp * tg)1876 static bool throtl_tg_is_idle(struct throtl_grp *tg)
1877 {
1878 	/*
1879 	 * cgroup is idle if:
1880 	 * - single idle is too long, longer than a fixed value (in case user
1881 	 *   configure a too big threshold) or 4 times of idletime threshold
1882 	 * - average think time is more than threshold
1883 	 * - IO latency is largely below threshold
1884 	 */
1885 	unsigned long time;
1886 	bool ret;
1887 
1888 	time = min_t(unsigned long, MAX_IDLE_TIME, 4 * tg->idletime_threshold);
1889 	ret = tg->latency_target == DFL_LATENCY_TARGET ||
1890 	      tg->idletime_threshold == DFL_IDLE_THRESHOLD ||
1891 	      (ktime_get_ns() >> 10) - tg->last_finish_time > time ||
1892 	      tg->avg_idletime > tg->idletime_threshold ||
1893 	      (tg->latency_target && tg->bio_cnt &&
1894 		tg->bad_bio_cnt * 5 < tg->bio_cnt);
1895 	throtl_log(&tg->service_queue,
1896 		"avg_idle=%ld, idle_threshold=%ld, bad_bio=%d, total_bio=%d, is_idle=%d, scale=%d",
1897 		tg->avg_idletime, tg->idletime_threshold, tg->bad_bio_cnt,
1898 		tg->bio_cnt, ret, tg->td->scale);
1899 	return ret;
1900 }
1901 
throtl_tg_can_upgrade(struct throtl_grp * tg)1902 static bool throtl_tg_can_upgrade(struct throtl_grp *tg)
1903 {
1904 	struct throtl_service_queue *sq = &tg->service_queue;
1905 	bool read_limit, write_limit;
1906 
1907 	/*
1908 	 * if cgroup reaches low limit (if low limit is 0, the cgroup always
1909 	 * reaches), it's ok to upgrade to next limit
1910 	 */
1911 	read_limit = tg->bps[READ][LIMIT_LOW] || tg->iops[READ][LIMIT_LOW];
1912 	write_limit = tg->bps[WRITE][LIMIT_LOW] || tg->iops[WRITE][LIMIT_LOW];
1913 	if (!read_limit && !write_limit)
1914 		return true;
1915 	if (read_limit && sq->nr_queued[READ] &&
1916 	    (!write_limit || sq->nr_queued[WRITE]))
1917 		return true;
1918 	if (write_limit && sq->nr_queued[WRITE] &&
1919 	    (!read_limit || sq->nr_queued[READ]))
1920 		return true;
1921 
1922 	if (time_after_eq(jiffies,
1923 		tg_last_low_overflow_time(tg) + tg->td->throtl_slice) &&
1924 	    throtl_tg_is_idle(tg))
1925 		return true;
1926 	return false;
1927 }
1928 
throtl_hierarchy_can_upgrade(struct throtl_grp * tg)1929 static bool throtl_hierarchy_can_upgrade(struct throtl_grp *tg)
1930 {
1931 	while (true) {
1932 		if (throtl_tg_can_upgrade(tg))
1933 			return true;
1934 		tg = sq_to_tg(tg->service_queue.parent_sq);
1935 		if (!tg || !tg_to_blkg(tg)->parent)
1936 			return false;
1937 	}
1938 	return false;
1939 }
1940 
throtl_can_upgrade(struct throtl_data * td,struct throtl_grp * this_tg)1941 static bool throtl_can_upgrade(struct throtl_data *td,
1942 	struct throtl_grp *this_tg)
1943 {
1944 	struct cgroup_subsys_state *pos_css;
1945 	struct blkcg_gq *blkg;
1946 
1947 	if (td->limit_index != LIMIT_LOW)
1948 		return false;
1949 
1950 	if (time_before(jiffies, td->low_downgrade_time + td->throtl_slice))
1951 		return false;
1952 
1953 	rcu_read_lock();
1954 	blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg) {
1955 		struct throtl_grp *tg = blkg_to_tg(blkg);
1956 
1957 		if (tg == this_tg)
1958 			continue;
1959 		if (!list_empty(&tg_to_blkg(tg)->blkcg->css.children))
1960 			continue;
1961 		if (!throtl_hierarchy_can_upgrade(tg)) {
1962 			rcu_read_unlock();
1963 			return false;
1964 		}
1965 	}
1966 	rcu_read_unlock();
1967 	return true;
1968 }
1969 
throtl_upgrade_check(struct throtl_grp * tg)1970 static void throtl_upgrade_check(struct throtl_grp *tg)
1971 {
1972 	unsigned long now = jiffies;
1973 
1974 	if (tg->td->limit_index != LIMIT_LOW)
1975 		return;
1976 
1977 	if (time_after(tg->last_check_time + tg->td->throtl_slice, now))
1978 		return;
1979 
1980 	tg->last_check_time = now;
1981 
1982 	if (!time_after_eq(now,
1983 	     __tg_last_low_overflow_time(tg) + tg->td->throtl_slice))
1984 		return;
1985 
1986 	if (throtl_can_upgrade(tg->td, NULL))
1987 		throtl_upgrade_state(tg->td);
1988 }
1989 
throtl_upgrade_state(struct throtl_data * td)1990 static void throtl_upgrade_state(struct throtl_data *td)
1991 {
1992 	struct cgroup_subsys_state *pos_css;
1993 	struct blkcg_gq *blkg;
1994 
1995 	throtl_log(&td->service_queue, "upgrade to max");
1996 	td->limit_index = LIMIT_MAX;
1997 	td->low_upgrade_time = jiffies;
1998 	td->scale = 0;
1999 	rcu_read_lock();
2000 	blkg_for_each_descendant_post(blkg, pos_css, td->queue->root_blkg) {
2001 		struct throtl_grp *tg = blkg_to_tg(blkg);
2002 		struct throtl_service_queue *sq = &tg->service_queue;
2003 
2004 		tg->disptime = jiffies - 1;
2005 		throtl_select_dispatch(sq);
2006 		throtl_schedule_next_dispatch(sq, true);
2007 	}
2008 	rcu_read_unlock();
2009 	throtl_select_dispatch(&td->service_queue);
2010 	throtl_schedule_next_dispatch(&td->service_queue, true);
2011 	queue_work(kthrotld_workqueue, &td->dispatch_work);
2012 }
2013 
throtl_downgrade_state(struct throtl_data * td)2014 static void throtl_downgrade_state(struct throtl_data *td)
2015 {
2016 	td->scale /= 2;
2017 
2018 	throtl_log(&td->service_queue, "downgrade, scale %d", td->scale);
2019 	if (td->scale) {
2020 		td->low_upgrade_time = jiffies - td->scale * td->throtl_slice;
2021 		return;
2022 	}
2023 
2024 	td->limit_index = LIMIT_LOW;
2025 	td->low_downgrade_time = jiffies;
2026 }
2027 
throtl_tg_can_downgrade(struct throtl_grp * tg)2028 static bool throtl_tg_can_downgrade(struct throtl_grp *tg)
2029 {
2030 	struct throtl_data *td = tg->td;
2031 	unsigned long now = jiffies;
2032 
2033 	/*
2034 	 * If cgroup is below low limit, consider downgrade and throttle other
2035 	 * cgroups
2036 	 */
2037 	if (time_after_eq(now, td->low_upgrade_time + td->throtl_slice) &&
2038 	    time_after_eq(now, tg_last_low_overflow_time(tg) +
2039 					td->throtl_slice) &&
2040 	    (!throtl_tg_is_idle(tg) ||
2041 	     !list_empty(&tg_to_blkg(tg)->blkcg->css.children)))
2042 		return true;
2043 	return false;
2044 }
2045 
throtl_hierarchy_can_downgrade(struct throtl_grp * tg)2046 static bool throtl_hierarchy_can_downgrade(struct throtl_grp *tg)
2047 {
2048 	while (true) {
2049 		if (!throtl_tg_can_downgrade(tg))
2050 			return false;
2051 		tg = sq_to_tg(tg->service_queue.parent_sq);
2052 		if (!tg || !tg_to_blkg(tg)->parent)
2053 			break;
2054 	}
2055 	return true;
2056 }
2057 
throtl_downgrade_check(struct throtl_grp * tg)2058 static void throtl_downgrade_check(struct throtl_grp *tg)
2059 {
2060 	uint64_t bps;
2061 	unsigned int iops;
2062 	unsigned long elapsed_time;
2063 	unsigned long now = jiffies;
2064 
2065 	if (tg->td->limit_index != LIMIT_MAX ||
2066 	    !tg->td->limit_valid[LIMIT_LOW])
2067 		return;
2068 	if (!list_empty(&tg_to_blkg(tg)->blkcg->css.children))
2069 		return;
2070 	if (time_after(tg->last_check_time + tg->td->throtl_slice, now))
2071 		return;
2072 
2073 	elapsed_time = now - tg->last_check_time;
2074 	tg->last_check_time = now;
2075 
2076 	if (time_before(now, tg_last_low_overflow_time(tg) +
2077 			tg->td->throtl_slice))
2078 		return;
2079 
2080 	if (tg->bps[READ][LIMIT_LOW]) {
2081 		bps = tg->last_bytes_disp[READ] * HZ;
2082 		do_div(bps, elapsed_time);
2083 		if (bps >= tg->bps[READ][LIMIT_LOW])
2084 			tg->last_low_overflow_time[READ] = now;
2085 	}
2086 
2087 	if (tg->bps[WRITE][LIMIT_LOW]) {
2088 		bps = tg->last_bytes_disp[WRITE] * HZ;
2089 		do_div(bps, elapsed_time);
2090 		if (bps >= tg->bps[WRITE][LIMIT_LOW])
2091 			tg->last_low_overflow_time[WRITE] = now;
2092 	}
2093 
2094 	if (tg->iops[READ][LIMIT_LOW]) {
2095 		tg->last_io_disp[READ] += atomic_xchg(&tg->last_io_split_cnt[READ], 0);
2096 		iops = tg->last_io_disp[READ] * HZ / elapsed_time;
2097 		if (iops >= tg->iops[READ][LIMIT_LOW])
2098 			tg->last_low_overflow_time[READ] = now;
2099 	}
2100 
2101 	if (tg->iops[WRITE][LIMIT_LOW]) {
2102 		tg->last_io_disp[WRITE] += atomic_xchg(&tg->last_io_split_cnt[WRITE], 0);
2103 		iops = tg->last_io_disp[WRITE] * HZ / elapsed_time;
2104 		if (iops >= tg->iops[WRITE][LIMIT_LOW])
2105 			tg->last_low_overflow_time[WRITE] = now;
2106 	}
2107 
2108 	/*
2109 	 * If cgroup is below low limit, consider downgrade and throttle other
2110 	 * cgroups
2111 	 */
2112 	if (throtl_hierarchy_can_downgrade(tg))
2113 		throtl_downgrade_state(tg->td);
2114 
2115 	tg->last_bytes_disp[READ] = 0;
2116 	tg->last_bytes_disp[WRITE] = 0;
2117 	tg->last_io_disp[READ] = 0;
2118 	tg->last_io_disp[WRITE] = 0;
2119 }
2120 
blk_throtl_update_idletime(struct throtl_grp * tg)2121 static void blk_throtl_update_idletime(struct throtl_grp *tg)
2122 {
2123 	unsigned long now;
2124 	unsigned long last_finish_time = tg->last_finish_time;
2125 
2126 	if (last_finish_time == 0)
2127 		return;
2128 
2129 	now = ktime_get_ns() >> 10;
2130 	if (now <= last_finish_time ||
2131 	    last_finish_time == tg->checked_last_finish_time)
2132 		return;
2133 
2134 	tg->avg_idletime = (tg->avg_idletime * 7 + now - last_finish_time) >> 3;
2135 	tg->checked_last_finish_time = last_finish_time;
2136 }
2137 
2138 #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
throtl_update_latency_buckets(struct throtl_data * td)2139 static void throtl_update_latency_buckets(struct throtl_data *td)
2140 {
2141 	struct avg_latency_bucket avg_latency[2][LATENCY_BUCKET_SIZE];
2142 	int i, cpu, rw;
2143 	unsigned long last_latency[2] = { 0 };
2144 	unsigned long latency[2];
2145 
2146 	if (!blk_queue_nonrot(td->queue) || !td->limit_valid[LIMIT_LOW])
2147 		return;
2148 	if (time_before(jiffies, td->last_calculate_time + HZ))
2149 		return;
2150 	td->last_calculate_time = jiffies;
2151 
2152 	memset(avg_latency, 0, sizeof(avg_latency));
2153 	for (rw = READ; rw <= WRITE; rw++) {
2154 		for (i = 0; i < LATENCY_BUCKET_SIZE; i++) {
2155 			struct latency_bucket *tmp = &td->tmp_buckets[rw][i];
2156 
2157 			for_each_possible_cpu(cpu) {
2158 				struct latency_bucket *bucket;
2159 
2160 				/* this isn't race free, but ok in practice */
2161 				bucket = per_cpu_ptr(td->latency_buckets[rw],
2162 					cpu);
2163 				tmp->total_latency += bucket[i].total_latency;
2164 				tmp->samples += bucket[i].samples;
2165 				bucket[i].total_latency = 0;
2166 				bucket[i].samples = 0;
2167 			}
2168 
2169 			if (tmp->samples >= 32) {
2170 				int samples = tmp->samples;
2171 
2172 				latency[rw] = tmp->total_latency;
2173 
2174 				tmp->total_latency = 0;
2175 				tmp->samples = 0;
2176 				latency[rw] /= samples;
2177 				if (latency[rw] == 0)
2178 					continue;
2179 				avg_latency[rw][i].latency = latency[rw];
2180 			}
2181 		}
2182 	}
2183 
2184 	for (rw = READ; rw <= WRITE; rw++) {
2185 		for (i = 0; i < LATENCY_BUCKET_SIZE; i++) {
2186 			if (!avg_latency[rw][i].latency) {
2187 				if (td->avg_buckets[rw][i].latency < last_latency[rw])
2188 					td->avg_buckets[rw][i].latency =
2189 						last_latency[rw];
2190 				continue;
2191 			}
2192 
2193 			if (!td->avg_buckets[rw][i].valid)
2194 				latency[rw] = avg_latency[rw][i].latency;
2195 			else
2196 				latency[rw] = (td->avg_buckets[rw][i].latency * 7 +
2197 					avg_latency[rw][i].latency) >> 3;
2198 
2199 			td->avg_buckets[rw][i].latency = max(latency[rw],
2200 				last_latency[rw]);
2201 			td->avg_buckets[rw][i].valid = true;
2202 			last_latency[rw] = td->avg_buckets[rw][i].latency;
2203 		}
2204 	}
2205 
2206 	for (i = 0; i < LATENCY_BUCKET_SIZE; i++)
2207 		throtl_log(&td->service_queue,
2208 			"Latency bucket %d: read latency=%ld, read valid=%d, "
2209 			"write latency=%ld, write valid=%d", i,
2210 			td->avg_buckets[READ][i].latency,
2211 			td->avg_buckets[READ][i].valid,
2212 			td->avg_buckets[WRITE][i].latency,
2213 			td->avg_buckets[WRITE][i].valid);
2214 }
2215 #else
throtl_update_latency_buckets(struct throtl_data * td)2216 static inline void throtl_update_latency_buckets(struct throtl_data *td)
2217 {
2218 }
2219 #endif
2220 
blk_throtl_charge_bio_split(struct bio * bio)2221 void blk_throtl_charge_bio_split(struct bio *bio)
2222 {
2223 	struct blkcg_gq *blkg = bio->bi_blkg;
2224 	struct throtl_grp *parent = blkg_to_tg(blkg);
2225 	struct throtl_service_queue *parent_sq;
2226 	bool rw = bio_data_dir(bio);
2227 
2228 	do {
2229 		if (!parent->has_rules[rw])
2230 			break;
2231 
2232 		atomic_inc(&parent->io_split_cnt[rw]);
2233 		atomic_inc(&parent->last_io_split_cnt[rw]);
2234 
2235 		parent_sq = parent->service_queue.parent_sq;
2236 		parent = sq_to_tg(parent_sq);
2237 	} while (parent);
2238 }
2239 
blk_throtl_bio(struct bio * bio)2240 bool blk_throtl_bio(struct bio *bio)
2241 {
2242 	struct request_queue *q = bio->bi_disk->queue;
2243 	struct blkcg_gq *blkg = bio->bi_blkg;
2244 	struct throtl_qnode *qn = NULL;
2245 	struct throtl_grp *tg = blkg_to_tg(blkg);
2246 	struct throtl_service_queue *sq;
2247 	bool rw = bio_data_dir(bio);
2248 	bool throttled = false;
2249 	struct throtl_data *td = tg->td;
2250 
2251 	rcu_read_lock();
2252 
2253 	/* see throtl_charge_bio() */
2254 	if (bio_flagged(bio, BIO_THROTTLED))
2255 		goto out;
2256 
2257 	if (!cgroup_subsys_on_dfl(io_cgrp_subsys)) {
2258 		blkg_rwstat_add(&tg->stat_bytes, bio->bi_opf,
2259 				bio->bi_iter.bi_size);
2260 		blkg_rwstat_add(&tg->stat_ios, bio->bi_opf, 1);
2261 	}
2262 
2263 	if (!tg->has_rules[rw])
2264 		goto out;
2265 
2266 	spin_lock_irq(&q->queue_lock);
2267 
2268 	throtl_update_latency_buckets(td);
2269 
2270 	blk_throtl_update_idletime(tg);
2271 
2272 	sq = &tg->service_queue;
2273 
2274 again:
2275 	while (true) {
2276 		if (tg->last_low_overflow_time[rw] == 0)
2277 			tg->last_low_overflow_time[rw] = jiffies;
2278 		throtl_downgrade_check(tg);
2279 		throtl_upgrade_check(tg);
2280 		/* throtl is FIFO - if bios are already queued, should queue */
2281 		if (sq->nr_queued[rw])
2282 			break;
2283 
2284 		/* if above limits, break to queue */
2285 		if (!tg_may_dispatch(tg, bio, NULL)) {
2286 			tg->last_low_overflow_time[rw] = jiffies;
2287 			if (throtl_can_upgrade(td, tg)) {
2288 				throtl_upgrade_state(td);
2289 				goto again;
2290 			}
2291 			break;
2292 		}
2293 
2294 		/* within limits, let's charge and dispatch directly */
2295 		throtl_charge_bio(tg, bio);
2296 
2297 		/*
2298 		 * We need to trim slice even when bios are not being queued
2299 		 * otherwise it might happen that a bio is not queued for
2300 		 * a long time and slice keeps on extending and trim is not
2301 		 * called for a long time. Now if limits are reduced suddenly
2302 		 * we take into account all the IO dispatched so far at new
2303 		 * low rate and * newly queued IO gets a really long dispatch
2304 		 * time.
2305 		 *
2306 		 * So keep on trimming slice even if bio is not queued.
2307 		 */
2308 		throtl_trim_slice(tg, rw);
2309 
2310 		/*
2311 		 * @bio passed through this layer without being throttled.
2312 		 * Climb up the ladder.  If we're already at the top, it
2313 		 * can be executed directly.
2314 		 */
2315 		qn = &tg->qnode_on_parent[rw];
2316 		sq = sq->parent_sq;
2317 		tg = sq_to_tg(sq);
2318 		if (!tg)
2319 			goto out_unlock;
2320 	}
2321 
2322 	/* out-of-limit, queue to @tg */
2323 	throtl_log(sq, "[%c] bio. bdisp=%llu sz=%u bps=%llu iodisp=%u iops=%u queued=%d/%d",
2324 		   rw == READ ? 'R' : 'W',
2325 		   tg->bytes_disp[rw], bio->bi_iter.bi_size,
2326 		   tg_bps_limit(tg, rw),
2327 		   tg->io_disp[rw], tg_iops_limit(tg, rw),
2328 		   sq->nr_queued[READ], sq->nr_queued[WRITE]);
2329 
2330 	tg->last_low_overflow_time[rw] = jiffies;
2331 
2332 	td->nr_queued[rw]++;
2333 	throtl_add_bio_tg(bio, qn, tg);
2334 	throttled = true;
2335 
2336 	/*
2337 	 * Update @tg's dispatch time and force schedule dispatch if @tg
2338 	 * was empty before @bio.  The forced scheduling isn't likely to
2339 	 * cause undue delay as @bio is likely to be dispatched directly if
2340 	 * its @tg's disptime is not in the future.
2341 	 */
2342 	if (tg->flags & THROTL_TG_WAS_EMPTY) {
2343 		tg_update_disptime(tg);
2344 		throtl_schedule_next_dispatch(tg->service_queue.parent_sq, true);
2345 	}
2346 
2347 out_unlock:
2348 	spin_unlock_irq(&q->queue_lock);
2349 out:
2350 	bio_set_flag(bio, BIO_THROTTLED);
2351 
2352 #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
2353 	if (throttled || !td->track_bio_latency)
2354 		bio->bi_issue.value |= BIO_ISSUE_THROTL_SKIP_LATENCY;
2355 #endif
2356 	rcu_read_unlock();
2357 	return throttled;
2358 }
2359 
2360 #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
throtl_track_latency(struct throtl_data * td,sector_t size,int op,unsigned long time)2361 static void throtl_track_latency(struct throtl_data *td, sector_t size,
2362 	int op, unsigned long time)
2363 {
2364 	struct latency_bucket *latency;
2365 	int index;
2366 
2367 	if (!td || td->limit_index != LIMIT_LOW ||
2368 	    !(op == REQ_OP_READ || op == REQ_OP_WRITE) ||
2369 	    !blk_queue_nonrot(td->queue))
2370 		return;
2371 
2372 	index = request_bucket_index(size);
2373 
2374 	latency = get_cpu_ptr(td->latency_buckets[op]);
2375 	latency[index].total_latency += time;
2376 	latency[index].samples++;
2377 	put_cpu_ptr(td->latency_buckets[op]);
2378 }
2379 
blk_throtl_stat_add(struct request * rq,u64 time_ns)2380 void blk_throtl_stat_add(struct request *rq, u64 time_ns)
2381 {
2382 	struct request_queue *q = rq->q;
2383 	struct throtl_data *td = q->td;
2384 
2385 	throtl_track_latency(td, blk_rq_stats_sectors(rq), req_op(rq),
2386 			     time_ns >> 10);
2387 }
2388 
blk_throtl_bio_endio(struct bio * bio)2389 void blk_throtl_bio_endio(struct bio *bio)
2390 {
2391 	struct blkcg_gq *blkg;
2392 	struct throtl_grp *tg;
2393 	u64 finish_time_ns;
2394 	unsigned long finish_time;
2395 	unsigned long start_time;
2396 	unsigned long lat;
2397 	int rw = bio_data_dir(bio);
2398 
2399 	blkg = bio->bi_blkg;
2400 	if (!blkg)
2401 		return;
2402 	tg = blkg_to_tg(blkg);
2403 	if (!tg->td->limit_valid[LIMIT_LOW])
2404 		return;
2405 
2406 	finish_time_ns = ktime_get_ns();
2407 	tg->last_finish_time = finish_time_ns >> 10;
2408 
2409 	start_time = bio_issue_time(&bio->bi_issue) >> 10;
2410 	finish_time = __bio_issue_time(finish_time_ns) >> 10;
2411 	if (!start_time || finish_time <= start_time)
2412 		return;
2413 
2414 	lat = finish_time - start_time;
2415 	/* this is only for bio based driver */
2416 	if (!(bio->bi_issue.value & BIO_ISSUE_THROTL_SKIP_LATENCY))
2417 		throtl_track_latency(tg->td, bio_issue_size(&bio->bi_issue),
2418 				     bio_op(bio), lat);
2419 
2420 	if (tg->latency_target && lat >= tg->td->filtered_latency) {
2421 		int bucket;
2422 		unsigned int threshold;
2423 
2424 		bucket = request_bucket_index(bio_issue_size(&bio->bi_issue));
2425 		threshold = tg->td->avg_buckets[rw][bucket].latency +
2426 			tg->latency_target;
2427 		if (lat > threshold)
2428 			tg->bad_bio_cnt++;
2429 		/*
2430 		 * Not race free, could get wrong count, which means cgroups
2431 		 * will be throttled
2432 		 */
2433 		tg->bio_cnt++;
2434 	}
2435 
2436 	if (time_after(jiffies, tg->bio_cnt_reset_time) || tg->bio_cnt > 1024) {
2437 		tg->bio_cnt_reset_time = tg->td->throtl_slice + jiffies;
2438 		tg->bio_cnt /= 2;
2439 		tg->bad_bio_cnt /= 2;
2440 	}
2441 }
2442 #endif
2443 
blk_throtl_init(struct request_queue * q)2444 int blk_throtl_init(struct request_queue *q)
2445 {
2446 	struct throtl_data *td;
2447 	int ret;
2448 
2449 	td = kzalloc_node(sizeof(*td), GFP_KERNEL, q->node);
2450 	if (!td)
2451 		return -ENOMEM;
2452 	td->latency_buckets[READ] = __alloc_percpu(sizeof(struct latency_bucket) *
2453 		LATENCY_BUCKET_SIZE, __alignof__(u64));
2454 	if (!td->latency_buckets[READ]) {
2455 		kfree(td);
2456 		return -ENOMEM;
2457 	}
2458 	td->latency_buckets[WRITE] = __alloc_percpu(sizeof(struct latency_bucket) *
2459 		LATENCY_BUCKET_SIZE, __alignof__(u64));
2460 	if (!td->latency_buckets[WRITE]) {
2461 		free_percpu(td->latency_buckets[READ]);
2462 		kfree(td);
2463 		return -ENOMEM;
2464 	}
2465 
2466 	INIT_WORK(&td->dispatch_work, blk_throtl_dispatch_work_fn);
2467 	throtl_service_queue_init(&td->service_queue);
2468 
2469 	q->td = td;
2470 	td->queue = q;
2471 
2472 	td->limit_valid[LIMIT_MAX] = true;
2473 	td->limit_index = LIMIT_MAX;
2474 	td->low_upgrade_time = jiffies;
2475 	td->low_downgrade_time = jiffies;
2476 
2477 	/* activate policy */
2478 	ret = blkcg_activate_policy(q, &blkcg_policy_throtl);
2479 	if (ret) {
2480 		free_percpu(td->latency_buckets[READ]);
2481 		free_percpu(td->latency_buckets[WRITE]);
2482 		kfree(td);
2483 	}
2484 	return ret;
2485 }
2486 
blk_throtl_exit(struct request_queue * q)2487 void blk_throtl_exit(struct request_queue *q)
2488 {
2489 	BUG_ON(!q->td);
2490 	del_timer_sync(&q->td->service_queue.pending_timer);
2491 	throtl_shutdown_wq(q);
2492 	blkcg_deactivate_policy(q, &blkcg_policy_throtl);
2493 	free_percpu(q->td->latency_buckets[READ]);
2494 	free_percpu(q->td->latency_buckets[WRITE]);
2495 	kfree(q->td);
2496 }
2497 
blk_throtl_register_queue(struct request_queue * q)2498 void blk_throtl_register_queue(struct request_queue *q)
2499 {
2500 	struct throtl_data *td;
2501 	int i;
2502 
2503 	td = q->td;
2504 	BUG_ON(!td);
2505 
2506 	if (blk_queue_nonrot(q)) {
2507 		td->throtl_slice = DFL_THROTL_SLICE_SSD;
2508 		td->filtered_latency = LATENCY_FILTERED_SSD;
2509 	} else {
2510 		td->throtl_slice = DFL_THROTL_SLICE_HD;
2511 		td->filtered_latency = LATENCY_FILTERED_HD;
2512 		for (i = 0; i < LATENCY_BUCKET_SIZE; i++) {
2513 			td->avg_buckets[READ][i].latency = DFL_HD_BASELINE_LATENCY;
2514 			td->avg_buckets[WRITE][i].latency = DFL_HD_BASELINE_LATENCY;
2515 		}
2516 	}
2517 #ifndef CONFIG_BLK_DEV_THROTTLING_LOW
2518 	/* if no low limit, use previous default */
2519 	td->throtl_slice = DFL_THROTL_SLICE_HD;
2520 #endif
2521 
2522 	td->track_bio_latency = !queue_is_mq(q);
2523 	if (!td->track_bio_latency)
2524 		blk_stat_enable_accounting(q);
2525 }
2526 
2527 #ifdef CONFIG_BLK_DEV_THROTTLING_LOW
blk_throtl_sample_time_show(struct request_queue * q,char * page)2528 ssize_t blk_throtl_sample_time_show(struct request_queue *q, char *page)
2529 {
2530 	if (!q->td)
2531 		return -EINVAL;
2532 	return sprintf(page, "%u\n", jiffies_to_msecs(q->td->throtl_slice));
2533 }
2534 
blk_throtl_sample_time_store(struct request_queue * q,const char * page,size_t count)2535 ssize_t blk_throtl_sample_time_store(struct request_queue *q,
2536 	const char *page, size_t count)
2537 {
2538 	unsigned long v;
2539 	unsigned long t;
2540 
2541 	if (!q->td)
2542 		return -EINVAL;
2543 	if (kstrtoul(page, 10, &v))
2544 		return -EINVAL;
2545 	t = msecs_to_jiffies(v);
2546 	if (t == 0 || t > MAX_THROTL_SLICE)
2547 		return -EINVAL;
2548 	q->td->throtl_slice = t;
2549 	return count;
2550 }
2551 #endif
2552 
throtl_init(void)2553 static int __init throtl_init(void)
2554 {
2555 	kthrotld_workqueue = alloc_workqueue("kthrotld", WQ_MEM_RECLAIM, 0);
2556 	if (!kthrotld_workqueue)
2557 		panic("Failed to create kthrotld\n");
2558 
2559 	return blkcg_policy_register(&blkcg_policy_throtl);
2560 }
2561 
2562 module_init(throtl_init);
2563