xref: /openbmc/linux/block/bfq-wf2q.c (revision b830f94f)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Hierarchical Budget Worst-case Fair Weighted Fair Queueing
4  * (B-WF2Q+): hierarchical scheduling algorithm by which the BFQ I/O
5  * scheduler schedules generic entities. The latter can represent
6  * either single bfq queues (associated with processes) or groups of
7  * bfq queues (associated with cgroups).
8  */
9 #include "bfq-iosched.h"
10 
11 /**
12  * bfq_gt - compare two timestamps.
13  * @a: first ts.
14  * @b: second ts.
15  *
16  * Return @a > @b, dealing with wrapping correctly.
17  */
18 static int bfq_gt(u64 a, u64 b)
19 {
20 	return (s64)(a - b) > 0;
21 }
22 
23 static struct bfq_entity *bfq_root_active_entity(struct rb_root *tree)
24 {
25 	struct rb_node *node = tree->rb_node;
26 
27 	return rb_entry(node, struct bfq_entity, rb_node);
28 }
29 
30 static unsigned int bfq_class_idx(struct bfq_entity *entity)
31 {
32 	struct bfq_queue *bfqq = bfq_entity_to_bfqq(entity);
33 
34 	return bfqq ? bfqq->ioprio_class - 1 :
35 		BFQ_DEFAULT_GRP_CLASS - 1;
36 }
37 
38 unsigned int bfq_tot_busy_queues(struct bfq_data *bfqd)
39 {
40 	return bfqd->busy_queues[0] + bfqd->busy_queues[1] +
41 		bfqd->busy_queues[2];
42 }
43 
44 static struct bfq_entity *bfq_lookup_next_entity(struct bfq_sched_data *sd,
45 						 bool expiration);
46 
47 static bool bfq_update_parent_budget(struct bfq_entity *next_in_service);
48 
49 /**
50  * bfq_update_next_in_service - update sd->next_in_service
51  * @sd: sched_data for which to perform the update.
52  * @new_entity: if not NULL, pointer to the entity whose activation,
53  *		requeueing or repositioning triggered the invocation of
54  *		this function.
55  * @expiration: id true, this function is being invoked after the
56  *             expiration of the in-service entity
57  *
58  * This function is called to update sd->next_in_service, which, in
59  * its turn, may change as a consequence of the insertion or
60  * extraction of an entity into/from one of the active trees of
61  * sd. These insertions/extractions occur as a consequence of
62  * activations/deactivations of entities, with some activations being
63  * 'true' activations, and other activations being requeueings (i.e.,
64  * implementing the second, requeueing phase of the mechanism used to
65  * reposition an entity in its active tree; see comments on
66  * __bfq_activate_entity and __bfq_requeue_entity for details). In
67  * both the last two activation sub-cases, new_entity points to the
68  * just activated or requeued entity.
69  *
70  * Returns true if sd->next_in_service changes in such a way that
71  * entity->parent may become the next_in_service for its parent
72  * entity.
73  */
74 static bool bfq_update_next_in_service(struct bfq_sched_data *sd,
75 				       struct bfq_entity *new_entity,
76 				       bool expiration)
77 {
78 	struct bfq_entity *next_in_service = sd->next_in_service;
79 	bool parent_sched_may_change = false;
80 	bool change_without_lookup = false;
81 
82 	/*
83 	 * If this update is triggered by the activation, requeueing
84 	 * or repositioning of an entity that does not coincide with
85 	 * sd->next_in_service, then a full lookup in the active tree
86 	 * can be avoided. In fact, it is enough to check whether the
87 	 * just-modified entity has the same priority as
88 	 * sd->next_in_service, is eligible and has a lower virtual
89 	 * finish time than sd->next_in_service. If this compound
90 	 * condition holds, then the new entity becomes the new
91 	 * next_in_service. Otherwise no change is needed.
92 	 */
93 	if (new_entity && new_entity != sd->next_in_service) {
94 		/*
95 		 * Flag used to decide whether to replace
96 		 * sd->next_in_service with new_entity. Tentatively
97 		 * set to true, and left as true if
98 		 * sd->next_in_service is NULL.
99 		 */
100 		change_without_lookup = true;
101 
102 		/*
103 		 * If there is already a next_in_service candidate
104 		 * entity, then compare timestamps to decide whether
105 		 * to replace sd->service_tree with new_entity.
106 		 */
107 		if (next_in_service) {
108 			unsigned int new_entity_class_idx =
109 				bfq_class_idx(new_entity);
110 			struct bfq_service_tree *st =
111 				sd->service_tree + new_entity_class_idx;
112 
113 			change_without_lookup =
114 				(new_entity_class_idx ==
115 				 bfq_class_idx(next_in_service)
116 				 &&
117 				 !bfq_gt(new_entity->start, st->vtime)
118 				 &&
119 				 bfq_gt(next_in_service->finish,
120 					new_entity->finish));
121 		}
122 
123 		if (change_without_lookup)
124 			next_in_service = new_entity;
125 	}
126 
127 	if (!change_without_lookup) /* lookup needed */
128 		next_in_service = bfq_lookup_next_entity(sd, expiration);
129 
130 	if (next_in_service) {
131 		bool new_budget_triggers_change =
132 			bfq_update_parent_budget(next_in_service);
133 
134 		parent_sched_may_change = !sd->next_in_service ||
135 			new_budget_triggers_change;
136 	}
137 
138 	sd->next_in_service = next_in_service;
139 
140 	if (!next_in_service)
141 		return parent_sched_may_change;
142 
143 	return parent_sched_may_change;
144 }
145 
146 #ifdef CONFIG_BFQ_GROUP_IOSCHED
147 
148 struct bfq_group *bfq_bfqq_to_bfqg(struct bfq_queue *bfqq)
149 {
150 	struct bfq_entity *group_entity = bfqq->entity.parent;
151 
152 	if (!group_entity)
153 		group_entity = &bfqq->bfqd->root_group->entity;
154 
155 	return container_of(group_entity, struct bfq_group, entity);
156 }
157 
158 /*
159  * Returns true if this budget changes may let next_in_service->parent
160  * become the next_in_service entity for its parent entity.
161  */
162 static bool bfq_update_parent_budget(struct bfq_entity *next_in_service)
163 {
164 	struct bfq_entity *bfqg_entity;
165 	struct bfq_group *bfqg;
166 	struct bfq_sched_data *group_sd;
167 	bool ret = false;
168 
169 	group_sd = next_in_service->sched_data;
170 
171 	bfqg = container_of(group_sd, struct bfq_group, sched_data);
172 	/*
173 	 * bfq_group's my_entity field is not NULL only if the group
174 	 * is not the root group. We must not touch the root entity
175 	 * as it must never become an in-service entity.
176 	 */
177 	bfqg_entity = bfqg->my_entity;
178 	if (bfqg_entity) {
179 		if (bfqg_entity->budget > next_in_service->budget)
180 			ret = true;
181 		bfqg_entity->budget = next_in_service->budget;
182 	}
183 
184 	return ret;
185 }
186 
187 /*
188  * This function tells whether entity stops being a candidate for next
189  * service, according to the restrictive definition of the field
190  * next_in_service. In particular, this function is invoked for an
191  * entity that is about to be set in service.
192  *
193  * If entity is a queue, then the entity is no longer a candidate for
194  * next service according to the that definition, because entity is
195  * about to become the in-service queue. This function then returns
196  * true if entity is a queue.
197  *
198  * In contrast, entity could still be a candidate for next service if
199  * it is not a queue, and has more than one active child. In fact,
200  * even if one of its children is about to be set in service, other
201  * active children may still be the next to serve, for the parent
202  * entity, even according to the above definition. As a consequence, a
203  * non-queue entity is not a candidate for next-service only if it has
204  * only one active child. And only if this condition holds, then this
205  * function returns true for a non-queue entity.
206  */
207 static bool bfq_no_longer_next_in_service(struct bfq_entity *entity)
208 {
209 	struct bfq_group *bfqg;
210 
211 	if (bfq_entity_to_bfqq(entity))
212 		return true;
213 
214 	bfqg = container_of(entity, struct bfq_group, entity);
215 
216 	/*
217 	 * The field active_entities does not always contain the
218 	 * actual number of active children entities: it happens to
219 	 * not account for the in-service entity in case the latter is
220 	 * removed from its active tree (which may get done after
221 	 * invoking the function bfq_no_longer_next_in_service in
222 	 * bfq_get_next_queue). Fortunately, here, i.e., while
223 	 * bfq_no_longer_next_in_service is not yet completed in
224 	 * bfq_get_next_queue, bfq_active_extract has not yet been
225 	 * invoked, and thus active_entities still coincides with the
226 	 * actual number of active entities.
227 	 */
228 	if (bfqg->active_entities == 1)
229 		return true;
230 
231 	return false;
232 }
233 
234 #else /* CONFIG_BFQ_GROUP_IOSCHED */
235 
236 struct bfq_group *bfq_bfqq_to_bfqg(struct bfq_queue *bfqq)
237 {
238 	return bfqq->bfqd->root_group;
239 }
240 
241 static bool bfq_update_parent_budget(struct bfq_entity *next_in_service)
242 {
243 	return false;
244 }
245 
246 static bool bfq_no_longer_next_in_service(struct bfq_entity *entity)
247 {
248 	return true;
249 }
250 
251 #endif /* CONFIG_BFQ_GROUP_IOSCHED */
252 
253 /*
254  * Shift for timestamp calculations.  This actually limits the maximum
255  * service allowed in one timestamp delta (small shift values increase it),
256  * the maximum total weight that can be used for the queues in the system
257  * (big shift values increase it), and the period of virtual time
258  * wraparounds.
259  */
260 #define WFQ_SERVICE_SHIFT	22
261 
262 struct bfq_queue *bfq_entity_to_bfqq(struct bfq_entity *entity)
263 {
264 	struct bfq_queue *bfqq = NULL;
265 
266 	if (!entity->my_sched_data)
267 		bfqq = container_of(entity, struct bfq_queue, entity);
268 
269 	return bfqq;
270 }
271 
272 
273 /**
274  * bfq_delta - map service into the virtual time domain.
275  * @service: amount of service.
276  * @weight: scale factor (weight of an entity or weight sum).
277  */
278 static u64 bfq_delta(unsigned long service, unsigned long weight)
279 {
280 	u64 d = (u64)service << WFQ_SERVICE_SHIFT;
281 
282 	do_div(d, weight);
283 	return d;
284 }
285 
286 /**
287  * bfq_calc_finish - assign the finish time to an entity.
288  * @entity: the entity to act upon.
289  * @service: the service to be charged to the entity.
290  */
291 static void bfq_calc_finish(struct bfq_entity *entity, unsigned long service)
292 {
293 	struct bfq_queue *bfqq = bfq_entity_to_bfqq(entity);
294 
295 	entity->finish = entity->start +
296 		bfq_delta(service, entity->weight);
297 
298 	if (bfqq) {
299 		bfq_log_bfqq(bfqq->bfqd, bfqq,
300 			"calc_finish: serv %lu, w %d",
301 			service, entity->weight);
302 		bfq_log_bfqq(bfqq->bfqd, bfqq,
303 			"calc_finish: start %llu, finish %llu, delta %llu",
304 			entity->start, entity->finish,
305 			bfq_delta(service, entity->weight));
306 	}
307 }
308 
309 /**
310  * bfq_entity_of - get an entity from a node.
311  * @node: the node field of the entity.
312  *
313  * Convert a node pointer to the relative entity.  This is used only
314  * to simplify the logic of some functions and not as the generic
315  * conversion mechanism because, e.g., in the tree walking functions,
316  * the check for a %NULL value would be redundant.
317  */
318 struct bfq_entity *bfq_entity_of(struct rb_node *node)
319 {
320 	struct bfq_entity *entity = NULL;
321 
322 	if (node)
323 		entity = rb_entry(node, struct bfq_entity, rb_node);
324 
325 	return entity;
326 }
327 
328 /**
329  * bfq_extract - remove an entity from a tree.
330  * @root: the tree root.
331  * @entity: the entity to remove.
332  */
333 static void bfq_extract(struct rb_root *root, struct bfq_entity *entity)
334 {
335 	entity->tree = NULL;
336 	rb_erase(&entity->rb_node, root);
337 }
338 
339 /**
340  * bfq_idle_extract - extract an entity from the idle tree.
341  * @st: the service tree of the owning @entity.
342  * @entity: the entity being removed.
343  */
344 static void bfq_idle_extract(struct bfq_service_tree *st,
345 			     struct bfq_entity *entity)
346 {
347 	struct bfq_queue *bfqq = bfq_entity_to_bfqq(entity);
348 	struct rb_node *next;
349 
350 	if (entity == st->first_idle) {
351 		next = rb_next(&entity->rb_node);
352 		st->first_idle = bfq_entity_of(next);
353 	}
354 
355 	if (entity == st->last_idle) {
356 		next = rb_prev(&entity->rb_node);
357 		st->last_idle = bfq_entity_of(next);
358 	}
359 
360 	bfq_extract(&st->idle, entity);
361 
362 	if (bfqq)
363 		list_del(&bfqq->bfqq_list);
364 }
365 
366 /**
367  * bfq_insert - generic tree insertion.
368  * @root: tree root.
369  * @entity: entity to insert.
370  *
371  * This is used for the idle and the active tree, since they are both
372  * ordered by finish time.
373  */
374 static void bfq_insert(struct rb_root *root, struct bfq_entity *entity)
375 {
376 	struct bfq_entity *entry;
377 	struct rb_node **node = &root->rb_node;
378 	struct rb_node *parent = NULL;
379 
380 	while (*node) {
381 		parent = *node;
382 		entry = rb_entry(parent, struct bfq_entity, rb_node);
383 
384 		if (bfq_gt(entry->finish, entity->finish))
385 			node = &parent->rb_left;
386 		else
387 			node = &parent->rb_right;
388 	}
389 
390 	rb_link_node(&entity->rb_node, parent, node);
391 	rb_insert_color(&entity->rb_node, root);
392 
393 	entity->tree = root;
394 }
395 
396 /**
397  * bfq_update_min - update the min_start field of a entity.
398  * @entity: the entity to update.
399  * @node: one of its children.
400  *
401  * This function is called when @entity may store an invalid value for
402  * min_start due to updates to the active tree.  The function  assumes
403  * that the subtree rooted at @node (which may be its left or its right
404  * child) has a valid min_start value.
405  */
406 static void bfq_update_min(struct bfq_entity *entity, struct rb_node *node)
407 {
408 	struct bfq_entity *child;
409 
410 	if (node) {
411 		child = rb_entry(node, struct bfq_entity, rb_node);
412 		if (bfq_gt(entity->min_start, child->min_start))
413 			entity->min_start = child->min_start;
414 	}
415 }
416 
417 /**
418  * bfq_update_active_node - recalculate min_start.
419  * @node: the node to update.
420  *
421  * @node may have changed position or one of its children may have moved,
422  * this function updates its min_start value.  The left and right subtrees
423  * are assumed to hold a correct min_start value.
424  */
425 static void bfq_update_active_node(struct rb_node *node)
426 {
427 	struct bfq_entity *entity = rb_entry(node, struct bfq_entity, rb_node);
428 
429 	entity->min_start = entity->start;
430 	bfq_update_min(entity, node->rb_right);
431 	bfq_update_min(entity, node->rb_left);
432 }
433 
434 /**
435  * bfq_update_active_tree - update min_start for the whole active tree.
436  * @node: the starting node.
437  *
438  * @node must be the deepest modified node after an update.  This function
439  * updates its min_start using the values held by its children, assuming
440  * that they did not change, and then updates all the nodes that may have
441  * changed in the path to the root.  The only nodes that may have changed
442  * are the ones in the path or their siblings.
443  */
444 static void bfq_update_active_tree(struct rb_node *node)
445 {
446 	struct rb_node *parent;
447 
448 up:
449 	bfq_update_active_node(node);
450 
451 	parent = rb_parent(node);
452 	if (!parent)
453 		return;
454 
455 	if (node == parent->rb_left && parent->rb_right)
456 		bfq_update_active_node(parent->rb_right);
457 	else if (parent->rb_left)
458 		bfq_update_active_node(parent->rb_left);
459 
460 	node = parent;
461 	goto up;
462 }
463 
464 /**
465  * bfq_active_insert - insert an entity in the active tree of its
466  *                     group/device.
467  * @st: the service tree of the entity.
468  * @entity: the entity being inserted.
469  *
470  * The active tree is ordered by finish time, but an extra key is kept
471  * per each node, containing the minimum value for the start times of
472  * its children (and the node itself), so it's possible to search for
473  * the eligible node with the lowest finish time in logarithmic time.
474  */
475 static void bfq_active_insert(struct bfq_service_tree *st,
476 			      struct bfq_entity *entity)
477 {
478 	struct bfq_queue *bfqq = bfq_entity_to_bfqq(entity);
479 	struct rb_node *node = &entity->rb_node;
480 #ifdef CONFIG_BFQ_GROUP_IOSCHED
481 	struct bfq_sched_data *sd = NULL;
482 	struct bfq_group *bfqg = NULL;
483 	struct bfq_data *bfqd = NULL;
484 #endif
485 
486 	bfq_insert(&st->active, entity);
487 
488 	if (node->rb_left)
489 		node = node->rb_left;
490 	else if (node->rb_right)
491 		node = node->rb_right;
492 
493 	bfq_update_active_tree(node);
494 
495 #ifdef CONFIG_BFQ_GROUP_IOSCHED
496 	sd = entity->sched_data;
497 	bfqg = container_of(sd, struct bfq_group, sched_data);
498 	bfqd = (struct bfq_data *)bfqg->bfqd;
499 #endif
500 	if (bfqq)
501 		list_add(&bfqq->bfqq_list, &bfqq->bfqd->active_list);
502 #ifdef CONFIG_BFQ_GROUP_IOSCHED
503 	if (bfqg != bfqd->root_group)
504 		bfqg->active_entities++;
505 #endif
506 }
507 
508 /**
509  * bfq_ioprio_to_weight - calc a weight from an ioprio.
510  * @ioprio: the ioprio value to convert.
511  */
512 unsigned short bfq_ioprio_to_weight(int ioprio)
513 {
514 	return (IOPRIO_BE_NR - ioprio) * BFQ_WEIGHT_CONVERSION_COEFF;
515 }
516 
517 /**
518  * bfq_weight_to_ioprio - calc an ioprio from a weight.
519  * @weight: the weight value to convert.
520  *
521  * To preserve as much as possible the old only-ioprio user interface,
522  * 0 is used as an escape ioprio value for weights (numerically) equal or
523  * larger than IOPRIO_BE_NR * BFQ_WEIGHT_CONVERSION_COEFF.
524  */
525 static unsigned short bfq_weight_to_ioprio(int weight)
526 {
527 	return max_t(int, 0,
528 		     IOPRIO_BE_NR * BFQ_WEIGHT_CONVERSION_COEFF - weight);
529 }
530 
531 static void bfq_get_entity(struct bfq_entity *entity)
532 {
533 	struct bfq_queue *bfqq = bfq_entity_to_bfqq(entity);
534 
535 	if (bfqq) {
536 		bfqq->ref++;
537 		bfq_log_bfqq(bfqq->bfqd, bfqq, "get_entity: %p %d",
538 			     bfqq, bfqq->ref);
539 	}
540 }
541 
542 /**
543  * bfq_find_deepest - find the deepest node that an extraction can modify.
544  * @node: the node being removed.
545  *
546  * Do the first step of an extraction in an rb tree, looking for the
547  * node that will replace @node, and returning the deepest node that
548  * the following modifications to the tree can touch.  If @node is the
549  * last node in the tree return %NULL.
550  */
551 static struct rb_node *bfq_find_deepest(struct rb_node *node)
552 {
553 	struct rb_node *deepest;
554 
555 	if (!node->rb_right && !node->rb_left)
556 		deepest = rb_parent(node);
557 	else if (!node->rb_right)
558 		deepest = node->rb_left;
559 	else if (!node->rb_left)
560 		deepest = node->rb_right;
561 	else {
562 		deepest = rb_next(node);
563 		if (deepest->rb_right)
564 			deepest = deepest->rb_right;
565 		else if (rb_parent(deepest) != node)
566 			deepest = rb_parent(deepest);
567 	}
568 
569 	return deepest;
570 }
571 
572 /**
573  * bfq_active_extract - remove an entity from the active tree.
574  * @st: the service_tree containing the tree.
575  * @entity: the entity being removed.
576  */
577 static void bfq_active_extract(struct bfq_service_tree *st,
578 			       struct bfq_entity *entity)
579 {
580 	struct bfq_queue *bfqq = bfq_entity_to_bfqq(entity);
581 	struct rb_node *node;
582 #ifdef CONFIG_BFQ_GROUP_IOSCHED
583 	struct bfq_sched_data *sd = NULL;
584 	struct bfq_group *bfqg = NULL;
585 	struct bfq_data *bfqd = NULL;
586 #endif
587 
588 	node = bfq_find_deepest(&entity->rb_node);
589 	bfq_extract(&st->active, entity);
590 
591 	if (node)
592 		bfq_update_active_tree(node);
593 
594 #ifdef CONFIG_BFQ_GROUP_IOSCHED
595 	sd = entity->sched_data;
596 	bfqg = container_of(sd, struct bfq_group, sched_data);
597 	bfqd = (struct bfq_data *)bfqg->bfqd;
598 #endif
599 	if (bfqq)
600 		list_del(&bfqq->bfqq_list);
601 #ifdef CONFIG_BFQ_GROUP_IOSCHED
602 	if (bfqg != bfqd->root_group)
603 		bfqg->active_entities--;
604 #endif
605 }
606 
607 /**
608  * bfq_idle_insert - insert an entity into the idle tree.
609  * @st: the service tree containing the tree.
610  * @entity: the entity to insert.
611  */
612 static void bfq_idle_insert(struct bfq_service_tree *st,
613 			    struct bfq_entity *entity)
614 {
615 	struct bfq_queue *bfqq = bfq_entity_to_bfqq(entity);
616 	struct bfq_entity *first_idle = st->first_idle;
617 	struct bfq_entity *last_idle = st->last_idle;
618 
619 	if (!first_idle || bfq_gt(first_idle->finish, entity->finish))
620 		st->first_idle = entity;
621 	if (!last_idle || bfq_gt(entity->finish, last_idle->finish))
622 		st->last_idle = entity;
623 
624 	bfq_insert(&st->idle, entity);
625 
626 	if (bfqq)
627 		list_add(&bfqq->bfqq_list, &bfqq->bfqd->idle_list);
628 }
629 
630 /**
631  * bfq_forget_entity - do not consider entity any longer for scheduling
632  * @st: the service tree.
633  * @entity: the entity being removed.
634  * @is_in_service: true if entity is currently the in-service entity.
635  *
636  * Forget everything about @entity. In addition, if entity represents
637  * a queue, and the latter is not in service, then release the service
638  * reference to the queue (the one taken through bfq_get_entity). In
639  * fact, in this case, there is really no more service reference to
640  * the queue, as the latter is also outside any service tree. If,
641  * instead, the queue is in service, then __bfq_bfqd_reset_in_service
642  * will take care of putting the reference when the queue finally
643  * stops being served.
644  */
645 static void bfq_forget_entity(struct bfq_service_tree *st,
646 			      struct bfq_entity *entity,
647 			      bool is_in_service)
648 {
649 	struct bfq_queue *bfqq = bfq_entity_to_bfqq(entity);
650 
651 	entity->on_st = false;
652 	st->wsum -= entity->weight;
653 	if (bfqq && !is_in_service)
654 		bfq_put_queue(bfqq);
655 }
656 
657 /**
658  * bfq_put_idle_entity - release the idle tree ref of an entity.
659  * @st: service tree for the entity.
660  * @entity: the entity being released.
661  */
662 void bfq_put_idle_entity(struct bfq_service_tree *st, struct bfq_entity *entity)
663 {
664 	bfq_idle_extract(st, entity);
665 	bfq_forget_entity(st, entity,
666 			  entity == entity->sched_data->in_service_entity);
667 }
668 
669 /**
670  * bfq_forget_idle - update the idle tree if necessary.
671  * @st: the service tree to act upon.
672  *
673  * To preserve the global O(log N) complexity we only remove one entry here;
674  * as the idle tree will not grow indefinitely this can be done safely.
675  */
676 static void bfq_forget_idle(struct bfq_service_tree *st)
677 {
678 	struct bfq_entity *first_idle = st->first_idle;
679 	struct bfq_entity *last_idle = st->last_idle;
680 
681 	if (RB_EMPTY_ROOT(&st->active) && last_idle &&
682 	    !bfq_gt(last_idle->finish, st->vtime)) {
683 		/*
684 		 * Forget the whole idle tree, increasing the vtime past
685 		 * the last finish time of idle entities.
686 		 */
687 		st->vtime = last_idle->finish;
688 	}
689 
690 	if (first_idle && !bfq_gt(first_idle->finish, st->vtime))
691 		bfq_put_idle_entity(st, first_idle);
692 }
693 
694 struct bfq_service_tree *bfq_entity_service_tree(struct bfq_entity *entity)
695 {
696 	struct bfq_sched_data *sched_data = entity->sched_data;
697 	unsigned int idx = bfq_class_idx(entity);
698 
699 	return sched_data->service_tree + idx;
700 }
701 
702 /*
703  * Update weight and priority of entity. If update_class_too is true,
704  * then update the ioprio_class of entity too.
705  *
706  * The reason why the update of ioprio_class is controlled through the
707  * last parameter is as follows. Changing the ioprio class of an
708  * entity implies changing the destination service trees for that
709  * entity. If such a change occurred when the entity is already on one
710  * of the service trees for its previous class, then the state of the
711  * entity would become more complex: none of the new possible service
712  * trees for the entity, according to bfq_entity_service_tree(), would
713  * match any of the possible service trees on which the entity
714  * is. Complex operations involving these trees, such as entity
715  * activations and deactivations, should take into account this
716  * additional complexity.  To avoid this issue, this function is
717  * invoked with update_class_too unset in the points in the code where
718  * entity may happen to be on some tree.
719  */
720 struct bfq_service_tree *
721 __bfq_entity_update_weight_prio(struct bfq_service_tree *old_st,
722 				struct bfq_entity *entity,
723 				bool update_class_too)
724 {
725 	struct bfq_service_tree *new_st = old_st;
726 
727 	if (entity->prio_changed) {
728 		struct bfq_queue *bfqq = bfq_entity_to_bfqq(entity);
729 		unsigned int prev_weight, new_weight;
730 		struct bfq_data *bfqd = NULL;
731 		struct rb_root_cached *root;
732 #ifdef CONFIG_BFQ_GROUP_IOSCHED
733 		struct bfq_sched_data *sd;
734 		struct bfq_group *bfqg;
735 #endif
736 
737 		if (bfqq)
738 			bfqd = bfqq->bfqd;
739 #ifdef CONFIG_BFQ_GROUP_IOSCHED
740 		else {
741 			sd = entity->my_sched_data;
742 			bfqg = container_of(sd, struct bfq_group, sched_data);
743 			bfqd = (struct bfq_data *)bfqg->bfqd;
744 		}
745 #endif
746 
747 		old_st->wsum -= entity->weight;
748 
749 		if (entity->new_weight != entity->orig_weight) {
750 			if (entity->new_weight < BFQ_MIN_WEIGHT ||
751 			    entity->new_weight > BFQ_MAX_WEIGHT) {
752 				pr_crit("update_weight_prio: new_weight %d\n",
753 					entity->new_weight);
754 				if (entity->new_weight < BFQ_MIN_WEIGHT)
755 					entity->new_weight = BFQ_MIN_WEIGHT;
756 				else
757 					entity->new_weight = BFQ_MAX_WEIGHT;
758 			}
759 			entity->orig_weight = entity->new_weight;
760 			if (bfqq)
761 				bfqq->ioprio =
762 				  bfq_weight_to_ioprio(entity->orig_weight);
763 		}
764 
765 		if (bfqq && update_class_too)
766 			bfqq->ioprio_class = bfqq->new_ioprio_class;
767 
768 		/*
769 		 * Reset prio_changed only if the ioprio_class change
770 		 * is not pending any longer.
771 		 */
772 		if (!bfqq || bfqq->ioprio_class == bfqq->new_ioprio_class)
773 			entity->prio_changed = 0;
774 
775 		/*
776 		 * NOTE: here we may be changing the weight too early,
777 		 * this will cause unfairness.  The correct approach
778 		 * would have required additional complexity to defer
779 		 * weight changes to the proper time instants (i.e.,
780 		 * when entity->finish <= old_st->vtime).
781 		 */
782 		new_st = bfq_entity_service_tree(entity);
783 
784 		prev_weight = entity->weight;
785 		new_weight = entity->orig_weight *
786 			     (bfqq ? bfqq->wr_coeff : 1);
787 		/*
788 		 * If the weight of the entity changes, and the entity is a
789 		 * queue, remove the entity from its old weight counter (if
790 		 * there is a counter associated with the entity).
791 		 */
792 		if (prev_weight != new_weight && bfqq) {
793 			root = &bfqd->queue_weights_tree;
794 			__bfq_weights_tree_remove(bfqd, bfqq, root);
795 		}
796 		entity->weight = new_weight;
797 		/*
798 		 * Add the entity, if it is not a weight-raised queue,
799 		 * to the counter associated with its new weight.
800 		 */
801 		if (prev_weight != new_weight && bfqq && bfqq->wr_coeff == 1) {
802 			/* If we get here, root has been initialized. */
803 			bfq_weights_tree_add(bfqd, bfqq, root);
804 		}
805 
806 		new_st->wsum += entity->weight;
807 
808 		if (new_st != old_st)
809 			entity->start = new_st->vtime;
810 	}
811 
812 	return new_st;
813 }
814 
815 /**
816  * bfq_bfqq_served - update the scheduler status after selection for
817  *                   service.
818  * @bfqq: the queue being served.
819  * @served: bytes to transfer.
820  *
821  * NOTE: this can be optimized, as the timestamps of upper level entities
822  * are synchronized every time a new bfqq is selected for service.  By now,
823  * we keep it to better check consistency.
824  */
825 void bfq_bfqq_served(struct bfq_queue *bfqq, int served)
826 {
827 	struct bfq_entity *entity = &bfqq->entity;
828 	struct bfq_service_tree *st;
829 
830 	if (!bfqq->service_from_backlogged)
831 		bfqq->first_IO_time = jiffies;
832 
833 	if (bfqq->wr_coeff > 1)
834 		bfqq->service_from_wr += served;
835 
836 	bfqq->service_from_backlogged += served;
837 	for_each_entity(entity) {
838 		st = bfq_entity_service_tree(entity);
839 
840 		entity->service += served;
841 
842 		st->vtime += bfq_delta(served, st->wsum);
843 		bfq_forget_idle(st);
844 	}
845 	bfq_log_bfqq(bfqq->bfqd, bfqq, "bfqq_served %d secs", served);
846 }
847 
848 /**
849  * bfq_bfqq_charge_time - charge an amount of service equivalent to the length
850  *			  of the time interval during which bfqq has been in
851  *			  service.
852  * @bfqd: the device
853  * @bfqq: the queue that needs a service update.
854  * @time_ms: the amount of time during which the queue has received service
855  *
856  * If a queue does not consume its budget fast enough, then providing
857  * the queue with service fairness may impair throughput, more or less
858  * severely. For this reason, queues that consume their budget slowly
859  * are provided with time fairness instead of service fairness. This
860  * goal is achieved through the BFQ scheduling engine, even if such an
861  * engine works in the service, and not in the time domain. The trick
862  * is charging these queues with an inflated amount of service, equal
863  * to the amount of service that they would have received during their
864  * service slot if they had been fast, i.e., if their requests had
865  * been dispatched at a rate equal to the estimated peak rate.
866  *
867  * It is worth noting that time fairness can cause important
868  * distortions in terms of bandwidth distribution, on devices with
869  * internal queueing. The reason is that I/O requests dispatched
870  * during the service slot of a queue may be served after that service
871  * slot is finished, and may have a total processing time loosely
872  * correlated with the duration of the service slot. This is
873  * especially true for short service slots.
874  */
875 void bfq_bfqq_charge_time(struct bfq_data *bfqd, struct bfq_queue *bfqq,
876 			  unsigned long time_ms)
877 {
878 	struct bfq_entity *entity = &bfqq->entity;
879 	unsigned long timeout_ms = jiffies_to_msecs(bfq_timeout);
880 	unsigned long bounded_time_ms = min(time_ms, timeout_ms);
881 	int serv_to_charge_for_time =
882 		(bfqd->bfq_max_budget * bounded_time_ms) / timeout_ms;
883 	int tot_serv_to_charge = max(serv_to_charge_for_time, entity->service);
884 
885 	/* Increase budget to avoid inconsistencies */
886 	if (tot_serv_to_charge > entity->budget)
887 		entity->budget = tot_serv_to_charge;
888 
889 	bfq_bfqq_served(bfqq,
890 			max_t(int, 0, tot_serv_to_charge - entity->service));
891 }
892 
893 static void bfq_update_fin_time_enqueue(struct bfq_entity *entity,
894 					struct bfq_service_tree *st,
895 					bool backshifted)
896 {
897 	struct bfq_queue *bfqq = bfq_entity_to_bfqq(entity);
898 
899 	/*
900 	 * When this function is invoked, entity is not in any service
901 	 * tree, then it is safe to invoke next function with the last
902 	 * parameter set (see the comments on the function).
903 	 */
904 	st = __bfq_entity_update_weight_prio(st, entity, true);
905 	bfq_calc_finish(entity, entity->budget);
906 
907 	/*
908 	 * If some queues enjoy backshifting for a while, then their
909 	 * (virtual) finish timestamps may happen to become lower and
910 	 * lower than the system virtual time.	In particular, if
911 	 * these queues often happen to be idle for short time
912 	 * periods, and during such time periods other queues with
913 	 * higher timestamps happen to be busy, then the backshifted
914 	 * timestamps of the former queues can become much lower than
915 	 * the system virtual time. In fact, to serve the queues with
916 	 * higher timestamps while the ones with lower timestamps are
917 	 * idle, the system virtual time may be pushed-up to much
918 	 * higher values than the finish timestamps of the idle
919 	 * queues. As a consequence, the finish timestamps of all new
920 	 * or newly activated queues may end up being much larger than
921 	 * those of lucky queues with backshifted timestamps. The
922 	 * latter queues may then monopolize the device for a lot of
923 	 * time. This would simply break service guarantees.
924 	 *
925 	 * To reduce this problem, push up a little bit the
926 	 * backshifted timestamps of the queue associated with this
927 	 * entity (only a queue can happen to have the backshifted
928 	 * flag set): just enough to let the finish timestamp of the
929 	 * queue be equal to the current value of the system virtual
930 	 * time. This may introduce a little unfairness among queues
931 	 * with backshifted timestamps, but it does not break
932 	 * worst-case fairness guarantees.
933 	 *
934 	 * As a special case, if bfqq is weight-raised, push up
935 	 * timestamps much less, to keep very low the probability that
936 	 * this push up causes the backshifted finish timestamps of
937 	 * weight-raised queues to become higher than the backshifted
938 	 * finish timestamps of non weight-raised queues.
939 	 */
940 	if (backshifted && bfq_gt(st->vtime, entity->finish)) {
941 		unsigned long delta = st->vtime - entity->finish;
942 
943 		if (bfqq)
944 			delta /= bfqq->wr_coeff;
945 
946 		entity->start += delta;
947 		entity->finish += delta;
948 	}
949 
950 	bfq_active_insert(st, entity);
951 }
952 
953 /**
954  * __bfq_activate_entity - handle activation of entity.
955  * @entity: the entity being activated.
956  * @non_blocking_wait_rq: true if entity was waiting for a request
957  *
958  * Called for a 'true' activation, i.e., if entity is not active and
959  * one of its children receives a new request.
960  *
961  * Basically, this function updates the timestamps of entity and
962  * inserts entity into its active tree, after possibly extracting it
963  * from its idle tree.
964  */
965 static void __bfq_activate_entity(struct bfq_entity *entity,
966 				  bool non_blocking_wait_rq)
967 {
968 	struct bfq_service_tree *st = bfq_entity_service_tree(entity);
969 	bool backshifted = false;
970 	unsigned long long min_vstart;
971 
972 	/* See comments on bfq_fqq_update_budg_for_activation */
973 	if (non_blocking_wait_rq && bfq_gt(st->vtime, entity->finish)) {
974 		backshifted = true;
975 		min_vstart = entity->finish;
976 	} else
977 		min_vstart = st->vtime;
978 
979 	if (entity->tree == &st->idle) {
980 		/*
981 		 * Must be on the idle tree, bfq_idle_extract() will
982 		 * check for that.
983 		 */
984 		bfq_idle_extract(st, entity);
985 		entity->start = bfq_gt(min_vstart, entity->finish) ?
986 			min_vstart : entity->finish;
987 	} else {
988 		/*
989 		 * The finish time of the entity may be invalid, and
990 		 * it is in the past for sure, otherwise the queue
991 		 * would have been on the idle tree.
992 		 */
993 		entity->start = min_vstart;
994 		st->wsum += entity->weight;
995 		/*
996 		 * entity is about to be inserted into a service tree,
997 		 * and then set in service: get a reference to make
998 		 * sure entity does not disappear until it is no
999 		 * longer in service or scheduled for service.
1000 		 */
1001 		bfq_get_entity(entity);
1002 
1003 		entity->on_st = true;
1004 	}
1005 
1006 #ifdef CONFIG_BFQ_GROUP_IOSCHED
1007 	if (!bfq_entity_to_bfqq(entity)) { /* bfq_group */
1008 		struct bfq_group *bfqg =
1009 			container_of(entity, struct bfq_group, entity);
1010 		struct bfq_data *bfqd = bfqg->bfqd;
1011 
1012 		if (!entity->in_groups_with_pending_reqs) {
1013 			entity->in_groups_with_pending_reqs = true;
1014 			bfqd->num_groups_with_pending_reqs++;
1015 		}
1016 	}
1017 #endif
1018 
1019 	bfq_update_fin_time_enqueue(entity, st, backshifted);
1020 }
1021 
1022 /**
1023  * __bfq_requeue_entity - handle requeueing or repositioning of an entity.
1024  * @entity: the entity being requeued or repositioned.
1025  *
1026  * Requeueing is needed if this entity stops being served, which
1027  * happens if a leaf descendant entity has expired. On the other hand,
1028  * repositioning is needed if the next_inservice_entity for the child
1029  * entity has changed. See the comments inside the function for
1030  * details.
1031  *
1032  * Basically, this function: 1) removes entity from its active tree if
1033  * present there, 2) updates the timestamps of entity and 3) inserts
1034  * entity back into its active tree (in the new, right position for
1035  * the new values of the timestamps).
1036  */
1037 static void __bfq_requeue_entity(struct bfq_entity *entity)
1038 {
1039 	struct bfq_sched_data *sd = entity->sched_data;
1040 	struct bfq_service_tree *st = bfq_entity_service_tree(entity);
1041 
1042 	if (entity == sd->in_service_entity) {
1043 		/*
1044 		 * We are requeueing the current in-service entity,
1045 		 * which may have to be done for one of the following
1046 		 * reasons:
1047 		 * - entity represents the in-service queue, and the
1048 		 *   in-service queue is being requeued after an
1049 		 *   expiration;
1050 		 * - entity represents a group, and its budget has
1051 		 *   changed because one of its child entities has
1052 		 *   just been either activated or requeued for some
1053 		 *   reason; the timestamps of the entity need then to
1054 		 *   be updated, and the entity needs to be enqueued
1055 		 *   or repositioned accordingly.
1056 		 *
1057 		 * In particular, before requeueing, the start time of
1058 		 * the entity must be moved forward to account for the
1059 		 * service that the entity has received while in
1060 		 * service. This is done by the next instructions. The
1061 		 * finish time will then be updated according to this
1062 		 * new value of the start time, and to the budget of
1063 		 * the entity.
1064 		 */
1065 		bfq_calc_finish(entity, entity->service);
1066 		entity->start = entity->finish;
1067 		/*
1068 		 * In addition, if the entity had more than one child
1069 		 * when set in service, then it was not extracted from
1070 		 * the active tree. This implies that the position of
1071 		 * the entity in the active tree may need to be
1072 		 * changed now, because we have just updated the start
1073 		 * time of the entity, and we will update its finish
1074 		 * time in a moment (the requeueing is then, more
1075 		 * precisely, a repositioning in this case). To
1076 		 * implement this repositioning, we: 1) dequeue the
1077 		 * entity here, 2) update the finish time and requeue
1078 		 * the entity according to the new timestamps below.
1079 		 */
1080 		if (entity->tree)
1081 			bfq_active_extract(st, entity);
1082 	} else { /* The entity is already active, and not in service */
1083 		/*
1084 		 * In this case, this function gets called only if the
1085 		 * next_in_service entity below this entity has
1086 		 * changed, and this change has caused the budget of
1087 		 * this entity to change, which, finally implies that
1088 		 * the finish time of this entity must be
1089 		 * updated. Such an update may cause the scheduling,
1090 		 * i.e., the position in the active tree, of this
1091 		 * entity to change. We handle this change by: 1)
1092 		 * dequeueing the entity here, 2) updating the finish
1093 		 * time and requeueing the entity according to the new
1094 		 * timestamps below. This is the same approach as the
1095 		 * non-extracted-entity sub-case above.
1096 		 */
1097 		bfq_active_extract(st, entity);
1098 	}
1099 
1100 	bfq_update_fin_time_enqueue(entity, st, false);
1101 }
1102 
1103 static void __bfq_activate_requeue_entity(struct bfq_entity *entity,
1104 					  struct bfq_sched_data *sd,
1105 					  bool non_blocking_wait_rq)
1106 {
1107 	struct bfq_service_tree *st = bfq_entity_service_tree(entity);
1108 
1109 	if (sd->in_service_entity == entity || entity->tree == &st->active)
1110 		 /*
1111 		  * in service or already queued on the active tree,
1112 		  * requeue or reposition
1113 		  */
1114 		__bfq_requeue_entity(entity);
1115 	else
1116 		/*
1117 		 * Not in service and not queued on its active tree:
1118 		 * the activity is idle and this is a true activation.
1119 		 */
1120 		__bfq_activate_entity(entity, non_blocking_wait_rq);
1121 }
1122 
1123 
1124 /**
1125  * bfq_activate_requeue_entity - activate or requeue an entity representing a
1126  *				 bfq_queue, and activate, requeue or reposition
1127  *				 all ancestors for which such an update becomes
1128  *				 necessary.
1129  * @entity: the entity to activate.
1130  * @non_blocking_wait_rq: true if this entity was waiting for a request
1131  * @requeue: true if this is a requeue, which implies that bfqq is
1132  *	     being expired; thus ALL its ancestors stop being served and must
1133  *	     therefore be requeued
1134  * @expiration: true if this function is being invoked in the expiration path
1135  *             of the in-service queue
1136  */
1137 static void bfq_activate_requeue_entity(struct bfq_entity *entity,
1138 					bool non_blocking_wait_rq,
1139 					bool requeue, bool expiration)
1140 {
1141 	struct bfq_sched_data *sd;
1142 
1143 	for_each_entity(entity) {
1144 		sd = entity->sched_data;
1145 		__bfq_activate_requeue_entity(entity, sd, non_blocking_wait_rq);
1146 
1147 		if (!bfq_update_next_in_service(sd, entity, expiration) &&
1148 		    !requeue)
1149 			break;
1150 	}
1151 }
1152 
1153 /**
1154  * __bfq_deactivate_entity - update sched_data and service trees for
1155  * entity, so as to represent entity as inactive
1156  * @entity: the entity being deactivated.
1157  * @ins_into_idle_tree: if false, the entity will not be put into the
1158  *			idle tree.
1159  *
1160  * If necessary and allowed, puts entity into the idle tree. NOTE:
1161  * entity may be on no tree if in service.
1162  */
1163 bool __bfq_deactivate_entity(struct bfq_entity *entity, bool ins_into_idle_tree)
1164 {
1165 	struct bfq_sched_data *sd = entity->sched_data;
1166 	struct bfq_service_tree *st;
1167 	bool is_in_service;
1168 
1169 	if (!entity->on_st) /* entity never activated, or already inactive */
1170 		return false;
1171 
1172 	/*
1173 	 * If we get here, then entity is active, which implies that
1174 	 * bfq_group_set_parent has already been invoked for the group
1175 	 * represented by entity. Therefore, the field
1176 	 * entity->sched_data has been set, and we can safely use it.
1177 	 */
1178 	st = bfq_entity_service_tree(entity);
1179 	is_in_service = entity == sd->in_service_entity;
1180 
1181 	bfq_calc_finish(entity, entity->service);
1182 
1183 	if (is_in_service)
1184 		sd->in_service_entity = NULL;
1185 	else
1186 		/*
1187 		 * Non in-service entity: nobody will take care of
1188 		 * resetting its service counter on expiration. Do it
1189 		 * now.
1190 		 */
1191 		entity->service = 0;
1192 
1193 	if (entity->tree == &st->active)
1194 		bfq_active_extract(st, entity);
1195 	else if (!is_in_service && entity->tree == &st->idle)
1196 		bfq_idle_extract(st, entity);
1197 
1198 	if (!ins_into_idle_tree || !bfq_gt(entity->finish, st->vtime))
1199 		bfq_forget_entity(st, entity, is_in_service);
1200 	else
1201 		bfq_idle_insert(st, entity);
1202 
1203 	return true;
1204 }
1205 
1206 /**
1207  * bfq_deactivate_entity - deactivate an entity representing a bfq_queue.
1208  * @entity: the entity to deactivate.
1209  * @ins_into_idle_tree: true if the entity can be put into the idle tree
1210  * @expiration: true if this function is being invoked in the expiration path
1211  *             of the in-service queue
1212  */
1213 static void bfq_deactivate_entity(struct bfq_entity *entity,
1214 				  bool ins_into_idle_tree,
1215 				  bool expiration)
1216 {
1217 	struct bfq_sched_data *sd;
1218 	struct bfq_entity *parent = NULL;
1219 
1220 	for_each_entity_safe(entity, parent) {
1221 		sd = entity->sched_data;
1222 
1223 		if (!__bfq_deactivate_entity(entity, ins_into_idle_tree)) {
1224 			/*
1225 			 * entity is not in any tree any more, so
1226 			 * this deactivation is a no-op, and there is
1227 			 * nothing to change for upper-level entities
1228 			 * (in case of expiration, this can never
1229 			 * happen).
1230 			 */
1231 			return;
1232 		}
1233 
1234 		if (sd->next_in_service == entity)
1235 			/*
1236 			 * entity was the next_in_service entity,
1237 			 * then, since entity has just been
1238 			 * deactivated, a new one must be found.
1239 			 */
1240 			bfq_update_next_in_service(sd, NULL, expiration);
1241 
1242 		if (sd->next_in_service || sd->in_service_entity) {
1243 			/*
1244 			 * The parent entity is still active, because
1245 			 * either next_in_service or in_service_entity
1246 			 * is not NULL. So, no further upwards
1247 			 * deactivation must be performed.  Yet,
1248 			 * next_in_service has changed.	Then the
1249 			 * schedule does need to be updated upwards.
1250 			 *
1251 			 * NOTE If in_service_entity is not NULL, then
1252 			 * next_in_service may happen to be NULL,
1253 			 * although the parent entity is evidently
1254 			 * active. This happens if 1) the entity
1255 			 * pointed by in_service_entity is the only
1256 			 * active entity in the parent entity, and 2)
1257 			 * according to the definition of
1258 			 * next_in_service, the in_service_entity
1259 			 * cannot be considered as
1260 			 * next_in_service. See the comments on the
1261 			 * definition of next_in_service for details.
1262 			 */
1263 			break;
1264 		}
1265 
1266 		/*
1267 		 * If we get here, then the parent is no more
1268 		 * backlogged and we need to propagate the
1269 		 * deactivation upwards. Thus let the loop go on.
1270 		 */
1271 
1272 		/*
1273 		 * Also let parent be queued into the idle tree on
1274 		 * deactivation, to preserve service guarantees, and
1275 		 * assuming that who invoked this function does not
1276 		 * need parent entities too to be removed completely.
1277 		 */
1278 		ins_into_idle_tree = true;
1279 	}
1280 
1281 	/*
1282 	 * If the deactivation loop is fully executed, then there are
1283 	 * no more entities to touch and next loop is not executed at
1284 	 * all. Otherwise, requeue remaining entities if they are
1285 	 * about to stop receiving service, or reposition them if this
1286 	 * is not the case.
1287 	 */
1288 	entity = parent;
1289 	for_each_entity(entity) {
1290 		/*
1291 		 * Invoke __bfq_requeue_entity on entity, even if
1292 		 * already active, to requeue/reposition it in the
1293 		 * active tree (because sd->next_in_service has
1294 		 * changed)
1295 		 */
1296 		__bfq_requeue_entity(entity);
1297 
1298 		sd = entity->sched_data;
1299 		if (!bfq_update_next_in_service(sd, entity, expiration) &&
1300 		    !expiration)
1301 			/*
1302 			 * next_in_service unchanged or not causing
1303 			 * any change in entity->parent->sd, and no
1304 			 * requeueing needed for expiration: stop
1305 			 * here.
1306 			 */
1307 			break;
1308 	}
1309 }
1310 
1311 /**
1312  * bfq_calc_vtime_jump - compute the value to which the vtime should jump,
1313  *                       if needed, to have at least one entity eligible.
1314  * @st: the service tree to act upon.
1315  *
1316  * Assumes that st is not empty.
1317  */
1318 static u64 bfq_calc_vtime_jump(struct bfq_service_tree *st)
1319 {
1320 	struct bfq_entity *root_entity = bfq_root_active_entity(&st->active);
1321 
1322 	if (bfq_gt(root_entity->min_start, st->vtime))
1323 		return root_entity->min_start;
1324 
1325 	return st->vtime;
1326 }
1327 
1328 static void bfq_update_vtime(struct bfq_service_tree *st, u64 new_value)
1329 {
1330 	if (new_value > st->vtime) {
1331 		st->vtime = new_value;
1332 		bfq_forget_idle(st);
1333 	}
1334 }
1335 
1336 /**
1337  * bfq_first_active_entity - find the eligible entity with
1338  *                           the smallest finish time
1339  * @st: the service tree to select from.
1340  * @vtime: the system virtual to use as a reference for eligibility
1341  *
1342  * This function searches the first schedulable entity, starting from the
1343  * root of the tree and going on the left every time on this side there is
1344  * a subtree with at least one eligible (start <= vtime) entity. The path on
1345  * the right is followed only if a) the left subtree contains no eligible
1346  * entities and b) no eligible entity has been found yet.
1347  */
1348 static struct bfq_entity *bfq_first_active_entity(struct bfq_service_tree *st,
1349 						  u64 vtime)
1350 {
1351 	struct bfq_entity *entry, *first = NULL;
1352 	struct rb_node *node = st->active.rb_node;
1353 
1354 	while (node) {
1355 		entry = rb_entry(node, struct bfq_entity, rb_node);
1356 left:
1357 		if (!bfq_gt(entry->start, vtime))
1358 			first = entry;
1359 
1360 		if (node->rb_left) {
1361 			entry = rb_entry(node->rb_left,
1362 					 struct bfq_entity, rb_node);
1363 			if (!bfq_gt(entry->min_start, vtime)) {
1364 				node = node->rb_left;
1365 				goto left;
1366 			}
1367 		}
1368 		if (first)
1369 			break;
1370 		node = node->rb_right;
1371 	}
1372 
1373 	return first;
1374 }
1375 
1376 /**
1377  * __bfq_lookup_next_entity - return the first eligible entity in @st.
1378  * @st: the service tree.
1379  *
1380  * If there is no in-service entity for the sched_data st belongs to,
1381  * then return the entity that will be set in service if:
1382  * 1) the parent entity this st belongs to is set in service;
1383  * 2) no entity belonging to such parent entity undergoes a state change
1384  * that would influence the timestamps of the entity (e.g., becomes idle,
1385  * becomes backlogged, changes its budget, ...).
1386  *
1387  * In this first case, update the virtual time in @st too (see the
1388  * comments on this update inside the function).
1389  *
1390  * In contrast, if there is an in-service entity, then return the
1391  * entity that would be set in service if not only the above
1392  * conditions, but also the next one held true: the currently
1393  * in-service entity, on expiration,
1394  * 1) gets a finish time equal to the current one, or
1395  * 2) is not eligible any more, or
1396  * 3) is idle.
1397  */
1398 static struct bfq_entity *
1399 __bfq_lookup_next_entity(struct bfq_service_tree *st, bool in_service)
1400 {
1401 	struct bfq_entity *entity;
1402 	u64 new_vtime;
1403 
1404 	if (RB_EMPTY_ROOT(&st->active))
1405 		return NULL;
1406 
1407 	/*
1408 	 * Get the value of the system virtual time for which at
1409 	 * least one entity is eligible.
1410 	 */
1411 	new_vtime = bfq_calc_vtime_jump(st);
1412 
1413 	/*
1414 	 * If there is no in-service entity for the sched_data this
1415 	 * active tree belongs to, then push the system virtual time
1416 	 * up to the value that guarantees that at least one entity is
1417 	 * eligible. If, instead, there is an in-service entity, then
1418 	 * do not make any such update, because there is already an
1419 	 * eligible entity, namely the in-service one (even if the
1420 	 * entity is not on st, because it was extracted when set in
1421 	 * service).
1422 	 */
1423 	if (!in_service)
1424 		bfq_update_vtime(st, new_vtime);
1425 
1426 	entity = bfq_first_active_entity(st, new_vtime);
1427 
1428 	return entity;
1429 }
1430 
1431 /**
1432  * bfq_lookup_next_entity - return the first eligible entity in @sd.
1433  * @sd: the sched_data.
1434  * @expiration: true if we are on the expiration path of the in-service queue
1435  *
1436  * This function is invoked when there has been a change in the trees
1437  * for sd, and we need to know what is the new next entity to serve
1438  * after this change.
1439  */
1440 static struct bfq_entity *bfq_lookup_next_entity(struct bfq_sched_data *sd,
1441 						 bool expiration)
1442 {
1443 	struct bfq_service_tree *st = sd->service_tree;
1444 	struct bfq_service_tree *idle_class_st = st + (BFQ_IOPRIO_CLASSES - 1);
1445 	struct bfq_entity *entity = NULL;
1446 	int class_idx = 0;
1447 
1448 	/*
1449 	 * Choose from idle class, if needed to guarantee a minimum
1450 	 * bandwidth to this class (and if there is some active entity
1451 	 * in idle class). This should also mitigate
1452 	 * priority-inversion problems in case a low priority task is
1453 	 * holding file system resources.
1454 	 */
1455 	if (time_is_before_jiffies(sd->bfq_class_idle_last_service +
1456 				   BFQ_CL_IDLE_TIMEOUT)) {
1457 		if (!RB_EMPTY_ROOT(&idle_class_st->active))
1458 			class_idx = BFQ_IOPRIO_CLASSES - 1;
1459 		/* About to be served if backlogged, or not yet backlogged */
1460 		sd->bfq_class_idle_last_service = jiffies;
1461 	}
1462 
1463 	/*
1464 	 * Find the next entity to serve for the highest-priority
1465 	 * class, unless the idle class needs to be served.
1466 	 */
1467 	for (; class_idx < BFQ_IOPRIO_CLASSES; class_idx++) {
1468 		/*
1469 		 * If expiration is true, then bfq_lookup_next_entity
1470 		 * is being invoked as a part of the expiration path
1471 		 * of the in-service queue. In this case, even if
1472 		 * sd->in_service_entity is not NULL,
1473 		 * sd->in_service_entity at this point is actually not
1474 		 * in service any more, and, if needed, has already
1475 		 * been properly queued or requeued into the right
1476 		 * tree. The reason why sd->in_service_entity is still
1477 		 * not NULL here, even if expiration is true, is that
1478 		 * sd->in_service_entity is reset as a last step in the
1479 		 * expiration path. So, if expiration is true, tell
1480 		 * __bfq_lookup_next_entity that there is no
1481 		 * sd->in_service_entity.
1482 		 */
1483 		entity = __bfq_lookup_next_entity(st + class_idx,
1484 						  sd->in_service_entity &&
1485 						  !expiration);
1486 
1487 		if (entity)
1488 			break;
1489 	}
1490 
1491 	if (!entity)
1492 		return NULL;
1493 
1494 	return entity;
1495 }
1496 
1497 bool next_queue_may_preempt(struct bfq_data *bfqd)
1498 {
1499 	struct bfq_sched_data *sd = &bfqd->root_group->sched_data;
1500 
1501 	return sd->next_in_service != sd->in_service_entity;
1502 }
1503 
1504 /*
1505  * Get next queue for service.
1506  */
1507 struct bfq_queue *bfq_get_next_queue(struct bfq_data *bfqd)
1508 {
1509 	struct bfq_entity *entity = NULL;
1510 	struct bfq_sched_data *sd;
1511 	struct bfq_queue *bfqq;
1512 
1513 	if (bfq_tot_busy_queues(bfqd) == 0)
1514 		return NULL;
1515 
1516 	/*
1517 	 * Traverse the path from the root to the leaf entity to
1518 	 * serve. Set in service all the entities visited along the
1519 	 * way.
1520 	 */
1521 	sd = &bfqd->root_group->sched_data;
1522 	for (; sd ; sd = entity->my_sched_data) {
1523 		/*
1524 		 * WARNING. We are about to set the in-service entity
1525 		 * to sd->next_in_service, i.e., to the (cached) value
1526 		 * returned by bfq_lookup_next_entity(sd) the last
1527 		 * time it was invoked, i.e., the last time when the
1528 		 * service order in sd changed as a consequence of the
1529 		 * activation or deactivation of an entity. In this
1530 		 * respect, if we execute bfq_lookup_next_entity(sd)
1531 		 * in this very moment, it may, although with low
1532 		 * probability, yield a different entity than that
1533 		 * pointed to by sd->next_in_service. This rare event
1534 		 * happens in case there was no CLASS_IDLE entity to
1535 		 * serve for sd when bfq_lookup_next_entity(sd) was
1536 		 * invoked for the last time, while there is now one
1537 		 * such entity.
1538 		 *
1539 		 * If the above event happens, then the scheduling of
1540 		 * such entity in CLASS_IDLE is postponed until the
1541 		 * service of the sd->next_in_service entity
1542 		 * finishes. In fact, when the latter is expired,
1543 		 * bfq_lookup_next_entity(sd) gets called again,
1544 		 * exactly to update sd->next_in_service.
1545 		 */
1546 
1547 		/* Make next_in_service entity become in_service_entity */
1548 		entity = sd->next_in_service;
1549 		sd->in_service_entity = entity;
1550 
1551 		/*
1552 		 * If entity is no longer a candidate for next
1553 		 * service, then it must be extracted from its active
1554 		 * tree, so as to make sure that it won't be
1555 		 * considered when computing next_in_service. See the
1556 		 * comments on the function
1557 		 * bfq_no_longer_next_in_service() for details.
1558 		 */
1559 		if (bfq_no_longer_next_in_service(entity))
1560 			bfq_active_extract(bfq_entity_service_tree(entity),
1561 					   entity);
1562 
1563 		/*
1564 		 * Even if entity is not to be extracted according to
1565 		 * the above check, a descendant entity may get
1566 		 * extracted in one of the next iterations of this
1567 		 * loop. Such an event could cause a change in
1568 		 * next_in_service for the level of the descendant
1569 		 * entity, and thus possibly back to this level.
1570 		 *
1571 		 * However, we cannot perform the resulting needed
1572 		 * update of next_in_service for this level before the
1573 		 * end of the whole loop, because, to know which is
1574 		 * the correct next-to-serve candidate entity for each
1575 		 * level, we need first to find the leaf entity to set
1576 		 * in service. In fact, only after we know which is
1577 		 * the next-to-serve leaf entity, we can discover
1578 		 * whether the parent entity of the leaf entity
1579 		 * becomes the next-to-serve, and so on.
1580 		 */
1581 	}
1582 
1583 	bfqq = bfq_entity_to_bfqq(entity);
1584 
1585 	/*
1586 	 * We can finally update all next-to-serve entities along the
1587 	 * path from the leaf entity just set in service to the root.
1588 	 */
1589 	for_each_entity(entity) {
1590 		struct bfq_sched_data *sd = entity->sched_data;
1591 
1592 		if (!bfq_update_next_in_service(sd, NULL, false))
1593 			break;
1594 	}
1595 
1596 	return bfqq;
1597 }
1598 
1599 /* returns true if the in-service queue gets freed */
1600 bool __bfq_bfqd_reset_in_service(struct bfq_data *bfqd)
1601 {
1602 	struct bfq_queue *in_serv_bfqq = bfqd->in_service_queue;
1603 	struct bfq_entity *in_serv_entity = &in_serv_bfqq->entity;
1604 	struct bfq_entity *entity = in_serv_entity;
1605 
1606 	bfq_clear_bfqq_wait_request(in_serv_bfqq);
1607 	hrtimer_try_to_cancel(&bfqd->idle_slice_timer);
1608 	bfqd->in_service_queue = NULL;
1609 
1610 	/*
1611 	 * When this function is called, all in-service entities have
1612 	 * been properly deactivated or requeued, so we can safely
1613 	 * execute the final step: reset in_service_entity along the
1614 	 * path from entity to the root.
1615 	 */
1616 	for_each_entity(entity)
1617 		entity->sched_data->in_service_entity = NULL;
1618 
1619 	/*
1620 	 * in_serv_entity is no longer in service, so, if it is in no
1621 	 * service tree either, then release the service reference to
1622 	 * the queue it represents (taken with bfq_get_entity).
1623 	 */
1624 	if (!in_serv_entity->on_st) {
1625 		/*
1626 		 * If no process is referencing in_serv_bfqq any
1627 		 * longer, then the service reference may be the only
1628 		 * reference to the queue. If this is the case, then
1629 		 * bfqq gets freed here.
1630 		 */
1631 		int ref = in_serv_bfqq->ref;
1632 		bfq_put_queue(in_serv_bfqq);
1633 		if (ref == 1)
1634 			return true;
1635 	}
1636 
1637 	return false;
1638 }
1639 
1640 void bfq_deactivate_bfqq(struct bfq_data *bfqd, struct bfq_queue *bfqq,
1641 			 bool ins_into_idle_tree, bool expiration)
1642 {
1643 	struct bfq_entity *entity = &bfqq->entity;
1644 
1645 	bfq_deactivate_entity(entity, ins_into_idle_tree, expiration);
1646 }
1647 
1648 void bfq_activate_bfqq(struct bfq_data *bfqd, struct bfq_queue *bfqq)
1649 {
1650 	struct bfq_entity *entity = &bfqq->entity;
1651 
1652 	bfq_activate_requeue_entity(entity, bfq_bfqq_non_blocking_wait_rq(bfqq),
1653 				    false, false);
1654 	bfq_clear_bfqq_non_blocking_wait_rq(bfqq);
1655 }
1656 
1657 void bfq_requeue_bfqq(struct bfq_data *bfqd, struct bfq_queue *bfqq,
1658 		      bool expiration)
1659 {
1660 	struct bfq_entity *entity = &bfqq->entity;
1661 
1662 	bfq_activate_requeue_entity(entity, false,
1663 				    bfqq == bfqd->in_service_queue, expiration);
1664 }
1665 
1666 /*
1667  * Called when the bfqq no longer has requests pending, remove it from
1668  * the service tree. As a special case, it can be invoked during an
1669  * expiration.
1670  */
1671 void bfq_del_bfqq_busy(struct bfq_data *bfqd, struct bfq_queue *bfqq,
1672 		       bool expiration)
1673 {
1674 	bfq_log_bfqq(bfqd, bfqq, "del from busy");
1675 
1676 	bfq_clear_bfqq_busy(bfqq);
1677 
1678 	bfqd->busy_queues[bfqq->ioprio_class - 1]--;
1679 
1680 	if (bfqq->wr_coeff > 1)
1681 		bfqd->wr_busy_queues--;
1682 
1683 	bfqg_stats_update_dequeue(bfqq_group(bfqq));
1684 
1685 	bfq_deactivate_bfqq(bfqd, bfqq, true, expiration);
1686 
1687 	if (!bfqq->dispatched)
1688 		bfq_weights_tree_remove(bfqd, bfqq);
1689 }
1690 
1691 /*
1692  * Called when an inactive queue receives a new request.
1693  */
1694 void bfq_add_bfqq_busy(struct bfq_data *bfqd, struct bfq_queue *bfqq)
1695 {
1696 	bfq_log_bfqq(bfqd, bfqq, "add to busy");
1697 
1698 	bfq_activate_bfqq(bfqd, bfqq);
1699 
1700 	bfq_mark_bfqq_busy(bfqq);
1701 	bfqd->busy_queues[bfqq->ioprio_class - 1]++;
1702 
1703 	if (!bfqq->dispatched)
1704 		if (bfqq->wr_coeff == 1)
1705 			bfq_weights_tree_add(bfqd, bfqq,
1706 					     &bfqd->queue_weights_tree);
1707 
1708 	if (bfqq->wr_coeff > 1)
1709 		bfqd->wr_busy_queues++;
1710 }
1711