1/* 2 * Budget Fair Queueing (BFQ) I/O scheduler. 3 * 4 * Based on ideas and code from CFQ: 5 * Copyright (C) 2003 Jens Axboe <axboe@kernel.dk> 6 * 7 * Copyright (C) 2008 Fabio Checconi <fabio@gandalf.sssup.it> 8 * Paolo Valente <paolo.valente@unimore.it> 9 * 10 * Copyright (C) 2010 Paolo Valente <paolo.valente@unimore.it> 11 * Arianna Avanzini <avanzini@google.com> 12 * 13 * Copyright (C) 2017 Paolo Valente <paolo.valente@linaro.org> 14 * 15 * This program is free software; you can redistribute it and/or 16 * modify it under the terms of the GNU General Public License as 17 * published by the Free Software Foundation; either version 2 of the 18 * License, or (at your option) any later version. 19 * 20 * This program is distributed in the hope that it will be useful, 21 * but WITHOUT ANY WARRANTY; without even the implied warranty of 22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 23 * General Public License for more details. 24 * 25 * BFQ is a proportional-share I/O scheduler, with some extra 26 * low-latency capabilities. BFQ also supports full hierarchical 27 * scheduling through cgroups. Next paragraphs provide an introduction 28 * on BFQ inner workings. Details on BFQ benefits, usage and 29 * limitations can be found in Documentation/block/bfq-iosched.txt. 30 * 31 * BFQ is a proportional-share storage-I/O scheduling algorithm based 32 * on the slice-by-slice service scheme of CFQ. But BFQ assigns 33 * budgets, measured in number of sectors, to processes instead of 34 * time slices. The device is not granted to the in-service process 35 * for a given time slice, but until it has exhausted its assigned 36 * budget. This change from the time to the service domain enables BFQ 37 * to distribute the device throughput among processes as desired, 38 * without any distortion due to throughput fluctuations, or to device 39 * internal queueing. BFQ uses an ad hoc internal scheduler, called 40 * B-WF2Q+, to schedule processes according to their budgets. More 41 * precisely, BFQ schedules queues associated with processes. Each 42 * process/queue is assigned a user-configurable weight, and B-WF2Q+ 43 * guarantees that each queue receives a fraction of the throughput 44 * proportional to its weight. Thanks to the accurate policy of 45 * B-WF2Q+, BFQ can afford to assign high budgets to I/O-bound 46 * processes issuing sequential requests (to boost the throughput), 47 * and yet guarantee a low latency to interactive and soft real-time 48 * applications. 49 * 50 * In particular, to provide these low-latency guarantees, BFQ 51 * explicitly privileges the I/O of two classes of time-sensitive 52 * applications: interactive and soft real-time. In more detail, BFQ 53 * behaves this way if the low_latency parameter is set (default 54 * configuration). This feature enables BFQ to provide applications in 55 * these classes with a very low latency. 56 * 57 * To implement this feature, BFQ constantly tries to detect whether 58 * the I/O requests in a bfq_queue come from an interactive or a soft 59 * real-time application. For brevity, in these cases, the queue is 60 * said to be interactive or soft real-time. In both cases, BFQ 61 * privileges the service of the queue, over that of non-interactive 62 * and non-soft-real-time queues. This privileging is performed, 63 * mainly, by raising the weight of the queue. So, for brevity, we 64 * call just weight-raising periods the time periods during which a 65 * queue is privileged, because deemed interactive or soft real-time. 66 * 67 * The detection of soft real-time queues/applications is described in 68 * detail in the comments on the function 69 * bfq_bfqq_softrt_next_start. On the other hand, the detection of an 70 * interactive queue works as follows: a queue is deemed interactive 71 * if it is constantly non empty only for a limited time interval, 72 * after which it does become empty. The queue may be deemed 73 * interactive again (for a limited time), if it restarts being 74 * constantly non empty, provided that this happens only after the 75 * queue has remained empty for a given minimum idle time. 76 * 77 * By default, BFQ computes automatically the above maximum time 78 * interval, i.e., the time interval after which a constantly 79 * non-empty queue stops being deemed interactive. Since a queue is 80 * weight-raised while it is deemed interactive, this maximum time 81 * interval happens to coincide with the (maximum) duration of the 82 * weight-raising for interactive queues. 83 * 84 * Finally, BFQ also features additional heuristics for 85 * preserving both a low latency and a high throughput on NCQ-capable, 86 * rotational or flash-based devices, and to get the job done quickly 87 * for applications consisting in many I/O-bound processes. 88 * 89 * NOTE: if the main or only goal, with a given device, is to achieve 90 * the maximum-possible throughput at all times, then do switch off 91 * all low-latency heuristics for that device, by setting low_latency 92 * to 0. 93 * 94 * BFQ is described in [1], where also a reference to the initial, 95 * more theoretical paper on BFQ can be found. The interested reader 96 * can find in the latter paper full details on the main algorithm, as 97 * well as formulas of the guarantees and formal proofs of all the 98 * properties. With respect to the version of BFQ presented in these 99 * papers, this implementation adds a few more heuristics, such as the 100 * ones that guarantee a low latency to interactive and soft real-time 101 * applications, and a hierarchical extension based on H-WF2Q+. 102 * 103 * B-WF2Q+ is based on WF2Q+, which is described in [2], together with 104 * H-WF2Q+, while the augmented tree used here to implement B-WF2Q+ 105 * with O(log N) complexity derives from the one introduced with EEVDF 106 * in [3]. 107 * 108 * [1] P. Valente, A. Avanzini, "Evolution of the BFQ Storage I/O 109 * Scheduler", Proceedings of the First Workshop on Mobile System 110 * Technologies (MST-2015), May 2015. 111 * http://algogroup.unimore.it/people/paolo/disk_sched/mst-2015.pdf 112 * 113 * [2] Jon C.R. Bennett and H. Zhang, "Hierarchical Packet Fair Queueing 114 * Algorithms", IEEE/ACM Transactions on Networking, 5(5):675-689, 115 * Oct 1997. 116 * 117 * http://www.cs.cmu.edu/~hzhang/papers/TON-97-Oct.ps.gz 118 * 119 * [3] I. Stoica and H. Abdel-Wahab, "Earliest Eligible Virtual Deadline 120 * First: A Flexible and Accurate Mechanism for Proportional Share 121 * Resource Allocation", technical report. 122 * 123 * http://www.cs.berkeley.edu/~istoica/papers/eevdf-tr-95.pdf 124 */ 125#include <linux/module.h> 126#include <linux/slab.h> 127#include <linux/blkdev.h> 128#include <linux/cgroup.h> 129#include <linux/elevator.h> 130#include <linux/ktime.h> 131#include <linux/rbtree.h> 132#include <linux/ioprio.h> 133#include <linux/sbitmap.h> 134#include <linux/delay.h> 135#include <linux/backing-dev.h> 136 137#include <trace/events/block.h> 138 139#include "blk.h" 140#include "blk-mq.h" 141#include "blk-mq-tag.h" 142#include "blk-mq-sched.h" 143#include "bfq-iosched.h" 144#include "blk-wbt.h" 145 146#define BFQ_BFQQ_FNS(name) \ 147void bfq_mark_bfqq_##name(struct bfq_queue *bfqq) \ 148{ \ 149 __set_bit(BFQQF_##name, &(bfqq)->flags); \ 150} \ 151void bfq_clear_bfqq_##name(struct bfq_queue *bfqq) \ 152{ \ 153 __clear_bit(BFQQF_##name, &(bfqq)->flags); \ 154} \ 155int bfq_bfqq_##name(const struct bfq_queue *bfqq) \ 156{ \ 157 return test_bit(BFQQF_##name, &(bfqq)->flags); \ 158} 159 160BFQ_BFQQ_FNS(just_created); 161BFQ_BFQQ_FNS(busy); 162BFQ_BFQQ_FNS(wait_request); 163BFQ_BFQQ_FNS(non_blocking_wait_rq); 164BFQ_BFQQ_FNS(fifo_expire); 165BFQ_BFQQ_FNS(has_short_ttime); 166BFQ_BFQQ_FNS(sync); 167BFQ_BFQQ_FNS(IO_bound); 168BFQ_BFQQ_FNS(in_large_burst); 169BFQ_BFQQ_FNS(coop); 170BFQ_BFQQ_FNS(split_coop); 171BFQ_BFQQ_FNS(softrt_update); 172#undef BFQ_BFQQ_FNS \ 173 174/* Expiration time of async (0) and sync (1) requests, in ns. */ 175static const u64 bfq_fifo_expire[2] = { NSEC_PER_SEC / 4, NSEC_PER_SEC / 8 }; 176 177/* Maximum backwards seek (magic number lifted from CFQ), in KiB. */ 178static const int bfq_back_max = 16 * 1024; 179 180/* Penalty of a backwards seek, in number of sectors. */ 181static const int bfq_back_penalty = 2; 182 183/* Idling period duration, in ns. */ 184static u64 bfq_slice_idle = NSEC_PER_SEC / 125; 185 186/* Minimum number of assigned budgets for which stats are safe to compute. */ 187static const int bfq_stats_min_budgets = 194; 188 189/* Default maximum budget values, in sectors and number of requests. */ 190static const int bfq_default_max_budget = 16 * 1024; 191 192/* 193 * When a sync request is dispatched, the queue that contains that 194 * request, and all the ancestor entities of that queue, are charged 195 * with the number of sectors of the request. In constrast, if the 196 * request is async, then the queue and its ancestor entities are 197 * charged with the number of sectors of the request, multiplied by 198 * the factor below. This throttles the bandwidth for async I/O, 199 * w.r.t. to sync I/O, and it is done to counter the tendency of async 200 * writes to steal I/O throughput to reads. 201 * 202 * The current value of this parameter is the result of a tuning with 203 * several hardware and software configurations. We tried to find the 204 * lowest value for which writes do not cause noticeable problems to 205 * reads. In fact, the lower this parameter, the stabler I/O control, 206 * in the following respect. The lower this parameter is, the less 207 * the bandwidth enjoyed by a group decreases 208 * - when the group does writes, w.r.t. to when it does reads; 209 * - when other groups do reads, w.r.t. to when they do writes. 210 */ 211static const int bfq_async_charge_factor = 3; 212 213/* Default timeout values, in jiffies, approximating CFQ defaults. */ 214const int bfq_timeout = HZ / 8; 215 216/* 217 * Time limit for merging (see comments in bfq_setup_cooperator). Set 218 * to the slowest value that, in our tests, proved to be effective in 219 * removing false positives, while not causing true positives to miss 220 * queue merging. 221 * 222 * As can be deduced from the low time limit below, queue merging, if 223 * successful, happens at the very beggining of the I/O of the involved 224 * cooperating processes, as a consequence of the arrival of the very 225 * first requests from each cooperator. After that, there is very 226 * little chance to find cooperators. 227 */ 228static const unsigned long bfq_merge_time_limit = HZ/10; 229 230static struct kmem_cache *bfq_pool; 231 232/* Below this threshold (in ns), we consider thinktime immediate. */ 233#define BFQ_MIN_TT (2 * NSEC_PER_MSEC) 234 235/* hw_tag detection: parallel requests threshold and min samples needed. */ 236#define BFQ_HW_QUEUE_THRESHOLD 3 237#define BFQ_HW_QUEUE_SAMPLES 32 238 239#define BFQQ_SEEK_THR (sector_t)(8 * 100) 240#define BFQQ_SECT_THR_NONROT (sector_t)(2 * 32) 241#define BFQ_RQ_SEEKY(bfqd, last_pos, rq) \ 242 (get_sdist(last_pos, rq) > \ 243 BFQQ_SEEK_THR && \ 244 (!blk_queue_nonrot(bfqd->queue) || \ 245 blk_rq_sectors(rq) < BFQQ_SECT_THR_NONROT)) 246#define BFQQ_CLOSE_THR (sector_t)(8 * 1024) 247#define BFQQ_SEEKY(bfqq) (hweight32(bfqq->seek_history) > 19) 248/* 249 * Sync random I/O is likely to be confused with soft real-time I/O, 250 * because it is characterized by limited throughput and apparently 251 * isochronous arrival pattern. To avoid false positives, queues 252 * containing only random (seeky) I/O are prevented from being tagged 253 * as soft real-time. 254 */ 255#define BFQQ_TOTALLY_SEEKY(bfqq) (bfqq->seek_history & -1) 256 257/* Min number of samples required to perform peak-rate update */ 258#define BFQ_RATE_MIN_SAMPLES 32 259/* Min observation time interval required to perform a peak-rate update (ns) */ 260#define BFQ_RATE_MIN_INTERVAL (300*NSEC_PER_MSEC) 261/* Target observation time interval for a peak-rate update (ns) */ 262#define BFQ_RATE_REF_INTERVAL NSEC_PER_SEC 263 264/* 265 * Shift used for peak-rate fixed precision calculations. 266 * With 267 * - the current shift: 16 positions 268 * - the current type used to store rate: u32 269 * - the current unit of measure for rate: [sectors/usec], or, more precisely, 270 * [(sectors/usec) / 2^BFQ_RATE_SHIFT] to take into account the shift, 271 * the range of rates that can be stored is 272 * [1 / 2^BFQ_RATE_SHIFT, 2^(32 - BFQ_RATE_SHIFT)] sectors/usec = 273 * [1 / 2^16, 2^16] sectors/usec = [15e-6, 65536] sectors/usec = 274 * [15, 65G] sectors/sec 275 * Which, assuming a sector size of 512B, corresponds to a range of 276 * [7.5K, 33T] B/sec 277 */ 278#define BFQ_RATE_SHIFT 16 279 280/* 281 * When configured for computing the duration of the weight-raising 282 * for interactive queues automatically (see the comments at the 283 * beginning of this file), BFQ does it using the following formula: 284 * duration = (ref_rate / r) * ref_wr_duration, 285 * where r is the peak rate of the device, and ref_rate and 286 * ref_wr_duration are two reference parameters. In particular, 287 * ref_rate is the peak rate of the reference storage device (see 288 * below), and ref_wr_duration is about the maximum time needed, with 289 * BFQ and while reading two files in parallel, to load typical large 290 * applications on the reference device (see the comments on 291 * max_service_from_wr below, for more details on how ref_wr_duration 292 * is obtained). In practice, the slower/faster the device at hand 293 * is, the more/less it takes to load applications with respect to the 294 * reference device. Accordingly, the longer/shorter BFQ grants 295 * weight raising to interactive applications. 296 * 297 * BFQ uses two different reference pairs (ref_rate, ref_wr_duration), 298 * depending on whether the device is rotational or non-rotational. 299 * 300 * In the following definitions, ref_rate[0] and ref_wr_duration[0] 301 * are the reference values for a rotational device, whereas 302 * ref_rate[1] and ref_wr_duration[1] are the reference values for a 303 * non-rotational device. The reference rates are not the actual peak 304 * rates of the devices used as a reference, but slightly lower 305 * values. The reason for using slightly lower values is that the 306 * peak-rate estimator tends to yield slightly lower values than the 307 * actual peak rate (it can yield the actual peak rate only if there 308 * is only one process doing I/O, and the process does sequential 309 * I/O). 310 * 311 * The reference peak rates are measured in sectors/usec, left-shifted 312 * by BFQ_RATE_SHIFT. 313 */ 314static int ref_rate[2] = {14000, 33000}; 315/* 316 * To improve readability, a conversion function is used to initialize 317 * the following array, which entails that the array can be 318 * initialized only in a function. 319 */ 320static int ref_wr_duration[2]; 321 322/* 323 * BFQ uses the above-detailed, time-based weight-raising mechanism to 324 * privilege interactive tasks. This mechanism is vulnerable to the 325 * following false positives: I/O-bound applications that will go on 326 * doing I/O for much longer than the duration of weight 327 * raising. These applications have basically no benefit from being 328 * weight-raised at the beginning of their I/O. On the opposite end, 329 * while being weight-raised, these applications 330 * a) unjustly steal throughput to applications that may actually need 331 * low latency; 332 * b) make BFQ uselessly perform device idling; device idling results 333 * in loss of device throughput with most flash-based storage, and may 334 * increase latencies when used purposelessly. 335 * 336 * BFQ tries to reduce these problems, by adopting the following 337 * countermeasure. To introduce this countermeasure, we need first to 338 * finish explaining how the duration of weight-raising for 339 * interactive tasks is computed. 340 * 341 * For a bfq_queue deemed as interactive, the duration of weight 342 * raising is dynamically adjusted, as a function of the estimated 343 * peak rate of the device, so as to be equal to the time needed to 344 * execute the 'largest' interactive task we benchmarked so far. By 345 * largest task, we mean the task for which each involved process has 346 * to do more I/O than for any of the other tasks we benchmarked. This 347 * reference interactive task is the start-up of LibreOffice Writer, 348 * and in this task each process/bfq_queue needs to have at most ~110K 349 * sectors transferred. 350 * 351 * This last piece of information enables BFQ to reduce the actual 352 * duration of weight-raising for at least one class of I/O-bound 353 * applications: those doing sequential or quasi-sequential I/O. An 354 * example is file copy. In fact, once started, the main I/O-bound 355 * processes of these applications usually consume the above 110K 356 * sectors in much less time than the processes of an application that 357 * is starting, because these I/O-bound processes will greedily devote 358 * almost all their CPU cycles only to their target, 359 * throughput-friendly I/O operations. This is even more true if BFQ 360 * happens to be underestimating the device peak rate, and thus 361 * overestimating the duration of weight raising. But, according to 362 * our measurements, once transferred 110K sectors, these processes 363 * have no right to be weight-raised any longer. 364 * 365 * Basing on the last consideration, BFQ ends weight-raising for a 366 * bfq_queue if the latter happens to have received an amount of 367 * service at least equal to the following constant. The constant is 368 * set to slightly more than 110K, to have a minimum safety margin. 369 * 370 * This early ending of weight-raising reduces the amount of time 371 * during which interactive false positives cause the two problems 372 * described at the beginning of these comments. 373 */ 374static const unsigned long max_service_from_wr = 120000; 375 376/* 377 * Maximum time between the creation of two queues, for stable merge 378 * to be activated (in ms) 379 */ 380static const unsigned long bfq_activation_stable_merging = 600; 381/* 382 * Minimum time to be waited before evaluating delayed stable merge (in ms) 383 */ 384static const unsigned long bfq_late_stable_merging = 600; 385 386#define RQ_BIC(rq) icq_to_bic((rq)->elv.priv[0]) 387#define RQ_BFQQ(rq) ((rq)->elv.priv[1]) 388 389struct bfq_queue *bic_to_bfqq(struct bfq_io_cq *bic, bool is_sync) 390{ 391 return bic->bfqq[is_sync]; 392} 393 394static void bfq_put_stable_ref(struct bfq_queue *bfqq); 395 396void bic_set_bfqq(struct bfq_io_cq *bic, struct bfq_queue *bfqq, bool is_sync) 397{ 398 /* 399 * If bfqq != NULL, then a non-stable queue merge between 400 * bic->bfqq and bfqq is happening here. This causes troubles 401 * in the following case: bic->bfqq has also been scheduled 402 * for a possible stable merge with bic->stable_merge_bfqq, 403 * and bic->stable_merge_bfqq == bfqq happens to 404 * hold. Troubles occur because bfqq may then undergo a split, 405 * thereby becoming eligible for a stable merge. Yet, if 406 * bic->stable_merge_bfqq points exactly to bfqq, then bfqq 407 * would be stably merged with itself. To avoid this anomaly, 408 * we cancel the stable merge if 409 * bic->stable_merge_bfqq == bfqq. 410 */ 411 bic->bfqq[is_sync] = bfqq; 412 413 if (bfqq && bic->stable_merge_bfqq == bfqq) { 414 /* 415 * Actually, these same instructions are executed also 416 * in bfq_setup_cooperator, in case of abort or actual 417 * execution of a stable merge. We could avoid 418 * repeating these instructions there too, but if we 419 * did so, we would nest even more complexity in this 420 * function. 421 */ 422 bfq_put_stable_ref(bic->stable_merge_bfqq); 423 424 bic->stable_merge_bfqq = NULL; 425 } 426} 427 428struct bfq_data *bic_to_bfqd(struct bfq_io_cq *bic) 429{ 430 return bic->icq.q->elevator->elevator_data; 431} 432 433/** 434 * icq_to_bic - convert iocontext queue structure to bfq_io_cq. 435 * @icq: the iocontext queue. 436 */ 437static struct bfq_io_cq *icq_to_bic(struct io_cq *icq) 438{ 439 /* bic->icq is the first member, %NULL will convert to %NULL */ 440 return container_of(icq, struct bfq_io_cq, icq); 441} 442 443/** 444 * bfq_bic_lookup - search into @ioc a bic associated to @bfqd. 445 * @bfqd: the lookup key. 446 * @ioc: the io_context of the process doing I/O. 447 * @q: the request queue. 448 */ 449static struct bfq_io_cq *bfq_bic_lookup(struct bfq_data *bfqd, 450 struct io_context *ioc, 451 struct request_queue *q) 452{ 453 if (ioc) { 454 unsigned long flags; 455 struct bfq_io_cq *icq; 456 457 spin_lock_irqsave(&q->queue_lock, flags); 458 icq = icq_to_bic(ioc_lookup_icq(ioc, q)); 459 spin_unlock_irqrestore(&q->queue_lock, flags); 460 461 return icq; 462 } 463 464 return NULL; 465} 466 467/* 468 * Scheduler run of queue, if there are requests pending and no one in the 469 * driver that will restart queueing. 470 */ 471void bfq_schedule_dispatch(struct bfq_data *bfqd) 472{ 473 if (bfqd->queued != 0) { 474 bfq_log(bfqd, "schedule dispatch"); 475 blk_mq_run_hw_queues(bfqd->queue, true); 476 } 477} 478 479#define bfq_class_idle(bfqq) ((bfqq)->ioprio_class == IOPRIO_CLASS_IDLE) 480 481#define bfq_sample_valid(samples) ((samples) > 80) 482 483/* 484 * Lifted from AS - choose which of rq1 and rq2 that is best served now. 485 * We choose the request that is closesr to the head right now. Distance 486 * behind the head is penalized and only allowed to a certain extent. 487 */ 488static struct request *bfq_choose_req(struct bfq_data *bfqd, 489 struct request *rq1, 490 struct request *rq2, 491 sector_t last) 492{ 493 sector_t s1, s2, d1 = 0, d2 = 0; 494 unsigned long back_max; 495#define BFQ_RQ1_WRAP 0x01 /* request 1 wraps */ 496#define BFQ_RQ2_WRAP 0x02 /* request 2 wraps */ 497 unsigned int wrap = 0; /* bit mask: requests behind the disk head? */ 498 499 if (!rq1 || rq1 == rq2) 500 return rq2; 501 if (!rq2) 502 return rq1; 503 504 if (rq_is_sync(rq1) && !rq_is_sync(rq2)) 505 return rq1; 506 else if (rq_is_sync(rq2) && !rq_is_sync(rq1)) 507 return rq2; 508 if ((rq1->cmd_flags & REQ_META) && !(rq2->cmd_flags & REQ_META)) 509 return rq1; 510 else if ((rq2->cmd_flags & REQ_META) && !(rq1->cmd_flags & REQ_META)) 511 return rq2; 512 513 s1 = blk_rq_pos(rq1); 514 s2 = blk_rq_pos(rq2); 515 516 /* 517 * By definition, 1KiB is 2 sectors. 518 */ 519 back_max = bfqd->bfq_back_max * 2; 520 521 /* 522 * Strict one way elevator _except_ in the case where we allow 523 * short backward seeks which are biased as twice the cost of a 524 * similar forward seek. 525 */ 526 if (s1 >= last) 527 d1 = s1 - last; 528 else if (s1 + back_max >= last) 529 d1 = (last - s1) * bfqd->bfq_back_penalty; 530 else 531 wrap |= BFQ_RQ1_WRAP; 532 533 if (s2 >= last) 534 d2 = s2 - last; 535 else if (s2 + back_max >= last) 536 d2 = (last - s2) * bfqd->bfq_back_penalty; 537 else 538 wrap |= BFQ_RQ2_WRAP; 539 540 /* Found required data */ 541 542 /* 543 * By doing switch() on the bit mask "wrap" we avoid having to 544 * check two variables for all permutations: --> faster! 545 */ 546 switch (wrap) { 547 case 0: /* common case for CFQ: rq1 and rq2 not wrapped */ 548 if (d1 < d2) 549 return rq1; 550 else if (d2 < d1) 551 return rq2; 552 553 if (s1 >= s2) 554 return rq1; 555 else 556 return rq2; 557 558 case BFQ_RQ2_WRAP: 559 return rq1; 560 case BFQ_RQ1_WRAP: 561 return rq2; 562 case BFQ_RQ1_WRAP|BFQ_RQ2_WRAP: /* both rqs wrapped */ 563 default: 564 /* 565 * Since both rqs are wrapped, 566 * start with the one that's further behind head 567 * (--> only *one* back seek required), 568 * since back seek takes more time than forward. 569 */ 570 if (s1 <= s2) 571 return rq1; 572 else 573 return rq2; 574 } 575} 576 577/* 578 * Async I/O can easily starve sync I/O (both sync reads and sync 579 * writes), by consuming all tags. Similarly, storms of sync writes, 580 * such as those that sync(2) may trigger, can starve sync reads. 581 * Limit depths of async I/O and sync writes so as to counter both 582 * problems. 583 */ 584static void bfq_limit_depth(unsigned int op, struct blk_mq_alloc_data *data) 585{ 586 struct bfq_data *bfqd = data->q->elevator->elevator_data; 587 588 if (op_is_sync(op) && !op_is_write(op)) 589 return; 590 591 data->shallow_depth = 592 bfqd->word_depths[!!bfqd->wr_busy_queues][op_is_sync(op)]; 593 594 bfq_log(bfqd, "[%s] wr_busy %d sync %d depth %u", 595 __func__, bfqd->wr_busy_queues, op_is_sync(op), 596 data->shallow_depth); 597} 598 599static struct bfq_queue * 600bfq_rq_pos_tree_lookup(struct bfq_data *bfqd, struct rb_root *root, 601 sector_t sector, struct rb_node **ret_parent, 602 struct rb_node ***rb_link) 603{ 604 struct rb_node **p, *parent; 605 struct bfq_queue *bfqq = NULL; 606 607 parent = NULL; 608 p = &root->rb_node; 609 while (*p) { 610 struct rb_node **n; 611 612 parent = *p; 613 bfqq = rb_entry(parent, struct bfq_queue, pos_node); 614 615 /* 616 * Sort strictly based on sector. Smallest to the left, 617 * largest to the right. 618 */ 619 if (sector > blk_rq_pos(bfqq->next_rq)) 620 n = &(*p)->rb_right; 621 else if (sector < blk_rq_pos(bfqq->next_rq)) 622 n = &(*p)->rb_left; 623 else 624 break; 625 p = n; 626 bfqq = NULL; 627 } 628 629 *ret_parent = parent; 630 if (rb_link) 631 *rb_link = p; 632 633 bfq_log(bfqd, "rq_pos_tree_lookup %llu: returning %d", 634 (unsigned long long)sector, 635 bfqq ? bfqq->pid : 0); 636 637 return bfqq; 638} 639 640static bool bfq_too_late_for_merging(struct bfq_queue *bfqq) 641{ 642 return bfqq->service_from_backlogged > 0 && 643 time_is_before_jiffies(bfqq->first_IO_time + 644 bfq_merge_time_limit); 645} 646 647/* 648 * The following function is not marked as __cold because it is 649 * actually cold, but for the same performance goal described in the 650 * comments on the likely() at the beginning of 651 * bfq_setup_cooperator(). Unexpectedly, to reach an even lower 652 * execution time for the case where this function is not invoked, we 653 * had to add an unlikely() in each involved if(). 654 */ 655void __cold 656bfq_pos_tree_add_move(struct bfq_data *bfqd, struct bfq_queue *bfqq) 657{ 658 struct rb_node **p, *parent; 659 struct bfq_queue *__bfqq; 660 661 if (bfqq->pos_root) { 662 rb_erase(&bfqq->pos_node, bfqq->pos_root); 663 bfqq->pos_root = NULL; 664 } 665 666 /* oom_bfqq does not participate in queue merging */ 667 if (bfqq == &bfqd->oom_bfqq) 668 return; 669 670 /* 671 * bfqq cannot be merged any longer (see comments in 672 * bfq_setup_cooperator): no point in adding bfqq into the 673 * position tree. 674 */ 675 if (bfq_too_late_for_merging(bfqq)) 676 return; 677 678 if (bfq_class_idle(bfqq)) 679 return; 680 if (!bfqq->next_rq) 681 return; 682 683 bfqq->pos_root = &bfq_bfqq_to_bfqg(bfqq)->rq_pos_tree; 684 __bfqq = bfq_rq_pos_tree_lookup(bfqd, bfqq->pos_root, 685 blk_rq_pos(bfqq->next_rq), &parent, &p); 686 if (!__bfqq) { 687 rb_link_node(&bfqq->pos_node, parent, p); 688 rb_insert_color(&bfqq->pos_node, bfqq->pos_root); 689 } else 690 bfqq->pos_root = NULL; 691} 692 693/* 694 * The following function returns false either if every active queue 695 * must receive the same share of the throughput (symmetric scenario), 696 * or, as a special case, if bfqq must receive a share of the 697 * throughput lower than or equal to the share that every other active 698 * queue must receive. If bfqq does sync I/O, then these are the only 699 * two cases where bfqq happens to be guaranteed its share of the 700 * throughput even if I/O dispatching is not plugged when bfqq remains 701 * temporarily empty (for more details, see the comments in the 702 * function bfq_better_to_idle()). For this reason, the return value 703 * of this function is used to check whether I/O-dispatch plugging can 704 * be avoided. 705 * 706 * The above first case (symmetric scenario) occurs when: 707 * 1) all active queues have the same weight, 708 * 2) all active queues belong to the same I/O-priority class, 709 * 3) all active groups at the same level in the groups tree have the same 710 * weight, 711 * 4) all active groups at the same level in the groups tree have the same 712 * number of children. 713 * 714 * Unfortunately, keeping the necessary state for evaluating exactly 715 * the last two symmetry sub-conditions above would be quite complex 716 * and time consuming. Therefore this function evaluates, instead, 717 * only the following stronger three sub-conditions, for which it is 718 * much easier to maintain the needed state: 719 * 1) all active queues have the same weight, 720 * 2) all active queues belong to the same I/O-priority class, 721 * 3) there are no active groups. 722 * In particular, the last condition is always true if hierarchical 723 * support or the cgroups interface are not enabled, thus no state 724 * needs to be maintained in this case. 725 */ 726static bool bfq_asymmetric_scenario(struct bfq_data *bfqd, 727 struct bfq_queue *bfqq) 728{ 729 bool smallest_weight = bfqq && 730 bfqq->weight_counter && 731 bfqq->weight_counter == 732 container_of( 733 rb_first_cached(&bfqd->queue_weights_tree), 734 struct bfq_weight_counter, 735 weights_node); 736 737 /* 738 * For queue weights to differ, queue_weights_tree must contain 739 * at least two nodes. 740 */ 741 bool varied_queue_weights = !smallest_weight && 742 !RB_EMPTY_ROOT(&bfqd->queue_weights_tree.rb_root) && 743 (bfqd->queue_weights_tree.rb_root.rb_node->rb_left || 744 bfqd->queue_weights_tree.rb_root.rb_node->rb_right); 745 746 bool multiple_classes_busy = 747 (bfqd->busy_queues[0] && bfqd->busy_queues[1]) || 748 (bfqd->busy_queues[0] && bfqd->busy_queues[2]) || 749 (bfqd->busy_queues[1] && bfqd->busy_queues[2]); 750 751 return varied_queue_weights || multiple_classes_busy 752#ifdef CONFIG_BFQ_GROUP_IOSCHED 753 || bfqd->num_groups_with_pending_reqs > 0 754#endif 755 ; 756} 757 758/* 759 * If the weight-counter tree passed as input contains no counter for 760 * the weight of the input queue, then add that counter; otherwise just 761 * increment the existing counter. 762 * 763 * Note that weight-counter trees contain few nodes in mostly symmetric 764 * scenarios. For example, if all queues have the same weight, then the 765 * weight-counter tree for the queues may contain at most one node. 766 * This holds even if low_latency is on, because weight-raised queues 767 * are not inserted in the tree. 768 * In most scenarios, the rate at which nodes are created/destroyed 769 * should be low too. 770 */ 771void bfq_weights_tree_add(struct bfq_data *bfqd, struct bfq_queue *bfqq, 772 struct rb_root_cached *root) 773{ 774 struct bfq_entity *entity = &bfqq->entity; 775 struct rb_node **new = &(root->rb_root.rb_node), *parent = NULL; 776 bool leftmost = true; 777 778 /* 779 * Do not insert if the queue is already associated with a 780 * counter, which happens if: 781 * 1) a request arrival has caused the queue to become both 782 * non-weight-raised, and hence change its weight, and 783 * backlogged; in this respect, each of the two events 784 * causes an invocation of this function, 785 * 2) this is the invocation of this function caused by the 786 * second event. This second invocation is actually useless, 787 * and we handle this fact by exiting immediately. More 788 * efficient or clearer solutions might possibly be adopted. 789 */ 790 if (bfqq->weight_counter) 791 return; 792 793 while (*new) { 794 struct bfq_weight_counter *__counter = container_of(*new, 795 struct bfq_weight_counter, 796 weights_node); 797 parent = *new; 798 799 if (entity->weight == __counter->weight) { 800 bfqq->weight_counter = __counter; 801 goto inc_counter; 802 } 803 if (entity->weight < __counter->weight) 804 new = &((*new)->rb_left); 805 else { 806 new = &((*new)->rb_right); 807 leftmost = false; 808 } 809 } 810 811 bfqq->weight_counter = kzalloc(sizeof(struct bfq_weight_counter), 812 GFP_ATOMIC); 813 814 /* 815 * In the unlucky event of an allocation failure, we just 816 * exit. This will cause the weight of queue to not be 817 * considered in bfq_asymmetric_scenario, which, in its turn, 818 * causes the scenario to be deemed wrongly symmetric in case 819 * bfqq's weight would have been the only weight making the 820 * scenario asymmetric. On the bright side, no unbalance will 821 * however occur when bfqq becomes inactive again (the 822 * invocation of this function is triggered by an activation 823 * of queue). In fact, bfq_weights_tree_remove does nothing 824 * if !bfqq->weight_counter. 825 */ 826 if (unlikely(!bfqq->weight_counter)) 827 return; 828 829 bfqq->weight_counter->weight = entity->weight; 830 rb_link_node(&bfqq->weight_counter->weights_node, parent, new); 831 rb_insert_color_cached(&bfqq->weight_counter->weights_node, root, 832 leftmost); 833 834inc_counter: 835 bfqq->weight_counter->num_active++; 836 bfqq->ref++; 837} 838 839/* 840 * Decrement the weight counter associated with the queue, and, if the 841 * counter reaches 0, remove the counter from the tree. 842 * See the comments to the function bfq_weights_tree_add() for considerations 843 * about overhead. 844 */ 845void __bfq_weights_tree_remove(struct bfq_data *bfqd, 846 struct bfq_queue *bfqq, 847 struct rb_root_cached *root) 848{ 849 if (!bfqq->weight_counter) 850 return; 851 852 bfqq->weight_counter->num_active--; 853 if (bfqq->weight_counter->num_active > 0) 854 goto reset_entity_pointer; 855 856 rb_erase_cached(&bfqq->weight_counter->weights_node, root); 857 kfree(bfqq->weight_counter); 858 859reset_entity_pointer: 860 bfqq->weight_counter = NULL; 861 bfq_put_queue(bfqq); 862} 863 864/* 865 * Invoke __bfq_weights_tree_remove on bfqq and decrement the number 866 * of active groups for each queue's inactive parent entity. 867 */ 868void bfq_weights_tree_remove(struct bfq_data *bfqd, 869 struct bfq_queue *bfqq) 870{ 871 struct bfq_entity *entity = bfqq->entity.parent; 872 873 for_each_entity(entity) { 874 struct bfq_sched_data *sd = entity->my_sched_data; 875 876 if (sd->next_in_service || sd->in_service_entity) { 877 /* 878 * entity is still active, because either 879 * next_in_service or in_service_entity is not 880 * NULL (see the comments on the definition of 881 * next_in_service for details on why 882 * in_service_entity must be checked too). 883 * 884 * As a consequence, its parent entities are 885 * active as well, and thus this loop must 886 * stop here. 887 */ 888 break; 889 } 890 891 /* 892 * The decrement of num_groups_with_pending_reqs is 893 * not performed immediately upon the deactivation of 894 * entity, but it is delayed to when it also happens 895 * that the first leaf descendant bfqq of entity gets 896 * all its pending requests completed. The following 897 * instructions perform this delayed decrement, if 898 * needed. See the comments on 899 * num_groups_with_pending_reqs for details. 900 */ 901 if (entity->in_groups_with_pending_reqs) { 902 entity->in_groups_with_pending_reqs = false; 903 bfqd->num_groups_with_pending_reqs--; 904 } 905 } 906 907 /* 908 * Next function is invoked last, because it causes bfqq to be 909 * freed if the following holds: bfqq is not in service and 910 * has no dispatched request. DO NOT use bfqq after the next 911 * function invocation. 912 */ 913 __bfq_weights_tree_remove(bfqd, bfqq, 914 &bfqd->queue_weights_tree); 915} 916 917/* 918 * Return expired entry, or NULL to just start from scratch in rbtree. 919 */ 920static struct request *bfq_check_fifo(struct bfq_queue *bfqq, 921 struct request *last) 922{ 923 struct request *rq; 924 925 if (bfq_bfqq_fifo_expire(bfqq)) 926 return NULL; 927 928 bfq_mark_bfqq_fifo_expire(bfqq); 929 930 rq = rq_entry_fifo(bfqq->fifo.next); 931 932 if (rq == last || ktime_get_ns() < rq->fifo_time) 933 return NULL; 934 935 bfq_log_bfqq(bfqq->bfqd, bfqq, "check_fifo: returned %p", rq); 936 return rq; 937} 938 939static struct request *bfq_find_next_rq(struct bfq_data *bfqd, 940 struct bfq_queue *bfqq, 941 struct request *last) 942{ 943 struct rb_node *rbnext = rb_next(&last->rb_node); 944 struct rb_node *rbprev = rb_prev(&last->rb_node); 945 struct request *next, *prev = NULL; 946 947 /* Follow expired path, else get first next available. */ 948 next = bfq_check_fifo(bfqq, last); 949 if (next) 950 return next; 951 952 if (rbprev) 953 prev = rb_entry_rq(rbprev); 954 955 if (rbnext) 956 next = rb_entry_rq(rbnext); 957 else { 958 rbnext = rb_first(&bfqq->sort_list); 959 if (rbnext && rbnext != &last->rb_node) 960 next = rb_entry_rq(rbnext); 961 } 962 963 return bfq_choose_req(bfqd, next, prev, blk_rq_pos(last)); 964} 965 966/* see the definition of bfq_async_charge_factor for details */ 967static unsigned long bfq_serv_to_charge(struct request *rq, 968 struct bfq_queue *bfqq) 969{ 970 if (bfq_bfqq_sync(bfqq) || bfqq->wr_coeff > 1 || 971 bfq_asymmetric_scenario(bfqq->bfqd, bfqq)) 972 return blk_rq_sectors(rq); 973 974 return blk_rq_sectors(rq) * bfq_async_charge_factor; 975} 976 977/** 978 * bfq_updated_next_req - update the queue after a new next_rq selection. 979 * @bfqd: the device data the queue belongs to. 980 * @bfqq: the queue to update. 981 * 982 * If the first request of a queue changes we make sure that the queue 983 * has enough budget to serve at least its first request (if the 984 * request has grown). We do this because if the queue has not enough 985 * budget for its first request, it has to go through two dispatch 986 * rounds to actually get it dispatched. 987 */ 988static void bfq_updated_next_req(struct bfq_data *bfqd, 989 struct bfq_queue *bfqq) 990{ 991 struct bfq_entity *entity = &bfqq->entity; 992 struct request *next_rq = bfqq->next_rq; 993 unsigned long new_budget; 994 995 if (!next_rq) 996 return; 997 998 if (bfqq == bfqd->in_service_queue) 999 /* 1000 * In order not to break guarantees, budgets cannot be
1001 * changed after an entity has been selected. 1002 */ 1003 return; 1004 1005 new_budget = max_t(unsigned long, 1006 max_t(unsigned long, bfqq->max_budget, 1007 bfq_serv_to_charge(next_rq, bfqq)), 1008 entity->service); 1009 if (entity->budget != new_budget) { 1010 entity->budget = new_budget; 1011 bfq_log_bfqq(bfqd, bfqq, "updated next rq: new budget %lu", 1012 new_budget); 1013 bfq_requeue_bfqq(bfqd, bfqq, false); 1014 } 1015} 1016 1017static unsigned int bfq_wr_duration(struct bfq_data *bfqd) 1018{ 1019 u64 dur; 1020 1021 if (bfqd->bfq_wr_max_time > 0) 1022 return bfqd->bfq_wr_max_time; 1023 1024 dur = bfqd->rate_dur_prod; 1025 do_div(dur, bfqd->peak_rate); 1026 1027 /* 1028 * Limit duration between 3 and 25 seconds. The upper limit 1029 * has been conservatively set after the following worst case: 1030 * on a QEMU/KVM virtual machine 1031 * - running in a slow PC 1032 * - with a virtual disk stacked on a slow low-end 5400rpm HDD 1033 * - serving a heavy I/O workload, such as the sequential reading 1034 * of several files 1035 * mplayer took 23 seconds to start, if constantly weight-raised. 1036 * 1037 * As for higher values than that accomodating the above bad 1038 * scenario, tests show that higher values would often yield 1039 * the opposite of the desired result, i.e., would worsen 1040 * responsiveness by allowing non-interactive applications to 1041 * preserve weight raising for too long. 1042 * 1043 * On the other end, lower values than 3 seconds make it 1044 * difficult for most interactive tasks to complete their jobs 1045 * before weight-raising finishes. 1046 */ 1047 return clamp_val(dur, msecs_to_jiffies(3000), msecs_to_jiffies(25000)); 1048} 1049 1050/* switch back from soft real-time to interactive weight raising */ 1051static void switch_back_to_interactive_wr(struct bfq_queue *bfqq, 1052 struct bfq_data *bfqd) 1053{ 1054 bfqq->wr_coeff = bfqd->bfq_wr_coeff; 1055 bfqq->wr_cur_max_time = bfq_wr_duration(bfqd); 1056 bfqq->last_wr_start_finish = bfqq->wr_start_at_switch_to_srt; 1057} 1058 1059static void 1060bfq_bfqq_resume_state(struct bfq_queue *bfqq, struct bfq_data *bfqd, 1061 struct bfq_io_cq *bic, bool bfq_already_existing) 1062{ 1063 unsigned int old_wr_coeff = 1; 1064 bool busy = bfq_already_existing && bfq_bfqq_busy(bfqq); 1065 1066 if (bic->saved_has_short_ttime) 1067 bfq_mark_bfqq_has_short_ttime(bfqq); 1068 else 1069 bfq_clear_bfqq_has_short_ttime(bfqq); 1070 1071 if (bic->saved_IO_bound) 1072 bfq_mark_bfqq_IO_bound(bfqq); 1073 else 1074 bfq_clear_bfqq_IO_bound(bfqq); 1075 1076 bfqq->last_serv_time_ns = bic->saved_last_serv_time_ns; 1077 bfqq->inject_limit = bic->saved_inject_limit; 1078 bfqq->decrease_time_jif = bic->saved_decrease_time_jif; 1079 1080 bfqq->entity.new_weight = bic->saved_weight; 1081 bfqq->ttime = bic->saved_ttime; 1082 bfqq->io_start_time = bic->saved_io_start_time; 1083 bfqq->tot_idle_time = bic->saved_tot_idle_time; 1084 /* 1085 * Restore weight coefficient only if low_latency is on 1086 */ 1087 if (bfqd->low_latency) { 1088 old_wr_coeff = bfqq->wr_coeff; 1089 bfqq->wr_coeff = bic->saved_wr_coeff; 1090 } 1091 bfqq->service_from_wr = bic->saved_service_from_wr; 1092 bfqq->wr_start_at_switch_to_srt = bic->saved_wr_start_at_switch_to_srt; 1093 bfqq->last_wr_start_finish = bic->saved_last_wr_start_finish; 1094 bfqq->wr_cur_max_time = bic->saved_wr_cur_max_time; 1095 1096 if (bfqq->wr_coeff > 1 && (bfq_bfqq_in_large_burst(bfqq) || 1097 time_is_before_jiffies(bfqq->last_wr_start_finish + 1098 bfqq->wr_cur_max_time))) { 1099 if (bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time && 1100 !bfq_bfqq_in_large_burst(bfqq) && 1101 time_is_after_eq_jiffies(bfqq->wr_start_at_switch_to_srt + 1102 bfq_wr_duration(bfqd))) { 1103 switch_back_to_interactive_wr(bfqq, bfqd); 1104 } else { 1105 bfqq->wr_coeff = 1; 1106 bfq_log_bfqq(bfqq->bfqd, bfqq, 1107 "resume state: switching off wr"); 1108 } 1109 } 1110 1111 /* make sure weight will be updated, however we got here */ 1112 bfqq->entity.prio_changed = 1; 1113 1114 if (likely(!busy)) 1115 return; 1116 1117 if (old_wr_coeff == 1 && bfqq->wr_coeff > 1) 1118 bfqd->wr_busy_queues++; 1119 else if (old_wr_coeff > 1 && bfqq->wr_coeff == 1) 1120 bfqd->wr_busy_queues--; 1121} 1122 1123static int bfqq_process_refs(struct bfq_queue *bfqq) 1124{ 1125 return bfqq->ref - bfqq->allocated - bfqq->entity.on_st_or_in_serv - 1126 (bfqq->weight_counter != NULL) - bfqq->stable_ref; 1127} 1128 1129/* Empty burst list and add just bfqq (see comments on bfq_handle_burst) */ 1130static void bfq_reset_burst_list(struct bfq_data *bfqd, struct bfq_queue *bfqq) 1131{ 1132 struct bfq_queue *item; 1133 struct hlist_node *n; 1134 1135 hlist_for_each_entry_safe(item, n, &bfqd->burst_list, burst_list_node) 1136 hlist_del_init(&item->burst_list_node); 1137 1138 /* 1139 * Start the creation of a new burst list only if there is no 1140 * active queue. See comments on the conditional invocation of 1141 * bfq_handle_burst(). 1142 */ 1143 if (bfq_tot_busy_queues(bfqd) == 0) { 1144 hlist_add_head(&bfqq->burst_list_node, &bfqd->burst_list); 1145 bfqd->burst_size = 1; 1146 } else 1147 bfqd->burst_size = 0; 1148 1149 bfqd->burst_parent_entity = bfqq->entity.parent; 1150} 1151 1152/* Add bfqq to the list of queues in current burst (see bfq_handle_burst) */ 1153static void bfq_add_to_burst(struct bfq_data *bfqd, struct bfq_queue *bfqq) 1154{ 1155 /* Increment burst size to take into account also bfqq */ 1156 bfqd->burst_size++; 1157 1158 if (bfqd->burst_size == bfqd->bfq_large_burst_thresh) { 1159 struct bfq_queue *pos, *bfqq_item; 1160 struct hlist_node *n; 1161 1162 /* 1163 * Enough queues have been activated shortly after each 1164 * other to consider this burst as large. 1165 */ 1166 bfqd->large_burst = true; 1167 1168 /* 1169 * We can now mark all queues in the burst list as 1170 * belonging to a large burst. 1171 */ 1172 hlist_for_each_entry(bfqq_item, &bfqd->burst_list, 1173 burst_list_node) 1174 bfq_mark_bfqq_in_large_burst(bfqq_item); 1175 bfq_mark_bfqq_in_large_burst(bfqq); 1176 1177 /* 1178 * From now on, and until the current burst finishes, any 1179 * new queue being activated shortly after the last queue 1180 * was inserted in the burst can be immediately marked as 1181 * belonging to a large burst. So the burst list is not 1182 * needed any more. Remove it. 1183 */ 1184 hlist_for_each_entry_safe(pos, n, &bfqd->burst_list, 1185 burst_list_node) 1186 hlist_del_init(&pos->burst_list_node); 1187 } else /* 1188 * Burst not yet large: add bfqq to the burst list. Do 1189 * not increment the ref counter for bfqq, because bfqq 1190 * is removed from the burst list before freeing bfqq 1191 * in put_queue. 1192 */ 1193 hlist_add_head(&bfqq->burst_list_node, &bfqd->burst_list); 1194} 1195 1196/* 1197 * If many queues belonging to the same group happen to be created 1198 * shortly after each other, then the processes associated with these 1199 * queues have typically a common goal. In particular, bursts of queue 1200 * creations are usually caused by services or applications that spawn 1201 * many parallel threads/processes. Examples are systemd during boot, 1202 * or git grep. To help these processes get their job done as soon as 1203 * possible, it is usually better to not grant either weight-raising 1204 * or device idling to their queues, unless these queues must be 1205 * protected from the I/O flowing through other active queues. 1206 * 1207 * In this comment we describe, firstly, the reasons why this fact 1208 * holds, and, secondly, the next function, which implements the main 1209 * steps needed to properly mark these queues so that they can then be 1210 * treated in a different way. 1211 * 1212 * The above services or applications benefit mostly from a high 1213 * throughput: the quicker the requests of the activated queues are 1214 * cumulatively served, the sooner the target job of these queues gets 1215 * completed. As a consequence, weight-raising any of these queues, 1216 * which also implies idling the device for it, is almost always 1217 * counterproductive, unless there are other active queues to isolate 1218 * these new queues from. If there no other active queues, then 1219 * weight-raising these new queues just lowers throughput in most 1220 * cases. 1221 * 1222 * On the other hand, a burst of queue creations may be caused also by 1223 * the start of an application that does not consist of a lot of 1224 * parallel I/O-bound threads. In fact, with a complex application, 1225 * several short processes may need to be executed to start-up the 1226 * application. In this respect, to start an application as quickly as 1227 * possible, the best thing to do is in any case to privilege the I/O 1228 * related to the application with respect to all other 1229 * I/O. Therefore, the best strategy to start as quickly as possible 1230 * an application that causes a burst of queue creations is to 1231 * weight-raise all the queues created during the burst. This is the 1232 * exact opposite of the best strategy for the other type of bursts. 1233 * 1234 * In the end, to take the best action for each of the two cases, the 1235 * two types of bursts need to be distinguished. Fortunately, this 1236 * seems relatively easy, by looking at the sizes of the bursts. In 1237 * particular, we found a threshold such that only bursts with a 1238 * larger size than that threshold are apparently caused by 1239 * services or commands such as systemd or git grep. For brevity, 1240 * hereafter we call just 'large' these bursts. BFQ *does not* 1241 * weight-raise queues whose creation occurs in a large burst. In 1242 * addition, for each of these queues BFQ performs or does not perform 1243 * idling depending on which choice boosts the throughput more. The 1244 * exact choice depends on the device and request pattern at 1245 * hand. 1246 * 1247 * Unfortunately, false positives may occur while an interactive task 1248 * is starting (e.g., an application is being started). The 1249 * consequence is that the queues associated with the task do not 1250 * enjoy weight raising as expected. Fortunately these false positives 1251 * are very rare. They typically occur if some service happens to 1252 * start doing I/O exactly when the interactive task starts. 1253 * 1254 * Turning back to the next function, it is invoked only if there are 1255 * no active queues (apart from active queues that would belong to the 1256 * same, possible burst bfqq would belong to), and it implements all 1257 * the steps needed to detect the occurrence of a large burst and to 1258 * properly mark all the queues belonging to it (so that they can then 1259 * be treated in a different way). This goal is achieved by 1260 * maintaining a "burst list" that holds, temporarily, the queues that 1261 * belong to the burst in progress. The list is then used to mark 1262 * these queues as belonging to a large burst if the burst does become 1263 * large. The main steps are the following. 1264 * 1265 * . when the very first queue is created, the queue is inserted into the 1266 * list (as it could be the first queue in a possible burst) 1267 * 1268 * . if the current burst has not yet become large, and a queue Q that does 1269 * not yet belong to the burst is activated shortly after the last time 1270 * at which a new queue entered the burst list, then the function appends 1271 * Q to the burst list 1272 * 1273 * . if, as a consequence of the previous step, the burst size reaches 1274 * the large-burst threshold, then 1275 * 1276 * . all the queues in the burst list are marked as belonging to a 1277 * large burst 1278 * 1279 * . the burst list is deleted; in fact, the burst list already served 1280 * its purpose (keeping temporarily track of the queues in a burst, 1281 * so as to be able to mark them as belonging to a large burst in the 1282 * previous sub-step), and now is not needed any more 1283 * 1284 * . the device enters a large-burst mode 1285 * 1286 * . if a queue Q that does not belong to the burst is created while 1287 * the device is in large-burst mode and shortly after the last time 1288 * at which a queue either entered the burst list or was marked as 1289 * belonging to the current large burst, then Q is immediately marked 1290 * as belonging to a large burst. 1291 * 1292 * . if a queue Q that does not belong to the burst is created a while 1293 * later, i.e., not shortly after, than the last time at which a queue 1294 * either entered the burst list or was marked as belonging to the 1295 * current large burst, then the current burst is deemed as finished and: 1296 * 1297 * . the large-burst mode is reset if set 1298 * 1299 * . the burst list is emptied 1300 * 1301 * . Q is inserted in the burst list, as Q may be the first queue 1302 * in a possible new burst (then the burst list contains just Q 1303 * after this step). 1304 */ 1305static void bfq_handle_burst(struct bfq_data *bfqd, struct bfq_queue *bfqq) 1306{ 1307 /* 1308 * If bfqq is already in the burst list or is part of a large 1309 * burst, or finally has just been split, then there is 1310 * nothing else to do. 1311 */ 1312 if (!hlist_unhashed(&bfqq->burst_list_node) || 1313 bfq_bfqq_in_large_burst(bfqq) || 1314 time_is_after_eq_jiffies(bfqq->split_time + 1315 msecs_to_jiffies(10))) 1316 return; 1317 1318 /* 1319 * If bfqq's creation happens late enough, or bfqq belongs to 1320 * a different group than the burst group, then the current 1321 * burst is finished, and related data structures must be 1322 * reset. 1323 * 1324 * In this respect, consider the special case where bfqq is 1325 * the very first queue created after BFQ is selected for this 1326 * device. In this case, last_ins_in_burst and 1327 * burst_parent_entity are not yet significant when we get 1328 * here. But it is easy to verify that, whether or not the 1329 * following condition is true, bfqq will end up being 1330 * inserted into the burst list. In particular the list will 1331 * happen to contain only bfqq. And this is exactly what has 1332 * to happen, as bfqq may be the first queue of the first 1333 * burst. 1334 */ 1335 if (time_is_before_jiffies(bfqd->last_ins_in_burst + 1336 bfqd->bfq_burst_interval) || 1337 bfqq->entity.parent != bfqd->burst_parent_entity) { 1338 bfqd->large_burst = false; 1339 bfq_reset_burst_list(bfqd, bfqq); 1340 goto end; 1341 } 1342 1343 /* 1344 * If we get here, then bfqq is being activated shortly after the 1345 * last queue. So, if the current burst is also large, we can mark 1346 * bfqq as belonging to this large burst immediately. 1347 */ 1348 if (bfqd->large_burst) { 1349 bfq_mark_bfqq_in_large_burst(bfqq); 1350 goto end; 1351 } 1352 1353 /* 1354 * If we get here, then a large-burst state has not yet been 1355 * reached, but bfqq is being activated shortly after the last 1356 * queue. Then we add bfqq to the burst. 1357 */ 1358 bfq_add_to_burst(bfqd, bfqq); 1359end: 1360 /* 1361 * At this point, bfqq either has been added to the current 1362 * burst or has caused the current burst to terminate and a 1363 * possible new burst to start. In particular, in the second 1364 * case, bfqq has become the first queue in the possible new 1365 * burst. In both cases last_ins_in_burst needs to be moved 1366 * forward. 1367 */ 1368 bfqd->last_ins_in_burst = jiffies; 1369} 1370 1371static int bfq_bfqq_budget_left(struct bfq_queue *bfqq) 1372{ 1373 struct bfq_entity *entity = &bfqq->entity; 1374 1375 return entity->budget - entity->service; 1376} 1377 1378/* 1379 * If enough samples have been computed, return the current max budget 1380 * stored in bfqd, which is dynamically updated according to the 1381 * estimated disk peak rate; otherwise return the default max budget 1382 */ 1383static int bfq_max_budget(struct bfq_data *bfqd) 1384{ 1385 if (bfqd->budgets_assigned < bfq_stats_min_budgets) 1386 return bfq_default_max_budget; 1387 else 1388 return bfqd->bfq_max_budget; 1389} 1390 1391/* 1392 * Return min budget, which is a fraction of the current or default 1393 * max budget (trying with 1/32) 1394 */ 1395static int bfq_min_budget(struct bfq_data *bfqd) 1396{ 1397 if (bfqd->budgets_assigned < bfq_stats_min_budgets) 1398 return bfq_default_max_budget / 32; 1399 else 1400 return bfqd->bfq_max_budget / 32; 1401} 1402 1403/* 1404 * The next function, invoked after the input queue bfqq switches from 1405 * idle to busy, updates the budget of bfqq. The function also tells 1406 * whether the in-service queue should be expired, by returning 1407 * true. The purpose of expiring the in-service queue is to give bfqq 1408 * the chance to possibly preempt the in-service queue, and the reason 1409 * for preempting the in-service queue is to achieve one of the two 1410 * goals below. 1411 * 1412 * 1. Guarantee to bfqq its reserved bandwidth even if bfqq has 1413 * expired because it has remained idle. In particular, bfqq may have 1414 * expired for one of the following two reasons: 1415 * 1416 * - BFQQE_NO_MORE_REQUESTS bfqq did not enjoy any device idling 1417 * and did not make it to issue a new request before its last 1418 * request was served; 1419 * 1420 * - BFQQE_TOO_IDLE bfqq did enjoy device idling, but did not issue 1421 * a new request before the expiration of the idling-time. 1422 * 1423 * Even if bfqq has expired for one of the above reasons, the process 1424 * associated with the queue may be however issuing requests greedily, 1425 * and thus be sensitive to the bandwidth it receives (bfqq may have 1426 * remained idle for other reasons: CPU high load, bfqq not enjoying 1427 * idling, I/O throttling somewhere in the path from the process to 1428 * the I/O scheduler, ...). But if, after every expiration for one of 1429 * the above two reasons, bfqq has to wait for the service of at least 1430 * one full budget of another queue before being served again, then 1431 * bfqq is likely to get a much lower bandwidth or resource time than 1432 * its reserved ones. To address this issue, two countermeasures need 1433 * to be taken. 1434 * 1435 * First, the budget and the timestamps of bfqq need to be updated in 1436 * a special way on bfqq reactivation: they need to be updated as if 1437 * bfqq did not remain idle and did not expire. In fact, if they are 1438 * computed as if bfqq expired and remained idle until reactivation, 1439 * then the process associated with bfqq is treated as if, instead of 1440 * being greedy, it stopped issuing requests when bfqq remained idle, 1441 * and restarts issuing requests only on this reactivation. In other 1442 * words, the scheduler does not help the process recover the "service 1443 * hole" between bfqq expiration and reactivation. As a consequence, 1444 * the process receives a lower bandwidth than its reserved one. In 1445 * contrast, to recover this hole, the budget must be updated as if 1446 * bfqq was not expired at all before this reactivation, i.e., it must 1447 * be set to the value of the remaining budget when bfqq was 1448 * expired. Along the same line, timestamps need to be assigned the 1449 * value they had the last time bfqq was selected for service, i.e., 1450 * before last expiration. Thus timestamps need to be back-shifted 1451 * with respect to their normal computation (see [1] for more details 1452 * on this tricky aspect). 1453 * 1454 * Secondly, to allow the process to recover the hole, the in-service 1455 * queue must be expired too, to give bfqq the chance to preempt it 1456 * immediately. In fact, if bfqq has to wait for a full budget of the 1457 * in-service queue to be completed, then it may become impossible to 1458 * let the process recover the hole, even if the back-shifted 1459 * timestamps of bfqq are lower than those of the in-service queue. If 1460 * this happens for most or all of the holes, then the process may not 1461 * receive its reserved bandwidth. In this respect, it is worth noting 1462 * that, being the service of outstanding requests unpreemptible, a 1463 * little fraction of the holes may however be unrecoverable, thereby 1464 * causing a little loss of bandwidth. 1465 * 1466 * The last important point is detecting whether bfqq does need this 1467 * bandwidth recovery. In this respect, the next function deems the 1468 * process associated with bfqq greedy, and thus allows it to recover 1469 * the hole, if: 1) the process is waiting for the arrival of a new 1470 * request (which implies that bfqq expired for one of the above two 1471 * reasons), and 2) such a request has arrived soon. The first 1472 * condition is controlled through the flag non_blocking_wait_rq, 1473 * while the second through the flag arrived_in_time. If both 1474 * conditions hold, then the function computes the budget in the 1475 * above-described special way, and signals that the in-service queue 1476 * should be expired. Timestamp back-shifting is done later in 1477 * __bfq_activate_entity. 1478 * 1479 * 2. Reduce latency. Even if timestamps are not backshifted to let 1480 * the process associated with bfqq recover a service hole, bfqq may 1481 * however happen to have, after being (re)activated, a lower finish 1482 * timestamp than the in-service queue. That is, the next budget of 1483 * bfqq may have to be completed before the one of the in-service 1484 * queue. If this is the case, then preempting the in-service queue 1485 * allows this goal to be achieved, apart from the unpreemptible, 1486 * outstanding requests mentioned above. 1487 * 1488 * Unfortunately, regardless of which of the above two goals one wants 1489 * to achieve, service trees need first to be updated to know whether 1490 * the in-service queue must be preempted. To have service trees 1491 * correctly updated, the in-service queue must be expired and 1492 * rescheduled, and bfqq must be scheduled too. This is one of the 1493 * most costly operations (in future versions, the scheduling 1494 * mechanism may be re-designed in such a way to make it possible to 1495 * know whether preemption is needed without needing to update service 1496 * trees). In addition, queue preemptions almost always cause random 1497 * I/O, which may in turn cause loss of throughput. Finally, there may 1498 * even be no in-service queue when the next function is invoked (so, 1499 * no queue to compare timestamps with). Because of these facts, the 1500 * next function adopts the following simple scheme to avoid costly 1501 * operations, too frequent preemptions and too many dependencies on 1502 * the state of the scheduler: it requests the expiration of the 1503 * in-service queue (unconditionally) only for queues that need to 1504 * recover a hole. Then it delegates to other parts of the code the 1505 * responsibility of handling the above case 2. 1506 */ 1507static bool bfq_bfqq_update_budg_for_activation(struct bfq_data *bfqd, 1508 struct bfq_queue *bfqq, 1509 bool arrived_in_time) 1510{ 1511 struct bfq_entity *entity = &bfqq->entity; 1512 1513 /* 1514 * In the next compound condition, we check also whether there 1515 * is some budget left, because otherwise there is no point in 1516 * trying to go on serving bfqq with this same budget: bfqq 1517 * would be expired immediately after being selected for 1518 * service. This would only cause useless overhead. 1519 */ 1520 if (bfq_bfqq_non_blocking_wait_rq(bfqq) && arrived_in_time && 1521 bfq_bfqq_budget_left(bfqq) > 0) { 1522 /* 1523 * We do not clear the flag non_blocking_wait_rq here, as 1524 * the latter is used in bfq_activate_bfqq to signal 1525 * that timestamps need to be back-shifted (and is 1526 * cleared right after). 1527 */ 1528 1529 /* 1530 * In next assignment we rely on that either 1531 * entity->service or entity->budget are not updated 1532 * on expiration if bfqq is empty (see 1533 * __bfq_bfqq_recalc_budget). Thus both quantities 1534 * remain unchanged after such an expiration, and the 1535 * following statement therefore assigns to 1536 * entity->budget the remaining budget on such an 1537 * expiration. 1538 */ 1539 entity->budget = min_t(unsigned long, 1540 bfq_bfqq_budget_left(bfqq), 1541 bfqq->max_budget); 1542 1543 /* 1544 * At this point, we have used entity->service to get 1545 * the budget left (needed for updating 1546 * entity->budget). Thus we finally can, and have to, 1547 * reset entity->service. The latter must be reset 1548 * because bfqq would otherwise be charged again for 1549 * the service it has received during its previous 1550 * service slot(s). 1551 */ 1552 entity->service = 0; 1553 1554 return true; 1555 } 1556 1557 /* 1558 * We can finally complete expiration, by setting service to 0. 1559 */ 1560 entity->service = 0; 1561 entity->budget = max_t(unsigned long, bfqq->max_budget, 1562 bfq_serv_to_charge(bfqq->next_rq, bfqq)); 1563 bfq_clear_bfqq_non_blocking_wait_rq(bfqq); 1564 return false; 1565} 1566 1567/* 1568 * Return the farthest past time instant according to jiffies 1569 * macros. 1570 */ 1571static unsigned long bfq_smallest_from_now(void) 1572{ 1573 return jiffies - MAX_JIFFY_OFFSET; 1574} 1575 1576static void bfq_update_bfqq_wr_on_rq_arrival(struct bfq_data *bfqd, 1577 struct bfq_queue *bfqq, 1578 unsigned int old_wr_coeff, 1579 bool wr_or_deserves_wr, 1580 bool interactive, 1581 bool in_burst, 1582 bool soft_rt) 1583{ 1584 if (old_wr_coeff == 1 && wr_or_deserves_wr) { 1585 /* start a weight-raising period */ 1586 if (interactive) { 1587 bfqq->service_from_wr = 0; 1588 bfqq->wr_coeff = bfqd->bfq_wr_coeff; 1589 bfqq->wr_cur_max_time = bfq_wr_duration(bfqd); 1590 } else { 1591 /* 1592 * No interactive weight raising in progress 1593 * here: assign minus infinity to 1594 * wr_start_at_switch_to_srt, to make sure 1595 * that, at the end of the soft-real-time 1596 * weight raising periods that is starting 1597 * now, no interactive weight-raising period 1598 * may be wrongly considered as still in 1599 * progress (and thus actually started by 1600 * mistake). 1601 */ 1602 bfqq->wr_start_at_switch_to_srt = 1603 bfq_smallest_from_now(); 1604 bfqq->wr_coeff = bfqd->bfq_wr_coeff * 1605 BFQ_SOFTRT_WEIGHT_FACTOR; 1606 bfqq->wr_cur_max_time = 1607 bfqd->bfq_wr_rt_max_time; 1608 } 1609 1610 /* 1611 * If needed, further reduce budget to make sure it is 1612 * close to bfqq's backlog, so as to reduce the 1613 * scheduling-error component due to a too large 1614 * budget. Do not care about throughput consequences, 1615 * but only about latency. Finally, do not assign a 1616 * too small budget either, to avoid increasing 1617 * latency by causing too frequent expirations. 1618 */ 1619 bfqq->entity.budget = min_t(unsigned long, 1620 bfqq->entity.budget, 1621 2 * bfq_min_budget(bfqd)); 1622 } else if (old_wr_coeff > 1) { 1623 if (interactive) { /* update wr coeff and duration */ 1624 bfqq->wr_coeff = bfqd->bfq_wr_coeff; 1625 bfqq->wr_cur_max_time = bfq_wr_duration(bfqd); 1626 } else if (in_burst) 1627 bfqq->wr_coeff = 1; 1628 else if (soft_rt) { 1629 /* 1630 * The application is now or still meeting the 1631 * requirements for being deemed soft rt. We 1632 * can then correctly and safely (re)charge 1633 * the weight-raising duration for the 1634 * application with the weight-raising 1635 * duration for soft rt applications. 1636 * 1637 * In particular, doing this recharge now, i.e., 1638 * before the weight-raising period for the 1639 * application finishes, reduces the probability 1640 * of the following negative scenario: 1641 * 1) the weight of a soft rt application is 1642 * raised at startup (as for any newly 1643 * created application), 1644 * 2) since the application is not interactive, 1645 * at a certain time weight-raising is 1646 * stopped for the application, 1647 * 3) at that time the application happens to 1648 * still have pending requests, and hence 1649 * is destined to not have a chance to be 1650 * deemed soft rt before these requests are 1651 * completed (see the comments to the 1652 * function bfq_bfqq_softrt_next_start() 1653 * for details on soft rt detection), 1654 * 4) these pending requests experience a high 1655 * latency because the application is not 1656 * weight-raised while they are pending. 1657 */ 1658 if (bfqq->wr_cur_max_time != 1659 bfqd->bfq_wr_rt_max_time) { 1660 bfqq->wr_start_at_switch_to_srt = 1661 bfqq->last_wr_start_finish; 1662 1663 bfqq->wr_cur_max_time = 1664 bfqd->bfq_wr_rt_max_time; 1665 bfqq->wr_coeff = bfqd->bfq_wr_coeff * 1666 BFQ_SOFTRT_WEIGHT_FACTOR; 1667 } 1668 bfqq->last_wr_start_finish = jiffies; 1669 } 1670 } 1671} 1672 1673static bool bfq_bfqq_idle_for_long_time(struct bfq_data *bfqd, 1674 struct bfq_queue *bfqq) 1675{ 1676 return bfqq->dispatched == 0 && 1677 time_is_before_jiffies( 1678 bfqq->budget_timeout + 1679 bfqd->bfq_wr_min_idle_time); 1680} 1681 1682 1683/* 1684 * Return true if bfqq is in a higher priority class, or has a higher 1685 * weight than the in-service queue. 1686 */ 1687static bool bfq_bfqq_higher_class_or_weight(struct bfq_queue *bfqq, 1688 struct bfq_queue *in_serv_bfqq) 1689{ 1690 int bfqq_weight, in_serv_weight; 1691 1692 if (bfqq->ioprio_class < in_serv_bfqq->ioprio_class) 1693 return true; 1694 1695 if (in_serv_bfqq->entity.parent == bfqq->entity.parent) { 1696 bfqq_weight = bfqq->entity.weight; 1697 in_serv_weight = in_serv_bfqq->entity.weight; 1698 } else { 1699 if (bfqq->entity.parent) 1700 bfqq_weight = bfqq->entity.parent->weight; 1701 else 1702 bfqq_weight = bfqq->entity.weight; 1703 if (in_serv_bfqq->entity.parent) 1704 in_serv_weight = in_serv_bfqq->entity.parent->weight; 1705 else 1706 in_serv_weight = in_serv_bfqq->entity.weight; 1707 } 1708 1709 return bfqq_weight > in_serv_weight; 1710} 1711 1712static bool bfq_better_to_idle(struct bfq_queue *bfqq); 1713 1714static void bfq_bfqq_handle_idle_busy_switch(struct bfq_data *bfqd, 1715 struct bfq_queue *bfqq, 1716 int old_wr_coeff, 1717 struct request *rq, 1718 bool *interactive) 1719{ 1720 bool soft_rt, in_burst, wr_or_deserves_wr, 1721 bfqq_wants_to_preempt, 1722 idle_for_long_time = bfq_bfqq_idle_for_long_time(bfqd, bfqq), 1723 /* 1724 * See the comments on 1725 * bfq_bfqq_update_budg_for_activation for 1726 * details on the usage of the next variable. 1727 */ 1728 arrived_in_time = ktime_get_ns() <= 1729 bfqq->ttime.last_end_request + 1730 bfqd->bfq_slice_idle * 3; 1731 1732 1733 /* 1734 * bfqq deserves to be weight-raised if: 1735 * - it is sync, 1736 * - it does not belong to a large burst, 1737 * - it has been idle for enough time or is soft real-time, 1738 * - is linked to a bfq_io_cq (it is not shared in any sense), 1739 * - has a default weight (otherwise we assume the user wanted 1740 * to control its weight explicitly) 1741 */ 1742 in_burst = bfq_bfqq_in_large_burst(bfqq); 1743 soft_rt = bfqd->bfq_wr_max_softrt_rate > 0 && 1744 !BFQQ_TOTALLY_SEEKY(bfqq) && 1745 !in_burst && 1746 time_is_before_jiffies(bfqq->soft_rt_next_start) && 1747 bfqq->dispatched == 0 && 1748 bfqq->entity.new_weight == 40; 1749 *interactive = !in_burst && idle_for_long_time && 1750 bfqq->entity.new_weight == 40; 1751 /* 1752 * Merged bfq_queues are kept out of weight-raising 1753 * (low-latency) mechanisms. The reason is that these queues 1754 * are usually created for non-interactive and 1755 * non-soft-real-time tasks. Yet this is not the case for 1756 * stably-merged queues. These queues are merged just because 1757 * they are created shortly after each other. So they may 1758 * easily serve the I/O of an interactive or soft-real time 1759 * application, if the application happens to spawn multiple 1760 * processes. So let also stably-merged queued enjoy weight 1761 * raising. 1762 */ 1763 wr_or_deserves_wr = bfqd->low_latency && 1764 (bfqq->wr_coeff > 1 || 1765 (bfq_bfqq_sync(bfqq) && 1766 (bfqq->bic || RQ_BIC(rq)->stably_merged) && 1767 (*interactive || soft_rt))); 1768 1769 /* 1770 * Using the last flag, update budget and check whether bfqq 1771 * may want to preempt the in-service queue. 1772 */ 1773 bfqq_wants_to_preempt = 1774 bfq_bfqq_update_budg_for_activation(bfqd, bfqq, 1775 arrived_in_time); 1776 1777 /* 1778 * If bfqq happened to be activated in a burst, but has been 1779 * idle for much more than an interactive queue, then we 1780 * assume that, in the overall I/O initiated in the burst, the 1781 * I/O associated with bfqq is finished. So bfqq does not need 1782 * to be treated as a queue belonging to a burst 1783 * anymore. Accordingly, we reset bfqq's in_large_burst flag 1784 * if set, and remove bfqq from the burst list if it's 1785 * there. We do not decrement burst_size, because the fact 1786 * that bfqq does not need to belong to the burst list any 1787 * more does not invalidate the fact that bfqq was created in 1788 * a burst. 1789 */ 1790 if (likely(!bfq_bfqq_just_created(bfqq)) && 1791 idle_for_long_time && 1792 time_is_before_jiffies( 1793 bfqq->budget_timeout + 1794 msecs_to_jiffies(10000))) { 1795 hlist_del_init(&bfqq->burst_list_node); 1796 bfq_clear_bfqq_in_large_burst(bfqq); 1797 } 1798 1799 bfq_clear_bfqq_just_created(bfqq); 1800 1801 if (bfqd->low_latency) { 1802 if (unlikely(time_is_after_jiffies(bfqq->split_time))) 1803 /* wraparound */ 1804 bfqq->split_time = 1805 jiffies - bfqd->bfq_wr_min_idle_time - 1; 1806 1807 if (time_is_before_jiffies(bfqq->split_time + 1808 bfqd->bfq_wr_min_idle_time)) { 1809 bfq_update_bfqq_wr_on_rq_arrival(bfqd, bfqq, 1810 old_wr_coeff, 1811 wr_or_deserves_wr, 1812 *interactive, 1813 in_burst, 1814 soft_rt); 1815 1816 if (old_wr_coeff != bfqq->wr_coeff) 1817 bfqq->entity.prio_changed = 1; 1818 } 1819 } 1820 1821 bfqq->last_idle_bklogged = jiffies; 1822 bfqq->service_from_backlogged = 0; 1823 bfq_clear_bfqq_softrt_update(bfqq); 1824 1825 bfq_add_bfqq_busy(bfqd, bfqq); 1826 1827 /* 1828 * Expire in-service queue if preemption may be needed for 1829 * guarantees or throughput. As for guarantees, we care 1830 * explicitly about two cases. The first is that bfqq has to 1831 * recover a service hole, as explained in the comments on 1832 * bfq_bfqq_update_budg_for_activation(), i.e., that 1833 * bfqq_wants_to_preempt is true. However, if bfqq does not 1834 * carry time-critical I/O, then bfqq's bandwidth is less 1835 * important than that of queues that carry time-critical I/O. 1836 * So, as a further constraint, we consider this case only if 1837 * bfqq is at least as weight-raised, i.e., at least as time 1838 * critical, as the in-service queue. 1839 * 1840 * The second case is that bfqq is in a higher priority class, 1841 * or has a higher weight than the in-service queue. If this 1842 * condition does not hold, we don't care because, even if 1843 * bfqq does not start to be served immediately, the resulting 1844 * delay for bfqq's I/O is however lower or much lower than 1845 * the ideal completion time to be guaranteed to bfqq's I/O. 1846 * 1847 * In both cases, preemption is needed only if, according to 1848 * the timestamps of both bfqq and of the in-service queue, 1849 * bfqq actually is the next queue to serve. So, to reduce 1850 * useless preemptions, the return value of 1851 * next_queue_may_preempt() is considered in the next compound 1852 * condition too. Yet next_queue_may_preempt() just checks a 1853 * simple, necessary condition for bfqq to be the next queue 1854 * to serve. In fact, to evaluate a sufficient condition, the 1855 * timestamps of the in-service queue would need to be 1856 * updated, and this operation is quite costly (see the 1857 * comments on bfq_bfqq_update_budg_for_activation()). 1858 * 1859 * As for throughput, we ask bfq_better_to_idle() whether we 1860 * still need to plug I/O dispatching. If bfq_better_to_idle() 1861 * says no, then plugging is not needed any longer, either to 1862 * boost throughput or to perserve service guarantees. Then 1863 * the best option is to stop plugging I/O, as not doing so 1864 * would certainly lower throughput. We may end up in this 1865 * case if: (1) upon a dispatch attempt, we detected that it 1866 * was better to plug I/O dispatch, and to wait for a new 1867 * request to arrive for the currently in-service queue, but 1868 * (2) this switch of bfqq to busy changes the scenario. 1869 */ 1870 if (bfqd->in_service_queue && 1871 ((bfqq_wants_to_preempt && 1872 bfqq->wr_coeff >= bfqd->in_service_queue->wr_coeff) || 1873 bfq_bfqq_higher_class_or_weight(bfqq, bfqd->in_service_queue) || 1874 !bfq_better_to_idle(bfqd->in_service_queue)) && 1875 next_queue_may_preempt(bfqd)) 1876 bfq_bfqq_expire(bfqd, bfqd->in_service_queue, 1877 false, BFQQE_PREEMPTED); 1878} 1879 1880static void bfq_reset_inject_limit(struct bfq_data *bfqd, 1881 struct bfq_queue *bfqq) 1882{ 1883 /* invalidate baseline total service time */ 1884 bfqq->last_serv_time_ns = 0; 1885 1886 /* 1887 * Reset pointer in case we are waiting for 1888 * some request completion. 1889 */ 1890 bfqd->waited_rq = NULL; 1891 1892 /* 1893 * If bfqq has a short think time, then start by setting the 1894 * inject limit to 0 prudentially, because the service time of 1895 * an injected I/O request may be higher than the think time 1896 * of bfqq, and therefore, if one request was injected when 1897 * bfqq remains empty, this injected request might delay the 1898 * service of the next I/O request for bfqq significantly. In 1899 * case bfqq can actually tolerate some injection, then the 1900 * adaptive update will however raise the limit soon. This 1901 * lucky circumstance holds exactly because bfqq has a short 1902 * think time, and thus, after remaining empty, is likely to 1903 * get new I/O enqueued---and then completed---before being 1904 * expired. This is the very pattern that gives the 1905 * limit-update algorithm the chance to measure the effect of 1906 * injection on request service times, and then to update the 1907 * limit accordingly. 1908 * 1909 * However, in the following special case, the inject limit is 1910 * left to 1 even if the think time is short: bfqq's I/O is 1911 * synchronized with that of some other queue, i.e., bfqq may 1912 * receive new I/O only after the I/O of the other queue is 1913 * completed. Keeping the inject limit to 1 allows the 1914 * blocking I/O to be served while bfqq is in service. And 1915 * this is very convenient both for bfqq and for overall 1916 * throughput, as explained in detail in the comments in 1917 * bfq_update_has_short_ttime(). 1918 * 1919 * On the opposite end, if bfqq has a long think time, then 1920 * start directly by 1, because: 1921 * a) on the bright side, keeping at most one request in 1922 * service in the drive is unlikely to cause any harm to the 1923 * latency of bfqq's requests, as the service time of a single 1924 * request is likely to be lower than the think time of bfqq; 1925 * b) on the downside, after becoming empty, bfqq is likely to 1926 * expire before getting its next request. With this request 1927 * arrival pattern, it is very hard to sample total service 1928 * times and update the inject limit accordingly (see comments 1929 * on bfq_update_inject_limit()). So the limit is likely to be 1930 * never, or at least seldom, updated. As a consequence, by 1931 * setting the limit to 1, we avoid that no injection ever 1932 * occurs with bfqq. On the downside, this proactive step 1933 * further reduces chances to actually compute the baseline 1934 * total service time. Thus it reduces chances to execute the 1935 * limit-update algorithm and possibly raise the limit to more 1936 * than 1. 1937 */ 1938 if (bfq_bfqq_has_short_ttime(bfqq)) 1939 bfqq->inject_limit = 0; 1940 else 1941 bfqq->inject_limit = 1; 1942 1943 bfqq->decrease_time_jif = jiffies; 1944} 1945 1946static void bfq_update_io_intensity(struct bfq_queue *bfqq, u64 now_ns) 1947{ 1948 u64 tot_io_time = now_ns - bfqq->io_start_time; 1949 1950 if (RB_EMPTY_ROOT(&bfqq->sort_list) && bfqq->dispatched == 0) 1951 bfqq->tot_idle_time += 1952 now_ns - bfqq->ttime.last_end_request; 1953 1954 if (unlikely(bfq_bfqq_just_created(bfqq))) 1955 return; 1956 1957 /* 1958 * Must be busy for at least about 80% of the time to be 1959 * considered I/O bound. 1960 */ 1961 if (bfqq->tot_idle_time * 5 > tot_io_time) 1962 bfq_clear_bfqq_IO_bound(bfqq); 1963 else 1964 bfq_mark_bfqq_IO_bound(bfqq); 1965 1966 /* 1967 * Keep an observation window of at most 200 ms in the past 1968 * from now. 1969 */ 1970 if (tot_io_time > 200 * NSEC_PER_MSEC) { 1971 bfqq->io_start_time = now_ns - (tot_io_time>>1); 1972 bfqq->tot_idle_time >>= 1; 1973 } 1974} 1975 1976/* 1977 * Detect whether bfqq's I/O seems synchronized with that of some 1978 * other queue, i.e., whether bfqq, after remaining empty, happens to 1979 * receive new I/O only right after some I/O request of the other 1980 * queue has been completed. We call waker queue the other queue, and 1981 * we assume, for simplicity, that bfqq may have at most one waker 1982 * queue. 1983 * 1984 * A remarkable throughput boost can be reached by unconditionally 1985 * injecting the I/O of the waker queue, every time a new 1986 * bfq_dispatch_request happens to be invoked while I/O is being 1987 * plugged for bfqq. In addition to boosting throughput, this 1988 * unblocks bfqq's I/O, thereby improving bandwidth and latency for 1989 * bfqq. Note that these same results may be achieved with the general 1990 * injection mechanism, but less effectively. For details on this 1991 * aspect, see the comments on the choice of the queue for injection 1992 * in bfq_select_queue(). 1993 * 1994 * Turning back to the detection of a waker queue, a queue Q is deemed 1995 * as a waker queue for bfqq if, for three consecutive times, bfqq 1996 * happens to become non empty right after a request of Q has been 1997 * completed. In this respect, even if bfqq is empty, we do not check 1998 * for a waker if it still has some in-flight I/O. In fact, in this 1999 * case bfqq is actually still being served by the drive, and may 2000 * receive new I/O on the completion of some of the in-flight
2001 * requests. In particular, on the first time, Q is tentatively set as 2002 * a candidate waker queue, while on the third consecutive time that Q 2003 * is detected, the field waker_bfqq is set to Q, to confirm that Q is 2004 * a waker queue for bfqq. These detection steps are performed only if 2005 * bfqq has a long think time, so as to make it more likely that 2006 * bfqq's I/O is actually being blocked by a synchronization. This 2007 * last filter, plus the above three-times requirement, make false 2008 * positives less likely. 2009 * 2010 * NOTE 2011 * 2012 * The sooner a waker queue is detected, the sooner throughput can be 2013 * boosted by injecting I/O from the waker queue. Fortunately, 2014 * detection is likely to be actually fast, for the following 2015 * reasons. While blocked by synchronization, bfqq has a long think 2016 * time. This implies that bfqq's inject limit is at least equal to 1 2017 * (see the comments in bfq_update_inject_limit()). So, thanks to 2018 * injection, the waker queue is likely to be served during the very 2019 * first I/O-plugging time interval for bfqq. This triggers the first 2020 * step of the detection mechanism. Thanks again to injection, the 2021 * candidate waker queue is then likely to be confirmed no later than 2022 * during the next I/O-plugging interval for bfqq. 2023 * 2024 * ISSUE 2025 * 2026 * On queue merging all waker information is lost. 2027 */ 2028static void bfq_check_waker(struct bfq_data *bfqd, struct bfq_queue *bfqq, 2029 u64 now_ns) 2030{ 2031 if (!bfqd->last_completed_rq_bfqq || 2032 bfqd->last_completed_rq_bfqq == bfqq || 2033 bfq_bfqq_has_short_ttime(bfqq) || 2034 bfqq->dispatched > 0 || 2035 now_ns - bfqd->last_completion >= 4 * NSEC_PER_MSEC || 2036 bfqd->last_completed_rq_bfqq == bfqq->waker_bfqq) 2037 return; 2038 2039 if (bfqd->last_completed_rq_bfqq != 2040 bfqq->tentative_waker_bfqq) { 2041 /* 2042 * First synchronization detected with a 2043 * candidate waker queue, or with a different 2044 * candidate waker queue from the current one. 2045 */ 2046 bfqq->tentative_waker_bfqq = 2047 bfqd->last_completed_rq_bfqq; 2048 bfqq->num_waker_detections = 1; 2049 } else /* Same tentative waker queue detected again */ 2050 bfqq->num_waker_detections++; 2051 2052 if (bfqq->num_waker_detections == 3) { 2053 bfqq->waker_bfqq = bfqd->last_completed_rq_bfqq; 2054 bfqq->tentative_waker_bfqq = NULL; 2055 2056 /* 2057 * If the waker queue disappears, then 2058 * bfqq->waker_bfqq must be reset. To 2059 * this goal, we maintain in each 2060 * waker queue a list, woken_list, of 2061 * all the queues that reference the 2062 * waker queue through their 2063 * waker_bfqq pointer. When the waker 2064 * queue exits, the waker_bfqq pointer 2065 * of all the queues in the woken_list 2066 * is reset. 2067 * 2068 * In addition, if bfqq is already in 2069 * the woken_list of a waker queue, 2070 * then, before being inserted into 2071 * the woken_list of a new waker 2072 * queue, bfqq must be removed from 2073 * the woken_list of the old waker 2074 * queue. 2075 */ 2076 if (!hlist_unhashed(&bfqq->woken_list_node)) 2077 hlist_del_init(&bfqq->woken_list_node); 2078 hlist_add_head(&bfqq->woken_list_node, 2079 &bfqd->last_completed_rq_bfqq->woken_list); 2080 } 2081} 2082 2083static void bfq_add_request(struct request *rq) 2084{ 2085 struct bfq_queue *bfqq = RQ_BFQQ(rq); 2086 struct bfq_data *bfqd = bfqq->bfqd; 2087 struct request *next_rq, *prev; 2088 unsigned int old_wr_coeff = bfqq->wr_coeff; 2089 bool interactive = false; 2090 u64 now_ns = ktime_get_ns(); 2091 2092 bfq_log_bfqq(bfqd, bfqq, "add_request %d", rq_is_sync(rq)); 2093 bfqq->queued[rq_is_sync(rq)]++; 2094 bfqd->queued++; 2095 2096 if (RB_EMPTY_ROOT(&bfqq->sort_list) && bfq_bfqq_sync(bfqq)) { 2097 bfq_check_waker(bfqd, bfqq, now_ns); 2098 2099 /* 2100 * Periodically reset inject limit, to make sure that 2101 * the latter eventually drops in case workload 2102 * changes, see step (3) in the comments on 2103 * bfq_update_inject_limit(). 2104 */ 2105 if (time_is_before_eq_jiffies(bfqq->decrease_time_jif + 2106 msecs_to_jiffies(1000))) 2107 bfq_reset_inject_limit(bfqd, bfqq); 2108 2109 /* 2110 * The following conditions must hold to setup a new 2111 * sampling of total service time, and then a new 2112 * update of the inject limit: 2113 * - bfqq is in service, because the total service 2114 * time is evaluated only for the I/O requests of 2115 * the queues in service; 2116 * - this is the right occasion to compute or to 2117 * lower the baseline total service time, because 2118 * there are actually no requests in the drive, 2119 * or 2120 * the baseline total service time is available, and 2121 * this is the right occasion to compute the other 2122 * quantity needed to update the inject limit, i.e., 2123 * the total service time caused by the amount of 2124 * injection allowed by the current value of the 2125 * limit. It is the right occasion because injection 2126 * has actually been performed during the service 2127 * hole, and there are still in-flight requests, 2128 * which are very likely to be exactly the injected 2129 * requests, or part of them; 2130 * - the minimum interval for sampling the total 2131 * service time and updating the inject limit has 2132 * elapsed. 2133 */ 2134 if (bfqq == bfqd->in_service_queue && 2135 (bfqd->rq_in_driver == 0 || 2136 (bfqq->last_serv_time_ns > 0 && 2137 bfqd->rqs_injected && bfqd->rq_in_driver > 0)) && 2138 time_is_before_eq_jiffies(bfqq->decrease_time_jif + 2139 msecs_to_jiffies(10))) { 2140 bfqd->last_empty_occupied_ns = ktime_get_ns(); 2141 /* 2142 * Start the state machine for measuring the 2143 * total service time of rq: setting 2144 * wait_dispatch will cause bfqd->waited_rq to 2145 * be set when rq will be dispatched. 2146 */ 2147 bfqd->wait_dispatch = true; 2148 /* 2149 * If there is no I/O in service in the drive, 2150 * then possible injection occurred before the 2151 * arrival of rq will not affect the total 2152 * service time of rq. So the injection limit 2153 * must not be updated as a function of such 2154 * total service time, unless new injection 2155 * occurs before rq is completed. To have the 2156 * injection limit updated only in the latter 2157 * case, reset rqs_injected here (rqs_injected 2158 * will be set in case injection is performed 2159 * on bfqq before rq is completed). 2160 */ 2161 if (bfqd->rq_in_driver == 0) 2162 bfqd->rqs_injected = false; 2163 } 2164 } 2165 2166 if (bfq_bfqq_sync(bfqq)) 2167 bfq_update_io_intensity(bfqq, now_ns); 2168 2169 elv_rb_add(&bfqq->sort_list, rq); 2170 2171 /* 2172 * Check if this request is a better next-serve candidate. 2173 */ 2174 prev = bfqq->next_rq; 2175 next_rq = bfq_choose_req(bfqd, bfqq->next_rq, rq, bfqd->last_position); 2176 bfqq->next_rq = next_rq; 2177 2178 /* 2179 * Adjust priority tree position, if next_rq changes. 2180 * See comments on bfq_pos_tree_add_move() for the unlikely(). 2181 */ 2182 if (unlikely(!bfqd->nonrot_with_queueing && prev != bfqq->next_rq)) 2183 bfq_pos_tree_add_move(bfqd, bfqq); 2184 2185 if (!bfq_bfqq_busy(bfqq)) /* switching to busy ... */ 2186 bfq_bfqq_handle_idle_busy_switch(bfqd, bfqq, old_wr_coeff, 2187 rq, &interactive); 2188 else { 2189 if (bfqd->low_latency && old_wr_coeff == 1 && !rq_is_sync(rq) && 2190 time_is_before_jiffies( 2191 bfqq->last_wr_start_finish + 2192 bfqd->bfq_wr_min_inter_arr_async)) { 2193 bfqq->wr_coeff = bfqd->bfq_wr_coeff; 2194 bfqq->wr_cur_max_time = bfq_wr_duration(bfqd); 2195 2196 bfqd->wr_busy_queues++; 2197 bfqq->entity.prio_changed = 1; 2198 } 2199 if (prev != bfqq->next_rq) 2200 bfq_updated_next_req(bfqd, bfqq); 2201 } 2202 2203 /* 2204 * Assign jiffies to last_wr_start_finish in the following 2205 * cases: 2206 * 2207 * . if bfqq is not going to be weight-raised, because, for 2208 * non weight-raised queues, last_wr_start_finish stores the 2209 * arrival time of the last request; as of now, this piece 2210 * of information is used only for deciding whether to 2211 * weight-raise async queues 2212 * 2213 * . if bfqq is not weight-raised, because, if bfqq is now 2214 * switching to weight-raised, then last_wr_start_finish 2215 * stores the time when weight-raising starts 2216 * 2217 * . if bfqq is interactive, because, regardless of whether 2218 * bfqq is currently weight-raised, the weight-raising 2219 * period must start or restart (this case is considered 2220 * separately because it is not detected by the above 2221 * conditions, if bfqq is already weight-raised) 2222 * 2223 * last_wr_start_finish has to be updated also if bfqq is soft 2224 * real-time, because the weight-raising period is constantly 2225 * restarted on idle-to-busy transitions for these queues, but 2226 * this is already done in bfq_bfqq_handle_idle_busy_switch if 2227 * needed. 2228 */ 2229 if (bfqd->low_latency && 2230 (old_wr_coeff == 1 || bfqq->wr_coeff == 1 || interactive)) 2231 bfqq->last_wr_start_finish = jiffies; 2232} 2233 2234static struct request *bfq_find_rq_fmerge(struct bfq_data *bfqd, 2235 struct bio *bio, 2236 struct request_queue *q) 2237{ 2238 struct bfq_queue *bfqq = bfqd->bio_bfqq; 2239 2240 2241 if (bfqq) 2242 return elv_rb_find(&bfqq->sort_list, bio_end_sector(bio)); 2243 2244 return NULL; 2245} 2246 2247static sector_t get_sdist(sector_t last_pos, struct request *rq) 2248{ 2249 if (last_pos) 2250 return abs(blk_rq_pos(rq) - last_pos); 2251 2252 return 0; 2253} 2254 2255#if 0 /* Still not clear if we can do without next two functions */ 2256static void bfq_activate_request(struct request_queue *q, struct request *rq) 2257{ 2258 struct bfq_data *bfqd = q->elevator->elevator_data; 2259 2260 bfqd->rq_in_driver++; 2261} 2262 2263static void bfq_deactivate_request(struct request_queue *q, struct request *rq) 2264{ 2265 struct bfq_data *bfqd = q->elevator->elevator_data; 2266 2267 bfqd->rq_in_driver--; 2268} 2269#endif 2270 2271static void bfq_remove_request(struct request_queue *q, 2272 struct request *rq) 2273{ 2274 struct bfq_queue *bfqq = RQ_BFQQ(rq); 2275 struct bfq_data *bfqd = bfqq->bfqd; 2276 const int sync = rq_is_sync(rq); 2277 2278 if (bfqq->next_rq == rq) { 2279 bfqq->next_rq = bfq_find_next_rq(bfqd, bfqq, rq); 2280 bfq_updated_next_req(bfqd, bfqq); 2281 } 2282 2283 if (rq->queuelist.prev != &rq->queuelist) 2284 list_del_init(&rq->queuelist); 2285 bfqq->queued[sync]--; 2286 bfqd->queued--; 2287 elv_rb_del(&bfqq->sort_list, rq); 2288 2289 elv_rqhash_del(q, rq); 2290 if (q->last_merge == rq) 2291 q->last_merge = NULL; 2292 2293 if (RB_EMPTY_ROOT(&bfqq->sort_list)) { 2294 bfqq->next_rq = NULL; 2295 2296 if (bfq_bfqq_busy(bfqq) && bfqq != bfqd->in_service_queue) { 2297 bfq_del_bfqq_busy(bfqd, bfqq, false); 2298 /* 2299 * bfqq emptied. In normal operation, when 2300 * bfqq is empty, bfqq->entity.service and 2301 * bfqq->entity.budget must contain, 2302 * respectively, the service received and the 2303 * budget used last time bfqq emptied. These 2304 * facts do not hold in this case, as at least 2305 * this last removal occurred while bfqq is 2306 * not in service. To avoid inconsistencies, 2307 * reset both bfqq->entity.service and 2308 * bfqq->entity.budget, if bfqq has still a 2309 * process that may issue I/O requests to it. 2310 */ 2311 bfqq->entity.budget = bfqq->entity.service = 0; 2312 } 2313 2314 /* 2315 * Remove queue from request-position tree as it is empty. 2316 */ 2317 if (bfqq->pos_root) { 2318 rb_erase(&bfqq->pos_node, bfqq->pos_root); 2319 bfqq->pos_root = NULL; 2320 } 2321 } else { 2322 /* see comments on bfq_pos_tree_add_move() for the unlikely() */ 2323 if (unlikely(!bfqd->nonrot_with_queueing)) 2324 bfq_pos_tree_add_move(bfqd, bfqq); 2325 } 2326 2327 if (rq->cmd_flags & REQ_META) 2328 bfqq->meta_pending--; 2329 2330} 2331 2332static bool bfq_bio_merge(struct blk_mq_hw_ctx *hctx, struct bio *bio) 2333{ 2334 struct request_queue *q = hctx->queue; 2335 struct bfq_data *bfqd = q->elevator->elevator_data; 2336 struct request *free = NULL; 2337 /* 2338 * bfq_bic_lookup grabs the queue_lock: invoke it now and 2339 * store its return value for later use, to avoid nesting 2340 * queue_lock inside the bfqd->lock. We assume that the bic 2341 * returned by bfq_bic_lookup does not go away before 2342 * bfqd->lock is taken. 2343 */ 2344 struct bfq_io_cq *bic = bfq_bic_lookup(bfqd, current->io_context, q); 2345 bool ret; 2346 2347 spin_lock_irq(&bfqd->lock); 2348 2349 if (bic) 2350 bfqd->bio_bfqq = bic_to_bfqq(bic, op_is_sync(bio->bi_opf)); 2351 else 2352 bfqd->bio_bfqq = NULL; 2353 bfqd->bio_bic = bic; 2354 2355 ret = blk_mq_sched_try_merge(q, bio, &free); 2356 2357 spin_unlock_irq(&bfqd->lock); 2358 if (free) 2359 blk_mq_free_request(free); 2360 2361 return ret; 2362} 2363 2364static int bfq_request_merge(struct request_queue *q, struct request **req, 2365 struct bio *bio) 2366{ 2367 struct bfq_data *bfqd = q->elevator->elevator_data; 2368 struct request *__rq; 2369 2370 __rq = bfq_find_rq_fmerge(bfqd, bio, q); 2371 if (__rq && elv_bio_merge_ok(__rq, bio)) { 2372 *req = __rq; 2373 2374 if (blk_discard_mergable(__rq)) 2375 return ELEVATOR_DISCARD_MERGE; 2376 return ELEVATOR_FRONT_MERGE; 2377 } 2378 2379 return ELEVATOR_NO_MERGE; 2380} 2381 2382static struct bfq_queue *bfq_init_rq(struct request *rq); 2383 2384static void bfq_request_merged(struct request_queue *q, struct request *req, 2385 enum elv_merge type) 2386{ 2387 if (type == ELEVATOR_FRONT_MERGE && 2388 rb_prev(&req->rb_node) && 2389 blk_rq_pos(req) < 2390 blk_rq_pos(container_of(rb_prev(&req->rb_node), 2391 struct request, rb_node))) { 2392 struct bfq_queue *bfqq = bfq_init_rq(req); 2393 struct bfq_data *bfqd; 2394 struct request *prev, *next_rq; 2395 2396 if (!bfqq) 2397 return; 2398 2399 bfqd = bfqq->bfqd; 2400 2401 /* Reposition request in its sort_list */ 2402 elv_rb_del(&bfqq->sort_list, req); 2403 elv_rb_add(&bfqq->sort_list, req); 2404 2405 /* Choose next request to be served for bfqq */ 2406 prev = bfqq->next_rq; 2407 next_rq = bfq_choose_req(bfqd, bfqq->next_rq, req, 2408 bfqd->last_position); 2409 bfqq->next_rq = next_rq; 2410 /* 2411 * If next_rq changes, update both the queue's budget to 2412 * fit the new request and the queue's position in its 2413 * rq_pos_tree. 2414 */ 2415 if (prev != bfqq->next_rq) { 2416 bfq_updated_next_req(bfqd, bfqq); 2417 /* 2418 * See comments on bfq_pos_tree_add_move() for 2419 * the unlikely(). 2420 */ 2421 if (unlikely(!bfqd->nonrot_with_queueing)) 2422 bfq_pos_tree_add_move(bfqd, bfqq); 2423 } 2424 } 2425} 2426 2427/* 2428 * This function is called to notify the scheduler that the requests 2429 * rq and 'next' have been merged, with 'next' going away. BFQ 2430 * exploits this hook to address the following issue: if 'next' has a 2431 * fifo_time lower that rq, then the fifo_time of rq must be set to 2432 * the value of 'next', to not forget the greater age of 'next'. 2433 * 2434 * NOTE: in this function we assume that rq is in a bfq_queue, basing 2435 * on that rq is picked from the hash table q->elevator->hash, which, 2436 * in its turn, is filled only with I/O requests present in 2437 * bfq_queues, while BFQ is in use for the request queue q. In fact, 2438 * the function that fills this hash table (elv_rqhash_add) is called 2439 * only by bfq_insert_request. 2440 */ 2441static void bfq_requests_merged(struct request_queue *q, struct request *rq, 2442 struct request *next) 2443{ 2444 struct bfq_queue *bfqq = bfq_init_rq(rq), 2445 *next_bfqq = bfq_init_rq(next); 2446 2447 if (!bfqq) 2448 goto remove; 2449 2450 /* 2451 * If next and rq belong to the same bfq_queue and next is older 2452 * than rq, then reposition rq in the fifo (by substituting next 2453 * with rq). Otherwise, if next and rq belong to different 2454 * bfq_queues, never reposition rq: in fact, we would have to 2455 * reposition it with respect to next's position in its own fifo, 2456 * which would most certainly be too expensive with respect to 2457 * the benefits. 2458 */ 2459 if (bfqq == next_bfqq && 2460 !list_empty(&rq->queuelist) && !list_empty(&next->queuelist) && 2461 next->fifo_time < rq->fifo_time) { 2462 list_del_init(&rq->queuelist); 2463 list_replace_init(&next->queuelist, &rq->queuelist); 2464 rq->fifo_time = next->fifo_time; 2465 } 2466 2467 if (bfqq->next_rq == next) 2468 bfqq->next_rq = rq; 2469 2470 bfqg_stats_update_io_merged(bfqq_group(bfqq), next->cmd_flags); 2471remove: 2472 /* Merged request may be in the IO scheduler. Remove it. */ 2473 if (!RB_EMPTY_NODE(&next->rb_node)) { 2474 bfq_remove_request(next->q, next); 2475 if (next_bfqq) 2476 bfqg_stats_update_io_remove(bfqq_group(next_bfqq), 2477 next->cmd_flags); 2478 } 2479} 2480 2481/* Must be called with bfqq != NULL */ 2482static void bfq_bfqq_end_wr(struct bfq_queue *bfqq) 2483{ 2484 /* 2485 * If bfqq has been enjoying interactive weight-raising, then 2486 * reset soft_rt_next_start. We do it for the following 2487 * reason. bfqq may have been conveying the I/O needed to load 2488 * a soft real-time application. Such an application actually 2489 * exhibits a soft real-time I/O pattern after it finishes 2490 * loading, and finally starts doing its job. But, if bfqq has 2491 * been receiving a lot of bandwidth so far (likely to happen 2492 * on a fast device), then soft_rt_next_start now contains a 2493 * high value that. So, without this reset, bfqq would be 2494 * prevented from being possibly considered as soft_rt for a 2495 * very long time. 2496 */ 2497 2498 if (bfqq->wr_cur_max_time != 2499 bfqq->bfqd->bfq_wr_rt_max_time) 2500 bfqq->soft_rt_next_start = jiffies; 2501 2502 if (bfq_bfqq_busy(bfqq)) 2503 bfqq->bfqd->wr_busy_queues--; 2504 bfqq->wr_coeff = 1; 2505 bfqq->wr_cur_max_time = 0; 2506 bfqq->last_wr_start_finish = jiffies; 2507 /* 2508 * Trigger a weight change on the next invocation of 2509 * __bfq_entity_update_weight_prio. 2510 */ 2511 bfqq->entity.prio_changed = 1; 2512} 2513 2514void bfq_end_wr_async_queues(struct bfq_data *bfqd, 2515 struct bfq_group *bfqg) 2516{ 2517 int i, j; 2518 2519 for (i = 0; i < 2; i++) 2520 for (j = 0; j < IOPRIO_BE_NR; j++) 2521 if (bfqg->async_bfqq[i][j]) 2522 bfq_bfqq_end_wr(bfqg->async_bfqq[i][j]); 2523 if (bfqg->async_idle_bfqq) 2524 bfq_bfqq_end_wr(bfqg->async_idle_bfqq); 2525} 2526 2527static void bfq_end_wr(struct bfq_data *bfqd) 2528{ 2529 struct bfq_queue *bfqq; 2530 2531 spin_lock_irq(&bfqd->lock); 2532 2533 list_for_each_entry(bfqq, &bfqd->active_list, bfqq_list) 2534 bfq_bfqq_end_wr(bfqq); 2535 list_for_each_entry(bfqq, &bfqd->idle_list, bfqq_list) 2536 bfq_bfqq_end_wr(bfqq); 2537 bfq_end_wr_async(bfqd); 2538 2539 spin_unlock_irq(&bfqd->lock); 2540} 2541 2542static sector_t bfq_io_struct_pos(void *io_struct, bool request) 2543{ 2544 if (request) 2545 return blk_rq_pos(io_struct); 2546 else 2547 return ((struct bio *)io_struct)->bi_iter.bi_sector; 2548} 2549 2550static int bfq_rq_close_to_sector(void *io_struct, bool request, 2551 sector_t sector) 2552{ 2553 return abs(bfq_io_struct_pos(io_struct, request) - sector) <= 2554 BFQQ_CLOSE_THR; 2555} 2556 2557static struct bfq_queue *bfqq_find_close(struct bfq_data *bfqd, 2558 struct bfq_queue *bfqq, 2559 sector_t sector) 2560{ 2561 struct rb_root *root = &bfq_bfqq_to_bfqg(bfqq)->rq_pos_tree; 2562 struct rb_node *parent, *node; 2563 struct bfq_queue *__bfqq; 2564 2565 if (RB_EMPTY_ROOT(root)) 2566 return NULL; 2567 2568 /* 2569 * First, if we find a request starting at the end of the last 2570 * request, choose it. 2571 */ 2572 __bfqq = bfq_rq_pos_tree_lookup(bfqd, root, sector, &parent, NULL); 2573 if (__bfqq) 2574 return __bfqq; 2575 2576 /* 2577 * If the exact sector wasn't found, the parent of the NULL leaf 2578 * will contain the closest sector (rq_pos_tree sorted by 2579 * next_request position). 2580 */ 2581 __bfqq = rb_entry(parent, struct bfq_queue, pos_node); 2582 if (bfq_rq_close_to_sector(__bfqq->next_rq, true, sector)) 2583 return __bfqq; 2584 2585 if (blk_rq_pos(__bfqq->next_rq) < sector) 2586 node = rb_next(&__bfqq->pos_node); 2587 else 2588 node = rb_prev(&__bfqq->pos_node); 2589 if (!node) 2590 return NULL; 2591 2592 __bfqq = rb_entry(node, struct bfq_queue, pos_node); 2593 if (bfq_rq_close_to_sector(__bfqq->next_rq, true, sector)) 2594 return __bfqq; 2595 2596 return NULL; 2597} 2598 2599static struct bfq_queue *bfq_find_close_cooperator(struct bfq_data *bfqd, 2600 struct bfq_queue *cur_bfqq, 2601 sector_t sector) 2602{ 2603 struct bfq_queue *bfqq; 2604 2605 /* 2606 * We shall notice if some of the queues are cooperating, 2607 * e.g., working closely on the same area of the device. In 2608 * that case, we can group them together and: 1) don't waste 2609 * time idling, and 2) serve the union of their requests in 2610 * the best possible order for throughput. 2611 */ 2612 bfqq = bfqq_find_close(bfqd, cur_bfqq, sector); 2613 if (!bfqq || bfqq == cur_bfqq) 2614 return NULL; 2615 2616 return bfqq; 2617} 2618 2619static struct bfq_queue * 2620bfq_setup_merge(struct bfq_queue *bfqq, struct bfq_queue *new_bfqq) 2621{ 2622 int process_refs, new_process_refs; 2623 struct bfq_queue *__bfqq; 2624 2625 /* 2626 * If there are no process references on the new_bfqq, then it is 2627 * unsafe to follow the ->new_bfqq chain as other bfqq's in the chain 2628 * may have dropped their last reference (not just their last process 2629 * reference). 2630 */ 2631 if (!bfqq_process_refs(new_bfqq)) 2632 return NULL; 2633 2634 /* Avoid a circular list and skip interim queue merges. */ 2635 while ((__bfqq = new_bfqq->new_bfqq)) { 2636 if (__bfqq == bfqq) 2637 return NULL; 2638 new_bfqq = __bfqq; 2639 } 2640 2641 process_refs = bfqq_process_refs(bfqq); 2642 new_process_refs = bfqq_process_refs(new_bfqq); 2643 /* 2644 * If the process for the bfqq has gone away, there is no 2645 * sense in merging the queues. 2646 */ 2647 if (process_refs == 0 || new_process_refs == 0) 2648 return NULL; 2649 2650 bfq_log_bfqq(bfqq->bfqd, bfqq, "scheduling merge with queue %d", 2651 new_bfqq->pid); 2652 2653 /* 2654 * Merging is just a redirection: the requests of the process 2655 * owning one of the two queues are redirected to the other queue. 2656 * The latter queue, in its turn, is set as shared if this is the 2657 * first time that the requests of some process are redirected to 2658 * it. 2659 * 2660 * We redirect bfqq to new_bfqq and not the opposite, because 2661 * we are in the context of the process owning bfqq, thus we 2662 * have the io_cq of this process. So we can immediately 2663 * configure this io_cq to redirect the requests of the 2664 * process to new_bfqq. In contrast, the io_cq of new_bfqq is 2665 * not available any more (new_bfqq->bic == NULL). 2666 * 2667 * Anyway, even in case new_bfqq coincides with the in-service 2668 * queue, redirecting requests the in-service queue is the 2669 * best option, as we feed the in-service queue with new 2670 * requests close to the last request served and, by doing so, 2671 * are likely to increase the throughput. 2672 */ 2673 bfqq->new_bfqq = new_bfqq; 2674 new_bfqq->ref += process_refs; 2675 return new_bfqq; 2676} 2677 2678static bool bfq_may_be_close_cooperator(struct bfq_queue *bfqq, 2679 struct bfq_queue *new_bfqq) 2680{ 2681 if (bfq_too_late_for_merging(new_bfqq)) 2682 return false; 2683 2684 if (bfq_class_idle(bfqq) || bfq_class_idle(new_bfqq) || 2685 (bfqq->ioprio_class != new_bfqq->ioprio_class)) 2686 return false; 2687 2688 /* 2689 * If either of the queues has already been detected as seeky, 2690 * then merging it with the other queue is unlikely to lead to 2691 * sequential I/O. 2692 */ 2693 if (BFQQ_SEEKY(bfqq) || BFQQ_SEEKY(new_bfqq)) 2694 return false; 2695 2696 /* 2697 * Interleaved I/O is known to be done by (some) applications 2698 * only for reads, so it does not make sense to merge async 2699 * queues. 2700 */ 2701 if (!bfq_bfqq_sync(bfqq) || !bfq_bfqq_sync(new_bfqq)) 2702 return false; 2703 2704 return true; 2705} 2706 2707static bool idling_boosts_thr_without_issues(struct bfq_data *bfqd, 2708 struct bfq_queue *bfqq); 2709 2710/* 2711 * Attempt to schedule a merge of bfqq with the currently in-service 2712 * queue or with a close queue among the scheduled queues. Return 2713 * NULL if no merge was scheduled, a pointer to the shared bfq_queue 2714 * structure otherwise. 2715 * 2716 * The OOM queue is not allowed to participate to cooperation: in fact, since 2717 * the requests temporarily redirected to the OOM queue could be redirected 2718 * again to dedicated queues at any time, the state needed to correctly 2719 * handle merging with the OOM queue would be quite complex and expensive 2720 * to maintain. Besides, in such a critical condition as an out of memory, 2721 * the benefits of queue merging may be little relevant, or even negligible. 2722 * 2723 * WARNING: queue merging may impair fairness among non-weight raised 2724 * queues, for at least two reasons: 1) the original weight of a 2725 * merged queue may change during the merged state, 2) even being the 2726 * weight the same, a merged queue may be bloated with many more 2727 * requests than the ones produced by its originally-associated 2728 * process. 2729 */ 2730static struct bfq_queue * 2731bfq_setup_cooperator(struct bfq_data *bfqd, struct bfq_queue *bfqq, 2732 void *io_struct, bool request, struct bfq_io_cq *bic) 2733{ 2734 struct bfq_queue *in_service_bfqq, *new_bfqq; 2735 2736 /* 2737 * Check delayed stable merge for rotational or non-queueing 2738 * devs. For this branch to be executed, bfqq must not be 2739 * currently merged with some other queue (i.e., bfqq->bic 2740 * must be non null). If we considered also merged queues, 2741 * then we should also check whether bfqq has already been 2742 * merged with bic->stable_merge_bfqq. But this would be 2743 * costly and complicated. 2744 */ 2745 if (unlikely(!bfqd->nonrot_with_queueing)) { 2746 /* 2747 * Make sure also that bfqq is sync, because 2748 * bic->stable_merge_bfqq may point to some queue (for 2749 * stable merging) also if bic is associated with a 2750 * sync queue, but this bfqq is async 2751 */ 2752 if (bfq_bfqq_sync(bfqq) && bic->stable_merge_bfqq && 2753 !bfq_bfqq_just_created(bfqq) && 2754 time_is_before_jiffies(bfqq->split_time + 2755 msecs_to_jiffies(bfq_late_stable_merging)) && 2756 time_is_before_jiffies(bfqq->creation_time + 2757 msecs_to_jiffies(bfq_late_stable_merging))) { 2758 struct bfq_queue *stable_merge_bfqq = 2759 bic->stable_merge_bfqq; 2760 int proc_ref = min(bfqq_process_refs(bfqq), 2761 bfqq_process_refs(stable_merge_bfqq)); 2762 2763 /* deschedule stable merge, because done or aborted here */ 2764 bfq_put_stable_ref(stable_merge_bfqq); 2765 2766 bic->stable_merge_bfqq = NULL; 2767 2768 if (!idling_boosts_thr_without_issues(bfqd, bfqq) && 2769 proc_ref > 0) { 2770 /* next function will take at least one ref */ 2771 struct bfq_queue *new_bfqq = 2772 bfq_setup_merge(bfqq, stable_merge_bfqq); 2773 2774 bic->stably_merged = true; 2775 if (new_bfqq && new_bfqq->bic) 2776 new_bfqq->bic->stably_merged = true; 2777 return new_bfqq; 2778 } else 2779 return NULL; 2780 } 2781 } 2782 2783 /* 2784 * Do not perform queue merging if the device is non 2785 * rotational and performs internal queueing. In fact, such a 2786 * device reaches a high speed through internal parallelism 2787 * and pipelining. This means that, to reach a high 2788 * throughput, it must have many requests enqueued at the same 2789 * time. But, in this configuration, the internal scheduling 2790 * algorithm of the device does exactly the job of queue 2791 * merging: it reorders requests so as to obtain as much as 2792 * possible a sequential I/O pattern. As a consequence, with 2793 * the workload generated by processes doing interleaved I/O, 2794 * the throughput reached by the device is likely to be the 2795 * same, with and without queue merging. 2796 * 2797 * Disabling merging also provides a remarkable benefit in 2798 * terms of throughput. Merging tends to make many workloads 2799 * artificially more uneven, because of shared queues 2800 * remaining non empty for incomparably more time than 2801 * non-merged queues. This may accentuate workload 2802 * asymmetries. For example, if one of the queues in a set of 2803 * merged queues has a higher weight than a normal queue, then 2804 * the shared queue may inherit such a high weight and, by 2805 * staying almost always active, may force BFQ to perform I/O 2806 * plugging most of the time. This evidently makes it harder 2807 * for BFQ to let the device reach a high throughput. 2808 * 2809 * Finally, the likely() macro below is not used because one 2810 * of the two branches is more likely than the other, but to 2811 * have the code path after the following if() executed as 2812 * fast as possible for the case of a non rotational device 2813 * with queueing. We want it because this is the fastest kind 2814 * of device. On the opposite end, the likely() may lengthen 2815 * the execution time of BFQ for the case of slower devices 2816 * (rotational or at least without queueing). But in this case 2817 * the execution time of BFQ matters very little, if not at 2818 * all. 2819 */ 2820 if (likely(bfqd->nonrot_with_queueing)) 2821 return NULL; 2822 2823 /* 2824 * Prevent bfqq from being merged if it has been created too 2825 * long ago. The idea is that true cooperating processes, and 2826 * thus their associated bfq_queues, are supposed to be 2827 * created shortly after each other. This is the case, e.g., 2828 * for KVM/QEMU and dump I/O threads. Basing on this 2829 * assumption, the following filtering greatly reduces the 2830 * probability that two non-cooperating processes, which just 2831 * happen to do close I/O for some short time interval, have 2832 * their queues merged by mistake. 2833 */ 2834 if (bfq_too_late_for_merging(bfqq)) 2835 return NULL; 2836 2837 if (bfqq->new_bfqq) 2838 return bfqq->new_bfqq; 2839 2840 if (!io_struct || unlikely(bfqq == &bfqd->oom_bfqq)) 2841 return NULL; 2842 2843 /* If there is only one backlogged queue, don't search. */ 2844 if (bfq_tot_busy_queues(bfqd) == 1) 2845 return NULL; 2846 2847 in_service_bfqq = bfqd->in_service_queue; 2848 2849 if (in_service_bfqq && in_service_bfqq != bfqq && 2850 likely(in_service_bfqq != &bfqd->oom_bfqq) && 2851 bfq_rq_close_to_sector(io_struct, request, 2852 bfqd->in_serv_last_pos) && 2853 bfqq->entity.parent == in_service_bfqq->entity.parent && 2854 bfq_may_be_close_cooperator(bfqq, in_service_bfqq)) { 2855 new_bfqq = bfq_setup_merge(bfqq, in_service_bfqq); 2856 if (new_bfqq) 2857 return new_bfqq; 2858 } 2859 /* 2860 * Check whether there is a cooperator among currently scheduled 2861 * queues. The only thing we need is that the bio/request is not 2862 * NULL, as we need it to establish whether a cooperator exists. 2863 */ 2864 new_bfqq = bfq_find_close_cooperator(bfqd, bfqq, 2865 bfq_io_struct_pos(io_struct, request)); 2866 2867 if (new_bfqq && likely(new_bfqq != &bfqd->oom_bfqq) && 2868 bfq_may_be_close_cooperator(bfqq, new_bfqq)) 2869 return bfq_setup_merge(bfqq, new_bfqq); 2870 2871 return NULL; 2872} 2873 2874static void bfq_bfqq_save_state(struct bfq_queue *bfqq) 2875{ 2876 struct bfq_io_cq *bic = bfqq->bic; 2877 2878 /* 2879 * If !bfqq->bic, the queue is already shared or its requests 2880 * have already been redirected to a shared queue; both idle window 2881 * and weight raising state have already been saved. Do nothing. 2882 */ 2883 if (!bic) 2884 return; 2885 2886 bic->saved_last_serv_time_ns = bfqq->last_serv_time_ns; 2887 bic->saved_inject_limit = bfqq->inject_limit; 2888 bic->saved_decrease_time_jif = bfqq->decrease_time_jif; 2889 2890 bic->saved_weight = bfqq->entity.orig_weight; 2891 bic->saved_ttime = bfqq->ttime; 2892 bic->saved_has_short_ttime = bfq_bfqq_has_short_ttime(bfqq); 2893 bic->saved_IO_bound = bfq_bfqq_IO_bound(bfqq); 2894 bic->saved_io_start_time = bfqq->io_start_time; 2895 bic->saved_tot_idle_time = bfqq->tot_idle_time; 2896 bic->saved_in_large_burst = bfq_bfqq_in_large_burst(bfqq); 2897 bic->was_in_burst_list = !hlist_unhashed(&bfqq->burst_list_node); 2898 if (unlikely(bfq_bfqq_just_created(bfqq) && 2899 !bfq_bfqq_in_large_burst(bfqq) && 2900 bfqq->bfqd->low_latency)) { 2901 /* 2902 * bfqq being merged right after being created: bfqq 2903 * would have deserved interactive weight raising, but 2904 * did not make it to be set in a weight-raised state, 2905 * because of this early merge. Store directly the 2906 * weight-raising state that would have been assigned 2907 * to bfqq, so that to avoid that bfqq unjustly fails 2908 * to enjoy weight raising if split soon. 2909 */ 2910 bic->saved_wr_coeff = bfqq->bfqd->bfq_wr_coeff; 2911 bic->saved_wr_start_at_switch_to_srt = bfq_smallest_from_now(); 2912 bic->saved_wr_cur_max_time = bfq_wr_duration(bfqq->bfqd); 2913 bic->saved_last_wr_start_finish = jiffies; 2914 } else { 2915 bic->saved_wr_coeff = bfqq->wr_coeff; 2916 bic->saved_wr_start_at_switch_to_srt = 2917 bfqq->wr_start_at_switch_to_srt; 2918 bic->saved_service_from_wr = bfqq->service_from_wr; 2919 bic->saved_last_wr_start_finish = bfqq->last_wr_start_finish; 2920 bic->saved_wr_cur_max_time = bfqq->wr_cur_max_time; 2921 } 2922} 2923 2924 2925static void 2926bfq_reassign_last_bfqq(struct bfq_queue *cur_bfqq, struct bfq_queue *new_bfqq) 2927{ 2928 if (cur_bfqq->entity.parent && 2929 cur_bfqq->entity.parent->last_bfqq_created == cur_bfqq) 2930 cur_bfqq->entity.parent->last_bfqq_created = new_bfqq; 2931 else if (cur_bfqq->bfqd && cur_bfqq->bfqd->last_bfqq_created == cur_bfqq) 2932 cur_bfqq->bfqd->last_bfqq_created = new_bfqq; 2933} 2934 2935void bfq_release_process_ref(struct bfq_data *bfqd, struct bfq_queue *bfqq) 2936{ 2937 /* 2938 * To prevent bfqq's service guarantees from being violated, 2939 * bfqq may be left busy, i.e., queued for service, even if 2940 * empty (see comments in __bfq_bfqq_expire() for 2941 * details). But, if no process will send requests to bfqq any 2942 * longer, then there is no point in keeping bfqq queued for 2943 * service. In addition, keeping bfqq queued for service, but 2944 * with no process ref any longer, may have caused bfqq to be 2945 * freed when dequeued from service. But this is assumed to 2946 * never happen. 2947 */ 2948 if (bfq_bfqq_busy(bfqq) && RB_EMPTY_ROOT(&bfqq->sort_list) && 2949 bfqq != bfqd->in_service_queue) 2950 bfq_del_bfqq_busy(bfqd, bfqq, false); 2951 2952 bfq_reassign_last_bfqq(bfqq, NULL); 2953 2954 bfq_put_queue(bfqq); 2955} 2956 2957static void 2958bfq_merge_bfqqs(struct bfq_data *bfqd, struct bfq_io_cq *bic, 2959 struct bfq_queue *bfqq, struct bfq_queue *new_bfqq) 2960{ 2961 bfq_log_bfqq(bfqd, bfqq, "merging with queue %lu", 2962 (unsigned long)new_bfqq->pid); 2963 /* Save weight raising and idle window of the merged queues */ 2964 bfq_bfqq_save_state(bfqq); 2965 bfq_bfqq_save_state(new_bfqq); 2966 if (bfq_bfqq_IO_bound(bfqq)) 2967 bfq_mark_bfqq_IO_bound(new_bfqq); 2968 bfq_clear_bfqq_IO_bound(bfqq); 2969 2970 /* 2971 * The processes associated with bfqq are cooperators of the 2972 * processes associated with new_bfqq. So, if bfqq has a 2973 * waker, then assume that all these processes will be happy 2974 * to let bfqq's waker freely inject I/O when they have no 2975 * I/O. 2976 */ 2977 if (bfqq->waker_bfqq && !new_bfqq->waker_bfqq && 2978 bfqq->waker_bfqq != new_bfqq) { 2979 new_bfqq->waker_bfqq = bfqq->waker_bfqq; 2980 new_bfqq->tentative_waker_bfqq = NULL; 2981 2982 /* 2983 * If the waker queue disappears, then 2984 * new_bfqq->waker_bfqq must be reset. So insert 2985 * new_bfqq into the woken_list of the waker. See 2986 * bfq_check_waker for details. 2987 */ 2988 hlist_add_head(&new_bfqq->woken_list_node, 2989 &new_bfqq->waker_bfqq->woken_list); 2990 2991 } 2992 2993 /* 2994 * If bfqq is weight-raised, then let new_bfqq inherit 2995 * weight-raising. To reduce false positives, neglect the case 2996 * where bfqq has just been created, but has not yet made it 2997 * to be weight-raised (which may happen because EQM may merge 2998 * bfqq even before bfq_add_request is executed for the first 2999 * time for bfqq). Handling this case would however be very 3000 * easy, thanks to the flag just_created.
3001 */ 3002 if (new_bfqq->wr_coeff == 1 && bfqq->wr_coeff > 1) { 3003 new_bfqq->wr_coeff = bfqq->wr_coeff; 3004 new_bfqq->wr_cur_max_time = bfqq->wr_cur_max_time; 3005 new_bfqq->last_wr_start_finish = bfqq->last_wr_start_finish; 3006 new_bfqq->wr_start_at_switch_to_srt = 3007 bfqq->wr_start_at_switch_to_srt; 3008 if (bfq_bfqq_busy(new_bfqq)) 3009 bfqd->wr_busy_queues++; 3010 new_bfqq->entity.prio_changed = 1; 3011 } 3012 3013 if (bfqq->wr_coeff > 1) { /* bfqq has given its wr to new_bfqq */ 3014 bfqq->wr_coeff = 1; 3015 bfqq->entity.prio_changed = 1; 3016 if (bfq_bfqq_busy(bfqq)) 3017 bfqd->wr_busy_queues--; 3018 } 3019 3020 bfq_log_bfqq(bfqd, new_bfqq, "merge_bfqqs: wr_busy %d", 3021 bfqd->wr_busy_queues); 3022 3023 /* 3024 * Merge queues (that is, let bic redirect its requests to new_bfqq) 3025 */ 3026 bic_set_bfqq(bic, new_bfqq, 1); 3027 bfq_mark_bfqq_coop(new_bfqq); 3028 /* 3029 * new_bfqq now belongs to at least two bics (it is a shared queue): 3030 * set new_bfqq->bic to NULL. bfqq either: 3031 * - does not belong to any bic any more, and hence bfqq->bic must 3032 * be set to NULL, or 3033 * - is a queue whose owning bics have already been redirected to a 3034 * different queue, hence the queue is destined to not belong to 3035 * any bic soon and bfqq->bic is already NULL (therefore the next 3036 * assignment causes no harm). 3037 */ 3038 new_bfqq->bic = NULL; 3039 /* 3040 * If the queue is shared, the pid is the pid of one of the associated 3041 * processes. Which pid depends on the exact sequence of merge events 3042 * the queue underwent. So printing such a pid is useless and confusing 3043 * because it reports a random pid between those of the associated 3044 * processes. 3045 * We mark such a queue with a pid -1, and then print SHARED instead of 3046 * a pid in logging messages. 3047 */ 3048 new_bfqq->pid = -1; 3049 bfqq->bic = NULL; 3050 3051 bfq_reassign_last_bfqq(bfqq, new_bfqq); 3052 3053 bfq_release_process_ref(bfqd, bfqq); 3054} 3055 3056static bool bfq_allow_bio_merge(struct request_queue *q, struct request *rq, 3057 struct bio *bio) 3058{ 3059 struct bfq_data *bfqd = q->elevator->elevator_data; 3060 bool is_sync = op_is_sync(bio->bi_opf); 3061 struct bfq_queue *bfqq = bfqd->bio_bfqq, *new_bfqq; 3062 3063 /* 3064 * Disallow merge of a sync bio into an async request. 3065 */ 3066 if (is_sync && !rq_is_sync(rq)) 3067 return false; 3068 3069 /* 3070 * Lookup the bfqq that this bio will be queued with. Allow 3071 * merge only if rq is queued there. 3072 */ 3073 if (!bfqq) 3074 return false; 3075 3076 /* 3077 * We take advantage of this function to perform an early merge 3078 * of the queues of possible cooperating processes. 3079 */ 3080 new_bfqq = bfq_setup_cooperator(bfqd, bfqq, bio, false, bfqd->bio_bic); 3081 if (new_bfqq) { 3082 /* 3083 * bic still points to bfqq, then it has not yet been 3084 * redirected to some other bfq_queue, and a queue 3085 * merge beween bfqq and new_bfqq can be safely 3086 * fulfillled, i.e., bic can be redirected to new_bfqq 3087 * and bfqq can be put. 3088 */ 3089 bfq_merge_bfqqs(bfqd, bfqd->bio_bic, bfqq, 3090 new_bfqq); 3091 /* 3092 * If we get here, bio will be queued into new_queue, 3093 * so use new_bfqq to decide whether bio and rq can be 3094 * merged. 3095 */ 3096 bfqq = new_bfqq; 3097 3098 /* 3099 * Change also bqfd->bio_bfqq, as 3100 * bfqd->bio_bic now points to new_bfqq, and 3101 * this function may be invoked again (and then may 3102 * use again bqfd->bio_bfqq). 3103 */ 3104 bfqd->bio_bfqq = bfqq; 3105 } 3106 3107 return bfqq == RQ_BFQQ(rq); 3108} 3109 3110/* 3111 * Set the maximum time for the in-service queue to consume its 3112 * budget. This prevents seeky processes from lowering the throughput. 3113 * In practice, a time-slice service scheme is used with seeky 3114 * processes. 3115 */ 3116static void bfq_set_budget_timeout(struct bfq_data *bfqd, 3117 struct bfq_queue *bfqq) 3118{ 3119 unsigned int timeout_coeff; 3120 3121 if (bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time) 3122 timeout_coeff = 1; 3123 else 3124 timeout_coeff = bfqq->entity.weight / bfqq->entity.orig_weight; 3125 3126 bfqd->last_budget_start = ktime_get(); 3127 3128 bfqq->budget_timeout = jiffies + 3129 bfqd->bfq_timeout * timeout_coeff; 3130} 3131 3132static void __bfq_set_in_service_queue(struct bfq_data *bfqd, 3133 struct bfq_queue *bfqq) 3134{ 3135 if (bfqq) { 3136 bfq_clear_bfqq_fifo_expire(bfqq); 3137 3138 bfqd->budgets_assigned = (bfqd->budgets_assigned * 7 + 256) / 8; 3139 3140 if (time_is_before_jiffies(bfqq->last_wr_start_finish) && 3141 bfqq->wr_coeff > 1 && 3142 bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time && 3143 time_is_before_jiffies(bfqq->budget_timeout)) { 3144 /* 3145 * For soft real-time queues, move the start 3146 * of the weight-raising period forward by the 3147 * time the queue has not received any 3148 * service. Otherwise, a relatively long 3149 * service delay is likely to cause the 3150 * weight-raising period of the queue to end, 3151 * because of the short duration of the 3152 * weight-raising period of a soft real-time 3153 * queue. It is worth noting that this move 3154 * is not so dangerous for the other queues, 3155 * because soft real-time queues are not 3156 * greedy. 3157 * 3158 * To not add a further variable, we use the 3159 * overloaded field budget_timeout to 3160 * determine for how long the queue has not 3161 * received service, i.e., how much time has 3162 * elapsed since the queue expired. However, 3163 * this is a little imprecise, because 3164 * budget_timeout is set to jiffies if bfqq 3165 * not only expires, but also remains with no 3166 * request. 3167 */ 3168 if (time_after(bfqq->budget_timeout, 3169 bfqq->last_wr_start_finish)) 3170 bfqq->last_wr_start_finish += 3171 jiffies - bfqq->budget_timeout; 3172 else 3173 bfqq->last_wr_start_finish = jiffies; 3174 } 3175 3176 bfq_set_budget_timeout(bfqd, bfqq); 3177 bfq_log_bfqq(bfqd, bfqq, 3178 "set_in_service_queue, cur-budget = %d", 3179 bfqq->entity.budget); 3180 } 3181 3182 bfqd->in_service_queue = bfqq; 3183 bfqd->in_serv_last_pos = 0; 3184} 3185 3186/* 3187 * Get and set a new queue for service. 3188 */ 3189static struct bfq_queue *bfq_set_in_service_queue(struct bfq_data *bfqd) 3190{ 3191 struct bfq_queue *bfqq = bfq_get_next_queue(bfqd); 3192 3193 __bfq_set_in_service_queue(bfqd, bfqq); 3194 return bfqq; 3195} 3196 3197static void bfq_arm_slice_timer(struct bfq_data *bfqd) 3198{ 3199 struct bfq_queue *bfqq = bfqd->in_service_queue; 3200 u32 sl; 3201 3202 bfq_mark_bfqq_wait_request(bfqq); 3203 3204 /* 3205 * We don't want to idle for seeks, but we do want to allow 3206 * fair distribution of slice time for a process doing back-to-back 3207 * seeks. So allow a little bit of time for him to submit a new rq. 3208 */ 3209 sl = bfqd->bfq_slice_idle; 3210 /* 3211 * Unless the queue is being weight-raised or the scenario is 3212 * asymmetric, grant only minimum idle time if the queue 3213 * is seeky. A long idling is preserved for a weight-raised 3214 * queue, or, more in general, in an asymmetric scenario, 3215 * because a long idling is needed for guaranteeing to a queue 3216 * its reserved share of the throughput (in particular, it is 3217 * needed if the queue has a higher weight than some other 3218 * queue). 3219 */ 3220 if (BFQQ_SEEKY(bfqq) && bfqq->wr_coeff == 1 && 3221 !bfq_asymmetric_scenario(bfqd, bfqq)) 3222 sl = min_t(u64, sl, BFQ_MIN_TT); 3223 else if (bfqq->wr_coeff > 1) 3224 sl = max_t(u32, sl, 20ULL * NSEC_PER_MSEC); 3225 3226 bfqd->last_idling_start = ktime_get(); 3227 bfqd->last_idling_start_jiffies = jiffies; 3228 3229 hrtimer_start(&bfqd->idle_slice_timer, ns_to_ktime(sl), 3230 HRTIMER_MODE_REL); 3231 bfqg_stats_set_start_idle_time(bfqq_group(bfqq)); 3232} 3233 3234/* 3235 * In autotuning mode, max_budget is dynamically recomputed as the 3236 * amount of sectors transferred in timeout at the estimated peak 3237 * rate. This enables BFQ to utilize a full timeslice with a full 3238 * budget, even if the in-service queue is served at peak rate. And 3239 * this maximises throughput with sequential workloads. 3240 */ 3241static unsigned long bfq_calc_max_budget(struct bfq_data *bfqd) 3242{ 3243 return (u64)bfqd->peak_rate * USEC_PER_MSEC * 3244 jiffies_to_msecs(bfqd->bfq_timeout)>>BFQ_RATE_SHIFT; 3245} 3246 3247/* 3248 * Update parameters related to throughput and responsiveness, as a 3249 * function of the estimated peak rate. See comments on 3250 * bfq_calc_max_budget(), and on the ref_wr_duration array. 3251 */ 3252static void update_thr_responsiveness_params(struct bfq_data *bfqd) 3253{ 3254 if (bfqd->bfq_user_max_budget == 0) { 3255 bfqd->bfq_max_budget = 3256 bfq_calc_max_budget(bfqd); 3257 bfq_log(bfqd, "new max_budget = %d", bfqd->bfq_max_budget); 3258 } 3259} 3260 3261static void bfq_reset_rate_computation(struct bfq_data *bfqd, 3262 struct request *rq) 3263{ 3264 if (rq != NULL) { /* new rq dispatch now, reset accordingly */ 3265 bfqd->last_dispatch = bfqd->first_dispatch = ktime_get_ns(); 3266 bfqd->peak_rate_samples = 1; 3267 bfqd->sequential_samples = 0; 3268 bfqd->tot_sectors_dispatched = bfqd->last_rq_max_size = 3269 blk_rq_sectors(rq); 3270 } else /* no new rq dispatched, just reset the number of samples */ 3271 bfqd->peak_rate_samples = 0; /* full re-init on next disp. */ 3272 3273 bfq_log(bfqd, 3274 "reset_rate_computation at end, sample %u/%u tot_sects %llu", 3275 bfqd->peak_rate_samples, bfqd->sequential_samples, 3276 bfqd->tot_sectors_dispatched); 3277} 3278 3279static void bfq_update_rate_reset(struct bfq_data *bfqd, struct request *rq) 3280{ 3281 u32 rate, weight, divisor; 3282 3283 /* 3284 * For the convergence property to hold (see comments on 3285 * bfq_update_peak_rate()) and for the assessment to be 3286 * reliable, a minimum number of samples must be present, and 3287 * a minimum amount of time must have elapsed. If not so, do 3288 * not compute new rate. Just reset parameters, to get ready 3289 * for a new evaluation attempt. 3290 */ 3291 if (bfqd->peak_rate_samples < BFQ_RATE_MIN_SAMPLES || 3292 bfqd->delta_from_first < BFQ_RATE_MIN_INTERVAL) 3293 goto reset_computation; 3294 3295 /* 3296 * If a new request completion has occurred after last 3297 * dispatch, then, to approximate the rate at which requests 3298 * have been served by the device, it is more precise to 3299 * extend the observation interval to the last completion. 3300 */ 3301 bfqd->delta_from_first = 3302 max_t(u64, bfqd->delta_from_first, 3303 bfqd->last_completion - bfqd->first_dispatch); 3304 3305 /* 3306 * Rate computed in sects/usec, and not sects/nsec, for 3307 * precision issues. 3308 */ 3309 rate = div64_ul(bfqd->tot_sectors_dispatched<<BFQ_RATE_SHIFT, 3310 div_u64(bfqd->delta_from_first, NSEC_PER_USEC)); 3311 3312 /* 3313 * Peak rate not updated if: 3314 * - the percentage of sequential dispatches is below 3/4 of the 3315 * total, and rate is below the current estimated peak rate 3316 * - rate is unreasonably high (> 20M sectors/sec) 3317 */ 3318 if ((bfqd->sequential_samples < (3 * bfqd->peak_rate_samples)>>2 && 3319 rate <= bfqd->peak_rate) || 3320 rate > 20<<BFQ_RATE_SHIFT) 3321 goto reset_computation; 3322 3323 /* 3324 * We have to update the peak rate, at last! To this purpose, 3325 * we use a low-pass filter. We compute the smoothing constant 3326 * of the filter as a function of the 'weight' of the new 3327 * measured rate. 3328 * 3329 * As can be seen in next formulas, we define this weight as a 3330 * quantity proportional to how sequential the workload is, 3331 * and to how long the observation time interval is. 3332 * 3333 * The weight runs from 0 to 8. The maximum value of the 3334 * weight, 8, yields the minimum value for the smoothing 3335 * constant. At this minimum value for the smoothing constant, 3336 * the measured rate contributes for half of the next value of 3337 * the estimated peak rate. 3338 * 3339 * So, the first step is to compute the weight as a function 3340 * of how sequential the workload is. Note that the weight 3341 * cannot reach 9, because bfqd->sequential_samples cannot 3342 * become equal to bfqd->peak_rate_samples, which, in its 3343 * turn, holds true because bfqd->sequential_samples is not 3344 * incremented for the first sample. 3345 */ 3346 weight = (9 * bfqd->sequential_samples) / bfqd->peak_rate_samples; 3347 3348 /* 3349 * Second step: further refine the weight as a function of the 3350 * duration of the observation interval. 3351 */ 3352 weight = min_t(u32, 8, 3353 div_u64(weight * bfqd->delta_from_first, 3354 BFQ_RATE_REF_INTERVAL)); 3355 3356 /* 3357 * Divisor ranging from 10, for minimum weight, to 2, for 3358 * maximum weight. 3359 */ 3360 divisor = 10 - weight; 3361 3362 /* 3363 * Finally, update peak rate: 3364 * 3365 * peak_rate = peak_rate * (divisor-1) / divisor + rate / divisor 3366 */ 3367 bfqd->peak_rate *= divisor-1; 3368 bfqd->peak_rate /= divisor; 3369 rate /= divisor; /* smoothing constant alpha = 1/divisor */ 3370 3371 bfqd->peak_rate += rate; 3372 3373 /* 3374 * For a very slow device, bfqd->peak_rate can reach 0 (see 3375 * the minimum representable values reported in the comments 3376 * on BFQ_RATE_SHIFT). Push to 1 if this happens, to avoid 3377 * divisions by zero where bfqd->peak_rate is used as a 3378 * divisor. 3379 */ 3380 bfqd->peak_rate = max_t(u32, 1, bfqd->peak_rate); 3381 3382 update_thr_responsiveness_params(bfqd); 3383 3384reset_computation: 3385 bfq_reset_rate_computation(bfqd, rq); 3386} 3387 3388/* 3389 * Update the read/write peak rate (the main quantity used for 3390 * auto-tuning, see update_thr_responsiveness_params()). 3391 * 3392 * It is not trivial to estimate the peak rate (correctly): because of 3393 * the presence of sw and hw queues between the scheduler and the 3394 * device components that finally serve I/O requests, it is hard to 3395 * say exactly when a given dispatched request is served inside the 3396 * device, and for how long. As a consequence, it is hard to know 3397 * precisely at what rate a given set of requests is actually served 3398 * by the device. 3399 * 3400 * On the opposite end, the dispatch time of any request is trivially 3401 * available, and, from this piece of information, the "dispatch rate" 3402 * of requests can be immediately computed. So, the idea in the next 3403 * function is to use what is known, namely request dispatch times 3404 * (plus, when useful, request completion times), to estimate what is 3405 * unknown, namely in-device request service rate. 3406 * 3407 * The main issue is that, because of the above facts, the rate at 3408 * which a certain set of requests is dispatched over a certain time 3409 * interval can vary greatly with respect to the rate at which the 3410 * same requests are then served. But, since the size of any 3411 * intermediate queue is limited, and the service scheme is lossless 3412 * (no request is silently dropped), the following obvious convergence 3413 * property holds: the number of requests dispatched MUST become 3414 * closer and closer to the number of requests completed as the 3415 * observation interval grows. This is the key property used in 3416 * the next function to estimate the peak service rate as a function 3417 * of the observed dispatch rate. The function assumes to be invoked 3418 * on every request dispatch. 3419 */ 3420static void bfq_update_peak_rate(struct bfq_data *bfqd, struct request *rq) 3421{ 3422 u64 now_ns = ktime_get_ns(); 3423 3424 if (bfqd->peak_rate_samples == 0) { /* first dispatch */ 3425 bfq_log(bfqd, "update_peak_rate: goto reset, samples %d", 3426 bfqd->peak_rate_samples); 3427 bfq_reset_rate_computation(bfqd, rq); 3428 goto update_last_values; /* will add one sample */ 3429 } 3430 3431 /* 3432 * Device idle for very long: the observation interval lasting 3433 * up to this dispatch cannot be a valid observation interval 3434 * for computing a new peak rate (similarly to the late- 3435 * completion event in bfq_completed_request()). Go to 3436 * update_rate_and_reset to have the following three steps 3437 * taken: 3438 * - close the observation interval at the last (previous) 3439 * request dispatch or completion 3440 * - compute rate, if possible, for that observation interval 3441 * - start a new observation interval with this dispatch 3442 */ 3443 if (now_ns - bfqd->last_dispatch > 100*NSEC_PER_MSEC && 3444 bfqd->rq_in_driver == 0) 3445 goto update_rate_and_reset; 3446 3447 /* Update sampling information */ 3448 bfqd->peak_rate_samples++; 3449 3450 if ((bfqd->rq_in_driver > 0 || 3451 now_ns - bfqd->last_completion < BFQ_MIN_TT) 3452 && !BFQ_RQ_SEEKY(bfqd, bfqd->last_position, rq)) 3453 bfqd->sequential_samples++; 3454 3455 bfqd->tot_sectors_dispatched += blk_rq_sectors(rq); 3456 3457 /* Reset max observed rq size every 32 dispatches */ 3458 if (likely(bfqd->peak_rate_samples % 32)) 3459 bfqd->last_rq_max_size = 3460 max_t(u32, blk_rq_sectors(rq), bfqd->last_rq_max_size); 3461 else 3462 bfqd->last_rq_max_size = blk_rq_sectors(rq); 3463 3464 bfqd->delta_from_first = now_ns - bfqd->first_dispatch; 3465 3466 /* Target observation interval not yet reached, go on sampling */ 3467 if (bfqd->delta_from_first < BFQ_RATE_REF_INTERVAL) 3468 goto update_last_values; 3469 3470update_rate_and_reset: 3471 bfq_update_rate_reset(bfqd, rq); 3472update_last_values: 3473 bfqd->last_position = blk_rq_pos(rq) + blk_rq_sectors(rq); 3474 if (RQ_BFQQ(rq) == bfqd->in_service_queue) 3475 bfqd->in_serv_last_pos = bfqd->last_position; 3476 bfqd->last_dispatch = now_ns; 3477} 3478 3479/* 3480 * Remove request from internal lists. 3481 */ 3482static void bfq_dispatch_remove(struct request_queue *q, struct request *rq) 3483{ 3484 struct bfq_queue *bfqq = RQ_BFQQ(rq); 3485 3486 /* 3487 * For consistency, the next instruction should have been 3488 * executed after removing the request from the queue and 3489 * dispatching it. We execute instead this instruction before 3490 * bfq_remove_request() (and hence introduce a temporary 3491 * inconsistency), for efficiency. In fact, should this 3492 * dispatch occur for a non in-service bfqq, this anticipated 3493 * increment prevents two counters related to bfqq->dispatched 3494 * from risking to be, first, uselessly decremented, and then 3495 * incremented again when the (new) value of bfqq->dispatched 3496 * happens to be taken into account. 3497 */ 3498 bfqq->dispatched++; 3499 bfq_update_peak_rate(q->elevator->elevator_data, rq); 3500 3501 bfq_remove_request(q, rq); 3502} 3503 3504/* 3505 * There is a case where idling does not have to be performed for 3506 * throughput concerns, but to preserve the throughput share of 3507 * the process associated with bfqq. 3508 * 3509 * To introduce this case, we can note that allowing the drive 3510 * to enqueue more than one request at a time, and hence 3511 * delegating de facto final scheduling decisions to the 3512 * drive's internal scheduler, entails loss of control on the 3513 * actual request service order. In particular, the critical 3514 * situation is when requests from different processes happen 3515 * to be present, at the same time, in the internal queue(s) 3516 * of the drive. In such a situation, the drive, by deciding 3517 * the service order of the internally-queued requests, does 3518 * determine also the actual throughput distribution among 3519 * these processes. But the drive typically has no notion or 3520 * concern about per-process throughput distribution, and 3521 * makes its decisions only on a per-request basis. Therefore, 3522 * the service distribution enforced by the drive's internal 3523 * scheduler is likely to coincide with the desired throughput 3524 * distribution only in a completely symmetric, or favorably 3525 * skewed scenario where: 3526 * (i-a) each of these processes must get the same throughput as 3527 * the others, 3528 * (i-b) in case (i-a) does not hold, it holds that the process 3529 * associated with bfqq must receive a lower or equal 3530 * throughput than any of the other processes; 3531 * (ii) the I/O of each process has the same properties, in 3532 * terms of locality (sequential or random), direction 3533 * (reads or writes), request sizes, greediness 3534 * (from I/O-bound to sporadic), and so on; 3535 3536 * In fact, in such a scenario, the drive tends to treat the requests 3537 * of each process in about the same way as the requests of the 3538 * others, and thus to provide each of these processes with about the 3539 * same throughput. This is exactly the desired throughput 3540 * distribution if (i-a) holds, or, if (i-b) holds instead, this is an 3541 * even more convenient distribution for (the process associated with) 3542 * bfqq. 3543 * 3544 * In contrast, in any asymmetric or unfavorable scenario, device 3545 * idling (I/O-dispatch plugging) is certainly needed to guarantee 3546 * that bfqq receives its assigned fraction of the device throughput 3547 * (see [1] for details). 3548 * 3549 * The problem is that idling may significantly reduce throughput with 3550 * certain combinations of types of I/O and devices. An important 3551 * example is sync random I/O on flash storage with command 3552 * queueing. So, unless bfqq falls in cases where idling also boosts 3553 * throughput, it is important to check conditions (i-a), i(-b) and 3554 * (ii) accurately, so as to avoid idling when not strictly needed for 3555 * service guarantees. 3556 * 3557 * Unfortunately, it is extremely difficult to thoroughly check 3558 * condition (ii). And, in case there are active groups, it becomes 3559 * very difficult to check conditions (i-a) and (i-b) too. In fact, 3560 * if there are active groups, then, for conditions (i-a) or (i-b) to 3561 * become false 'indirectly', it is enough that an active group 3562 * contains more active processes or sub-groups than some other active 3563 * group. More precisely, for conditions (i-a) or (i-b) to become 3564 * false because of such a group, it is not even necessary that the 3565 * group is (still) active: it is sufficient that, even if the group 3566 * has become inactive, some of its descendant processes still have 3567 * some request already dispatched but still waiting for 3568 * completion. In fact, requests have still to be guaranteed their 3569 * share of the throughput even after being dispatched. In this 3570 * respect, it is easy to show that, if a group frequently becomes 3571 * inactive while still having in-flight requests, and if, when this 3572 * happens, the group is not considered in the calculation of whether 3573 * the scenario is asymmetric, then the group may fail to be 3574 * guaranteed its fair share of the throughput (basically because 3575 * idling may not be performed for the descendant processes of the 3576 * group, but it had to be). We address this issue with the following 3577 * bi-modal behavior, implemented in the function 3578 * bfq_asymmetric_scenario(). 3579 * 3580 * If there are groups with requests waiting for completion 3581 * (as commented above, some of these groups may even be 3582 * already inactive), then the scenario is tagged as 3583 * asymmetric, conservatively, without checking any of the 3584 * conditions (i-a), (i-b) or (ii). So the device is idled for bfqq. 3585 * This behavior matches also the fact that groups are created 3586 * exactly if controlling I/O is a primary concern (to 3587 * preserve bandwidth and latency guarantees). 3588 * 3589 * On the opposite end, if there are no groups with requests waiting 3590 * for completion, then only conditions (i-a) and (i-b) are actually 3591 * controlled, i.e., provided that conditions (i-a) or (i-b) holds, 3592 * idling is not performed, regardless of whether condition (ii) 3593 * holds. In other words, only if conditions (i-a) and (i-b) do not 3594 * hold, then idling is allowed, and the device tends to be prevented 3595 * from queueing many requests, possibly of several processes. Since 3596 * there are no groups with requests waiting for completion, then, to 3597 * control conditions (i-a) and (i-b) it is enough to check just 3598 * whether all the queues with requests waiting for completion also 3599 * have the same weight. 3600 * 3601 * Not checking condition (ii) evidently exposes bfqq to the 3602 * risk of getting less throughput than its fair share. 3603 * However, for queues with the same weight, a further 3604 * mechanism, preemption, mitigates or even eliminates this 3605 * problem. And it does so without consequences on overall 3606 * throughput. This mechanism and its benefits are explained 3607 * in the next three paragraphs. 3608 * 3609 * Even if a queue, say Q, is expired when it remains idle, Q 3610 * can still preempt the new in-service queue if the next 3611 * request of Q arrives soon (see the comments on 3612 * bfq_bfqq_update_budg_for_activation). If all queues and 3613 * groups have the same weight, this form of preemption, 3614 * combined with the hole-recovery heuristic described in the 3615 * comments on function bfq_bfqq_update_budg_for_activation, 3616 * are enough to preserve a correct bandwidth distribution in 3617 * the mid term, even without idling. In fact, even if not 3618 * idling allows the internal queues of the device to contain 3619 * many requests, and thus to reorder requests, we can rather 3620 * safely assume that the internal scheduler still preserves a 3621 * minimum of mid-term fairness. 3622 * 3623 * More precisely, this preemption-based, idleless approach 3624 * provides fairness in terms of IOPS, and not sectors per 3625 * second. This can be seen with a simple example. Suppose 3626 * that there are two queues with the same weight, but that 3627 * the first queue receives requests of 8 sectors, while the 3628 * second queue receives requests of 1024 sectors. In 3629 * addition, suppose that each of the two queues contains at 3630 * most one request at a time, which implies that each queue 3631 * always remains idle after it is served. Finally, after 3632 * remaining idle, each queue receives very quickly a new 3633 * request. It follows that the two queues are served 3634 * alternatively, preempting each other if needed. This 3635 * implies that, although both queues have the same weight, 3636 * the queue with large requests receives a service that is 3637 * 1024/8 times as high as the service received by the other 3638 * queue. 3639 * 3640 * The motivation for using preemption instead of idling (for 3641 * queues with the same weight) is that, by not idling, 3642 * service guarantees are preserved (completely or at least in 3643 * part) without minimally sacrificing throughput. And, if 3644 * there is no active group, then the primary expectation for 3645 * this device is probably a high throughput. 3646 * 3647 * We are now left only with explaining the two sub-conditions in the 3648 * additional compound condition that is checked below for deciding 3649 * whether the scenario is asymmetric. To explain the first 3650 * sub-condition, we need to add that the function 3651 * bfq_asymmetric_scenario checks the weights of only 3652 * non-weight-raised queues, for efficiency reasons (see comments on 3653 * bfq_weights_tree_add()). Then the fact that bfqq is weight-raised 3654 * is checked explicitly here. More precisely, the compound condition 3655 * below takes into account also the fact that, even if bfqq is being 3656 * weight-raised, the scenario is still symmetric if all queues with 3657 * requests waiting for completion happen to be 3658 * weight-raised. Actually, we should be even more precise here, and 3659 * differentiate between interactive weight raising and soft real-time 3660 * weight raising. 3661 * 3662 * The second sub-condition checked in the compound condition is 3663 * whether there is a fair amount of already in-flight I/O not 3664 * belonging to bfqq. If so, I/O dispatching is to be plugged, for the 3665 * following reason. The drive may decide to serve in-flight 3666 * non-bfqq's I/O requests before bfqq's ones, thereby delaying the 3667 * arrival of new I/O requests for bfqq (recall that bfqq is sync). If 3668 * I/O-dispatching is not plugged, then, while bfqq remains empty, a 3669 * basically uncontrolled amount of I/O from other queues may be 3670 * dispatched too, possibly causing the service of bfqq's I/O to be 3671 * delayed even longer in the drive. This problem gets more and more 3672 * serious as the speed and the queue depth of the drive grow, 3673 * because, as these two quantities grow, the probability to find no 3674 * queue busy but many requests in flight grows too. By contrast, 3675 * plugging I/O dispatching minimizes the delay induced by already 3676 * in-flight I/O, and enables bfqq to recover the bandwidth it may 3677 * lose because of this delay. 3678 * 3679 * As a side note, it is worth considering that the above 3680 * device-idling countermeasures may however fail in the following 3681 * unlucky scenario: if I/O-dispatch plugging is (correctly) disabled 3682 * in a time period during which all symmetry sub-conditions hold, and 3683 * therefore the device is allowed to enqueue many requests, but at 3684 * some later point in time some sub-condition stops to hold, then it 3685 * may become impossible to make requests be served in the desired 3686 * order until all the requests already queued in the device have been 3687 * served. The last sub-condition commented above somewhat mitigates 3688 * this problem for weight-raised queues. 3689 * 3690 * However, as an additional mitigation for this problem, we preserve 3691 * plugging for a special symmetric case that may suddenly turn into 3692 * asymmetric: the case where only bfqq is busy. In this case, not 3693 * expiring bfqq does not cause any harm to any other queues in terms 3694 * of service guarantees. In contrast, it avoids the following unlucky 3695 * sequence of events: (1) bfqq is expired, (2) a new queue with a 3696 * lower weight than bfqq becomes busy (or more queues), (3) the new 3697 * queue is served until a new request arrives for bfqq, (4) when bfqq 3698 * is finally served, there are so many requests of the new queue in 3699 * the drive that the pending requests for bfqq take a lot of time to 3700 * be served. In particular, event (2) may case even already 3701 * dispatched requests of bfqq to be delayed, inside the drive. So, to 3702 * avoid this series of events, the scenario is preventively declared 3703 * as asymmetric also if bfqq is the only busy queues 3704 */ 3705static bool idling_needed_for_service_guarantees(struct bfq_data *bfqd, 3706 struct bfq_queue *bfqq) 3707{ 3708 int tot_busy_queues = bfq_tot_busy_queues(bfqd); 3709 3710 /* No point in idling for bfqq if it won't get requests any longer */ 3711 if (unlikely(!bfqq_process_refs(bfqq))) 3712 return false; 3713 3714 return (bfqq->wr_coeff > 1 && 3715 (bfqd->wr_busy_queues < 3716 tot_busy_queues || 3717 bfqd->rq_in_driver >= 3718 bfqq->dispatched + 4)) || 3719 bfq_asymmetric_scenario(bfqd, bfqq) || 3720 tot_busy_queues == 1; 3721} 3722 3723static bool __bfq_bfqq_expire(struct bfq_data *bfqd, struct bfq_queue *bfqq, 3724 enum bfqq_expiration reason) 3725{ 3726 /* 3727 * If this bfqq is shared between multiple processes, check 3728 * to make sure that those processes are still issuing I/Os 3729 * within the mean seek distance. If not, it may be time to 3730 * break the queues apart again. 3731 */ 3732 if (bfq_bfqq_coop(bfqq) && BFQQ_SEEKY(bfqq)) 3733 bfq_mark_bfqq_split_coop(bfqq); 3734 3735 /* 3736 * Consider queues with a higher finish virtual time than 3737 * bfqq. If idling_needed_for_service_guarantees(bfqq) returns 3738 * true, then bfqq's bandwidth would be violated if an 3739 * uncontrolled amount of I/O from these queues were 3740 * dispatched while bfqq is waiting for its new I/O to 3741 * arrive. This is exactly what may happen if this is a forced 3742 * expiration caused by a preemption attempt, and if bfqq is 3743 * not re-scheduled. To prevent this from happening, re-queue 3744 * bfqq if it needs I/O-dispatch plugging, even if it is 3745 * empty. By doing so, bfqq is granted to be served before the 3746 * above queues (provided that bfqq is of course eligible). 3747 */ 3748 if (RB_EMPTY_ROOT(&bfqq->sort_list) && 3749 !(reason == BFQQE_PREEMPTED && 3750 idling_needed_for_service_guarantees(bfqd, bfqq))) { 3751 if (bfqq->dispatched == 0) 3752 /* 3753 * Overloading budget_timeout field to store 3754 * the time at which the queue remains with no 3755 * backlog and no outstanding request; used by 3756 * the weight-raising mechanism. 3757 */ 3758 bfqq->budget_timeout = jiffies; 3759 3760 bfq_del_bfqq_busy(bfqd, bfqq, true); 3761 } else { 3762 bfq_requeue_bfqq(bfqd, bfqq, true); 3763 /* 3764 * Resort priority tree of potential close cooperators. 3765 * See comments on bfq_pos_tree_add_move() for the unlikely(). 3766 */ 3767 if (unlikely(!bfqd->nonrot_with_queueing && 3768 !RB_EMPTY_ROOT(&bfqq->sort_list))) 3769 bfq_pos_tree_add_move(bfqd, bfqq); 3770 } 3771 3772 /* 3773 * All in-service entities must have been properly deactivated 3774 * or requeued before executing the next function, which 3775 * resets all in-service entities as no more in service. This 3776 * may cause bfqq to be freed. If this happens, the next 3777 * function returns true. 3778 */ 3779 return __bfq_bfqd_reset_in_service(bfqd); 3780} 3781 3782/** 3783 * __bfq_bfqq_recalc_budget - try to adapt the budget to the @bfqq behavior. 3784 * @bfqd: device data. 3785 * @bfqq: queue to update. 3786 * @reason: reason for expiration. 3787 * 3788 * Handle the feedback on @bfqq budget at queue expiration. 3789 * See the body for detailed comments. 3790 */ 3791static void __bfq_bfqq_recalc_budget(struct bfq_data *bfqd, 3792 struct bfq_queue *bfqq, 3793 enum bfqq_expiration reason) 3794{ 3795 struct request *next_rq; 3796 int budget, min_budget; 3797 3798 min_budget = bfq_min_budget(bfqd); 3799 3800 if (bfqq->wr_coeff == 1) 3801 budget = bfqq->max_budget; 3802 else /* 3803 * Use a constant, low budget for weight-raised queues, 3804 * to help achieve a low latency. Keep it slightly higher 3805 * than the minimum possible budget, to cause a little 3806 * bit fewer expirations. 3807 */ 3808 budget = 2 * min_budget; 3809 3810 bfq_log_bfqq(bfqd, bfqq, "recalc_budg: last budg %d, budg left %d", 3811 bfqq->entity.budget, bfq_bfqq_budget_left(bfqq)); 3812 bfq_log_bfqq(bfqd, bfqq, "recalc_budg: last max_budg %d, min budg %d", 3813 budget, bfq_min_budget(bfqd)); 3814 bfq_log_bfqq(bfqd, bfqq, "recalc_budg: sync %d, seeky %d", 3815 bfq_bfqq_sync(bfqq), BFQQ_SEEKY(bfqd->in_service_queue)); 3816 3817 if (bfq_bfqq_sync(bfqq) && bfqq->wr_coeff == 1) { 3818 switch (reason) { 3819 /* 3820 * Caveat: in all the following cases we trade latency 3821 * for throughput. 3822 */ 3823 case BFQQE_TOO_IDLE: 3824 /* 3825 * This is the only case where we may reduce 3826 * the budget: if there is no request of the 3827 * process still waiting for completion, then 3828 * we assume (tentatively) that the timer has 3829 * expired because the batch of requests of 3830 * the process could have been served with a 3831 * smaller budget. Hence, betting that 3832 * process will behave in the same way when it 3833 * becomes backlogged again, we reduce its 3834 * next budget. As long as we guess right, 3835 * this budget cut reduces the latency 3836 * experienced by the process. 3837 * 3838 * However, if there are still outstanding 3839 * requests, then the process may have not yet 3840 * issued its next request just because it is 3841 * still waiting for the completion of some of 3842 * the still outstanding ones. So in this 3843 * subcase we do not reduce its budget, on the 3844 * contrary we increase it to possibly boost 3845 * the throughput, as discussed in the 3846 * comments to the BUDGET_TIMEOUT case. 3847 */ 3848 if (bfqq->dispatched > 0) /* still outstanding reqs */ 3849 budget = min(budget * 2, bfqd->bfq_max_budget); 3850 else { 3851 if (budget > 5 * min_budget) 3852 budget -= 4 * min_budget; 3853 else 3854 budget = min_budget; 3855 } 3856 break; 3857 case BFQQE_BUDGET_TIMEOUT: 3858 /* 3859 * We double the budget here because it gives 3860 * the chance to boost the throughput if this 3861 * is not a seeky process (and has bumped into 3862 * this timeout because of, e.g., ZBR). 3863 */ 3864 budget = min(budget * 2, bfqd->bfq_max_budget); 3865 break; 3866 case BFQQE_BUDGET_EXHAUSTED: 3867 /* 3868 * The process still has backlog, and did not 3869 * let either the budget timeout or the disk 3870 * idling timeout expire. Hence it is not 3871 * seeky, has a short thinktime and may be 3872 * happy with a higher budget too. So 3873 * definitely increase the budget of this good 3874 * candidate to boost the disk throughput. 3875 */ 3876 budget = min(budget * 4, bfqd->bfq_max_budget); 3877 break; 3878 case BFQQE_NO_MORE_REQUESTS: 3879 /* 3880 * For queues that expire for this reason, it 3881 * is particularly important to keep the 3882 * budget close to the actual service they 3883 * need. Doing so reduces the timestamp 3884 * misalignment problem described in the 3885 * comments in the body of 3886 * __bfq_activate_entity. In fact, suppose 3887 * that a queue systematically expires for 3888 * BFQQE_NO_MORE_REQUESTS and presents a 3889 * new request in time to enjoy timestamp 3890 * back-shifting. The larger the budget of the 3891 * queue is with respect to the service the 3892 * queue actually requests in each service 3893 * slot, the more times the queue can be 3894 * reactivated with the same virtual finish 3895 * time. It follows that, even if this finish 3896 * time is pushed to the system virtual time 3897 * to reduce the consequent timestamp 3898 * misalignment, the queue unjustly enjoys for 3899 * many re-activations a lower finish time 3900 * than all newly activated queues. 3901 * 3902 * The service needed by bfqq is measured 3903 * quite precisely by bfqq->entity.service. 3904 * Since bfqq does not enjoy device idling, 3905 * bfqq->entity.service is equal to the number 3906 * of sectors that the process associated with 3907 * bfqq requested to read/write before waiting 3908 * for request completions, or blocking for 3909 * other reasons. 3910 */ 3911 budget = max_t(int, bfqq->entity.service, min_budget); 3912 break; 3913 default: 3914 return; 3915 } 3916 } else if (!bfq_bfqq_sync(bfqq)) { 3917 /* 3918 * Async queues get always the maximum possible 3919 * budget, as for them we do not care about latency 3920 * (in addition, their ability to dispatch is limited 3921 * by the charging factor). 3922 */ 3923 budget = bfqd->bfq_max_budget; 3924 } 3925 3926 bfqq->max_budget = budget; 3927 3928 if (bfqd->budgets_assigned >= bfq_stats_min_budgets && 3929 !bfqd->bfq_user_max_budget) 3930 bfqq->max_budget = min(bfqq->max_budget, bfqd->bfq_max_budget); 3931 3932 /* 3933 * If there is still backlog, then assign a new budget, making 3934 * sure that it is large enough for the next request. Since 3935 * the finish time of bfqq must be kept in sync with the 3936 * budget, be sure to call __bfq_bfqq_expire() *after* this 3937 * update. 3938 * 3939 * If there is no backlog, then no need to update the budget; 3940 * it will be updated on the arrival of a new request. 3941 */ 3942 next_rq = bfqq->next_rq; 3943 if (next_rq) 3944 bfqq->entity.budget = max_t(unsigned long, bfqq->max_budget, 3945 bfq_serv_to_charge(next_rq, bfqq)); 3946 3947 bfq_log_bfqq(bfqd, bfqq, "head sect: %u, new budget %d", 3948 next_rq ? blk_rq_sectors(next_rq) : 0, 3949 bfqq->entity.budget); 3950} 3951 3952/* 3953 * Return true if the process associated with bfqq is "slow". The slow 3954 * flag is used, in addition to the budget timeout, to reduce the 3955 * amount of service provided to seeky processes, and thus reduce 3956 * their chances to lower the throughput. More details in the comments 3957 * on the function bfq_bfqq_expire(). 3958 * 3959 * An important observation is in order: as discussed in the comments 3960 * on the function bfq_update_peak_rate(), with devices with internal 3961 * queues, it is hard if ever possible to know when and for how long 3962 * an I/O request is processed by the device (apart from the trivial 3963 * I/O pattern where a new request is dispatched only after the 3964 * previous one has been completed). This makes it hard to evaluate 3965 * the real rate at which the I/O requests of each bfq_queue are 3966 * served. In fact, for an I/O scheduler like BFQ, serving a 3967 * bfq_queue means just dispatching its requests during its service 3968 * slot (i.e., until the budget of the queue is exhausted, or the 3969 * queue remains idle, or, finally, a timeout fires). But, during the 3970 * service slot of a bfq_queue, around 100 ms at most, the device may 3971 * be even still processing requests of bfq_queues served in previous 3972 * service slots. On the opposite end, the requests of the in-service 3973 * bfq_queue may be completed after the service slot of the queue 3974 * finishes. 3975 * 3976 * Anyway, unless more sophisticated solutions are used 3977 * (where possible), the sum of the sizes of the requests dispatched 3978 * during the service slot of a bfq_queue is probably the only 3979 * approximation available for the service received by the bfq_queue 3980 * during its service slot. And this sum is the quantity used in this 3981 * function to evaluate the I/O speed of a process. 3982 */ 3983static bool bfq_bfqq_is_slow(struct bfq_data *bfqd, struct bfq_queue *bfqq, 3984 bool compensate, enum bfqq_expiration reason, 3985 unsigned long *delta_ms) 3986{ 3987 ktime_t delta_ktime; 3988 u32 delta_usecs; 3989 bool slow = BFQQ_SEEKY(bfqq); /* if delta too short, use seekyness */ 3990 3991 if (!bfq_bfqq_sync(bfqq)) 3992 return false; 3993 3994 if (compensate) 3995 delta_ktime = bfqd->last_idling_start; 3996 else 3997 delta_ktime = ktime_get(); 3998 delta_ktime = ktime_sub(delta_ktime, bfqd->last_budget_start); 3999 delta_usecs = ktime_to_us(delta_ktime); 4000
4001 /* don't use too short time intervals */ 4002 if (delta_usecs < 1000) { 4003 if (blk_queue_nonrot(bfqd->queue)) 4004 /* 4005 * give same worst-case guarantees as idling 4006 * for seeky 4007 */ 4008 *delta_ms = BFQ_MIN_TT / NSEC_PER_MSEC; 4009 else /* charge at least one seek */ 4010 *delta_ms = bfq_slice_idle / NSEC_PER_MSEC; 4011 4012 return slow; 4013 } 4014 4015 *delta_ms = delta_usecs / USEC_PER_MSEC; 4016 4017 /* 4018 * Use only long (> 20ms) intervals to filter out excessive 4019 * spikes in service rate estimation. 4020 */ 4021 if (delta_usecs > 20000) { 4022 /* 4023 * Caveat for rotational devices: processes doing I/O 4024 * in the slower disk zones tend to be slow(er) even 4025 * if not seeky. In this respect, the estimated peak 4026 * rate is likely to be an average over the disk 4027 * surface. Accordingly, to not be too harsh with 4028 * unlucky processes, a process is deemed slow only if 4029 * its rate has been lower than half of the estimated 4030 * peak rate. 4031 */ 4032 slow = bfqq->entity.service < bfqd->bfq_max_budget / 2; 4033 } 4034 4035 bfq_log_bfqq(bfqd, bfqq, "bfq_bfqq_is_slow: slow %d", slow); 4036 4037 return slow; 4038} 4039 4040/* 4041 * To be deemed as soft real-time, an application must meet two 4042 * requirements. First, the application must not require an average 4043 * bandwidth higher than the approximate bandwidth required to playback or 4044 * record a compressed high-definition video. 4045 * The next function is invoked on the completion of the last request of a 4046 * batch, to compute the next-start time instant, soft_rt_next_start, such 4047 * that, if the next request of the application does not arrive before 4048 * soft_rt_next_start, then the above requirement on the bandwidth is met. 4049 * 4050 * The second requirement is that the request pattern of the application is 4051 * isochronous, i.e., that, after issuing a request or a batch of requests, 4052 * the application stops issuing new requests until all its pending requests 4053 * have been completed. After that, the application may issue a new batch, 4054 * and so on. 4055 * For this reason the next function is invoked to compute 4056 * soft_rt_next_start only for applications that meet this requirement, 4057 * whereas soft_rt_next_start is set to infinity for applications that do 4058 * not. 4059 * 4060 * Unfortunately, even a greedy (i.e., I/O-bound) application may 4061 * happen to meet, occasionally or systematically, both the above 4062 * bandwidth and isochrony requirements. This may happen at least in 4063 * the following circumstances. First, if the CPU load is high. The 4064 * application may stop issuing requests while the CPUs are busy 4065 * serving other processes, then restart, then stop again for a while, 4066 * and so on. The other circumstances are related to the storage 4067 * device: the storage device is highly loaded or reaches a low-enough 4068 * throughput with the I/O of the application (e.g., because the I/O 4069 * is random and/or the device is slow). In all these cases, the 4070 * I/O of the application may be simply slowed down enough to meet 4071 * the bandwidth and isochrony requirements. To reduce the probability 4072 * that greedy applications are deemed as soft real-time in these 4073 * corner cases, a further rule is used in the computation of 4074 * soft_rt_next_start: the return value of this function is forced to 4075 * be higher than the maximum between the following two quantities. 4076 * 4077 * (a) Current time plus: (1) the maximum time for which the arrival 4078 * of a request is waited for when a sync queue becomes idle, 4079 * namely bfqd->bfq_slice_idle, and (2) a few extra jiffies. We 4080 * postpone for a moment the reason for adding a few extra 4081 * jiffies; we get back to it after next item (b). Lower-bounding 4082 * the return value of this function with the current time plus 4083 * bfqd->bfq_slice_idle tends to filter out greedy applications, 4084 * because the latter issue their next request as soon as possible 4085 * after the last one has been completed. In contrast, a soft 4086 * real-time application spends some time processing data, after a 4087 * batch of its requests has been completed. 4088 * 4089 * (b) Current value of bfqq->soft_rt_next_start. As pointed out 4090 * above, greedy applications may happen to meet both the 4091 * bandwidth and isochrony requirements under heavy CPU or 4092 * storage-device load. In more detail, in these scenarios, these 4093 * applications happen, only for limited time periods, to do I/O 4094 * slowly enough to meet all the requirements described so far, 4095 * including the filtering in above item (a). These slow-speed 4096 * time intervals are usually interspersed between other time 4097 * intervals during which these applications do I/O at a very high 4098 * speed. Fortunately, exactly because of the high speed of the 4099 * I/O in the high-speed intervals, the values returned by this 4100 * function happen to be so high, near the end of any such 4101 * high-speed interval, to be likely to fall *after* the end of 4102 * the low-speed time interval that follows. These high values are 4103 * stored in bfqq->soft_rt_next_start after each invocation of 4104 * this function. As a consequence, if the last value of 4105 * bfqq->soft_rt_next_start is constantly used to lower-bound the 4106 * next value that this function may return, then, from the very 4107 * beginning of a low-speed interval, bfqq->soft_rt_next_start is 4108 * likely to be constantly kept so high that any I/O request 4109 * issued during the low-speed interval is considered as arriving 4110 * to soon for the application to be deemed as soft 4111 * real-time. Then, in the high-speed interval that follows, the 4112 * application will not be deemed as soft real-time, just because 4113 * it will do I/O at a high speed. And so on. 4114 * 4115 * Getting back to the filtering in item (a), in the following two 4116 * cases this filtering might be easily passed by a greedy 4117 * application, if the reference quantity was just 4118 * bfqd->bfq_slice_idle: 4119 * 1) HZ is so low that the duration of a jiffy is comparable to or 4120 * higher than bfqd->bfq_slice_idle. This happens, e.g., on slow 4121 * devices with HZ=100. The time granularity may be so coarse 4122 * that the approximation, in jiffies, of bfqd->bfq_slice_idle 4123 * is rather lower than the exact value. 4124 * 2) jiffies, instead of increasing at a constant rate, may stop increasing 4125 * for a while, then suddenly 'jump' by several units to recover the lost 4126 * increments. This seems to happen, e.g., inside virtual machines. 4127 * To address this issue, in the filtering in (a) we do not use as a 4128 * reference time interval just bfqd->bfq_slice_idle, but 4129 * bfqd->bfq_slice_idle plus a few jiffies. In particular, we add the 4130 * minimum number of jiffies for which the filter seems to be quite 4131 * precise also in embedded systems and KVM/QEMU virtual machines. 4132 */ 4133static unsigned long bfq_bfqq_softrt_next_start(struct bfq_data *bfqd, 4134 struct bfq_queue *bfqq) 4135{ 4136 return max3(bfqq->soft_rt_next_start, 4137 bfqq->last_idle_bklogged + 4138 HZ * bfqq->service_from_backlogged / 4139 bfqd->bfq_wr_max_softrt_rate, 4140 jiffies + nsecs_to_jiffies(bfqq->bfqd->bfq_slice_idle) + 4); 4141} 4142 4143/** 4144 * bfq_bfqq_expire - expire a queue. 4145 * @bfqd: device owning the queue. 4146 * @bfqq: the queue to expire. 4147 * @compensate: if true, compensate for the time spent idling. 4148 * @reason: the reason causing the expiration. 4149 * 4150 * If the process associated with bfqq does slow I/O (e.g., because it 4151 * issues random requests), we charge bfqq with the time it has been 4152 * in service instead of the service it has received (see 4153 * bfq_bfqq_charge_time for details on how this goal is achieved). As 4154 * a consequence, bfqq will typically get higher timestamps upon 4155 * reactivation, and hence it will be rescheduled as if it had 4156 * received more service than what it has actually received. In the 4157 * end, bfqq receives less service in proportion to how slowly its 4158 * associated process consumes its budgets (and hence how seriously it 4159 * tends to lower the throughput). In addition, this time-charging 4160 * strategy guarantees time fairness among slow processes. In 4161 * contrast, if the process associated with bfqq is not slow, we 4162 * charge bfqq exactly with the service it has received. 4163 * 4164 * Charging time to the first type of queues and the exact service to 4165 * the other has the effect of using the WF2Q+ policy to schedule the 4166 * former on a timeslice basis, without violating service domain 4167 * guarantees among the latter. 4168 */ 4169void bfq_bfqq_expire(struct bfq_data *bfqd, 4170 struct bfq_queue *bfqq, 4171 bool compensate, 4172 enum bfqq_expiration reason) 4173{ 4174 bool slow; 4175 unsigned long delta = 0; 4176 struct bfq_entity *entity = &bfqq->entity; 4177 4178 /* 4179 * Check whether the process is slow (see bfq_bfqq_is_slow). 4180 */ 4181 slow = bfq_bfqq_is_slow(bfqd, bfqq, compensate, reason, &delta); 4182 4183 /* 4184 * As above explained, charge slow (typically seeky) and 4185 * timed-out queues with the time and not the service 4186 * received, to favor sequential workloads. 4187 * 4188 * Processes doing I/O in the slower disk zones will tend to 4189 * be slow(er) even if not seeky. Therefore, since the 4190 * estimated peak rate is actually an average over the disk 4191 * surface, these processes may timeout just for bad luck. To 4192 * avoid punishing them, do not charge time to processes that 4193 * succeeded in consuming at least 2/3 of their budget. This 4194 * allows BFQ to preserve enough elasticity to still perform 4195 * bandwidth, and not time, distribution with little unlucky 4196 * or quasi-sequential processes. 4197 */ 4198 if (bfqq->wr_coeff == 1 && 4199 (slow || 4200 (reason == BFQQE_BUDGET_TIMEOUT && 4201 bfq_bfqq_budget_left(bfqq) >= entity->budget / 3))) 4202 bfq_bfqq_charge_time(bfqd, bfqq, delta); 4203 4204 if (bfqd->low_latency && bfqq->wr_coeff == 1) 4205 bfqq->last_wr_start_finish = jiffies; 4206 4207 if (bfqd->low_latency && bfqd->bfq_wr_max_softrt_rate > 0 && 4208 RB_EMPTY_ROOT(&bfqq->sort_list)) { 4209 /* 4210 * If we get here, and there are no outstanding 4211 * requests, then the request pattern is isochronous 4212 * (see the comments on the function 4213 * bfq_bfqq_softrt_next_start()). Therefore we can 4214 * compute soft_rt_next_start. 4215 * 4216 * If, instead, the queue still has outstanding 4217 * requests, then we have to wait for the completion 4218 * of all the outstanding requests to discover whether 4219 * the request pattern is actually isochronous. 4220 */ 4221 if (bfqq->dispatched == 0) 4222 bfqq->soft_rt_next_start = 4223 bfq_bfqq_softrt_next_start(bfqd, bfqq); 4224 else if (bfqq->dispatched > 0) { 4225 /* 4226 * Schedule an update of soft_rt_next_start to when 4227 * the task may be discovered to be isochronous. 4228 */ 4229 bfq_mark_bfqq_softrt_update(bfqq); 4230 } 4231 } 4232 4233 bfq_log_bfqq(bfqd, bfqq, 4234 "expire (%d, slow %d, num_disp %d, short_ttime %d)", reason, 4235 slow, bfqq->dispatched, bfq_bfqq_has_short_ttime(bfqq)); 4236 4237 /* 4238 * bfqq expired, so no total service time needs to be computed 4239 * any longer: reset state machine for measuring total service 4240 * times. 4241 */ 4242 bfqd->rqs_injected = bfqd->wait_dispatch = false; 4243 bfqd->waited_rq = NULL; 4244 4245 /* 4246 * Increase, decrease or leave budget unchanged according to 4247 * reason. 4248 */ 4249 __bfq_bfqq_recalc_budget(bfqd, bfqq, reason); 4250 if (__bfq_bfqq_expire(bfqd, bfqq, reason)) 4251 /* bfqq is gone, no more actions on it */ 4252 return; 4253 4254 /* mark bfqq as waiting a request only if a bic still points to it */ 4255 if (!bfq_bfqq_busy(bfqq) && 4256 reason != BFQQE_BUDGET_TIMEOUT && 4257 reason != BFQQE_BUDGET_EXHAUSTED) { 4258 bfq_mark_bfqq_non_blocking_wait_rq(bfqq); 4259 /* 4260 * Not setting service to 0, because, if the next rq 4261 * arrives in time, the queue will go on receiving 4262 * service with this same budget (as if it never expired) 4263 */ 4264 } else 4265 entity->service = 0; 4266 4267 /* 4268 * Reset the received-service counter for every parent entity. 4269 * Differently from what happens with bfqq->entity.service, 4270 * the resetting of this counter never needs to be postponed 4271 * for parent entities. In fact, in case bfqq may have a 4272 * chance to go on being served using the last, partially 4273 * consumed budget, bfqq->entity.service needs to be kept, 4274 * because if bfqq then actually goes on being served using 4275 * the same budget, the last value of bfqq->entity.service is 4276 * needed to properly decrement bfqq->entity.budget by the 4277 * portion already consumed. In contrast, it is not necessary 4278 * to keep entity->service for parent entities too, because 4279 * the bubble up of the new value of bfqq->entity.budget will 4280 * make sure that the budgets of parent entities are correct, 4281 * even in case bfqq and thus parent entities go on receiving 4282 * service with the same budget. 4283 */ 4284 entity = entity->parent; 4285 for_each_entity(entity) 4286 entity->service = 0; 4287} 4288 4289/* 4290 * Budget timeout is not implemented through a dedicated timer, but 4291 * just checked on request arrivals and completions, as well as on 4292 * idle timer expirations. 4293 */ 4294static bool bfq_bfqq_budget_timeout(struct bfq_queue *bfqq) 4295{ 4296 return time_is_before_eq_jiffies(bfqq->budget_timeout); 4297} 4298 4299/* 4300 * If we expire a queue that is actively waiting (i.e., with the 4301 * device idled) for the arrival of a new request, then we may incur 4302 * the timestamp misalignment problem described in the body of the 4303 * function __bfq_activate_entity. Hence we return true only if this 4304 * condition does not hold, or if the queue is slow enough to deserve 4305 * only to be kicked off for preserving a high throughput. 4306 */ 4307static bool bfq_may_expire_for_budg_timeout(struct bfq_queue *bfqq) 4308{ 4309 bfq_log_bfqq(bfqq->bfqd, bfqq, 4310 "may_budget_timeout: wait_request %d left %d timeout %d", 4311 bfq_bfqq_wait_request(bfqq), 4312 bfq_bfqq_budget_left(bfqq) >= bfqq->entity.budget / 3, 4313 bfq_bfqq_budget_timeout(bfqq)); 4314 4315 return (!bfq_bfqq_wait_request(bfqq) || 4316 bfq_bfqq_budget_left(bfqq) >= bfqq->entity.budget / 3) 4317 && 4318 bfq_bfqq_budget_timeout(bfqq); 4319} 4320 4321static bool idling_boosts_thr_without_issues(struct bfq_data *bfqd, 4322 struct bfq_queue *bfqq) 4323{ 4324 bool rot_without_queueing = 4325 !blk_queue_nonrot(bfqd->queue) && !bfqd->hw_tag, 4326 bfqq_sequential_and_IO_bound, 4327 idling_boosts_thr; 4328 4329 /* No point in idling for bfqq if it won't get requests any longer */ 4330 if (unlikely(!bfqq_process_refs(bfqq))) 4331 return false; 4332 4333 bfqq_sequential_and_IO_bound = !BFQQ_SEEKY(bfqq) && 4334 bfq_bfqq_IO_bound(bfqq) && bfq_bfqq_has_short_ttime(bfqq); 4335 4336 /* 4337 * The next variable takes into account the cases where idling 4338 * boosts the throughput. 4339 * 4340 * The value of the variable is computed considering, first, that 4341 * idling is virtually always beneficial for the throughput if: 4342 * (a) the device is not NCQ-capable and rotational, or 4343 * (b) regardless of the presence of NCQ, the device is rotational and 4344 * the request pattern for bfqq is I/O-bound and sequential, or 4345 * (c) regardless of whether it is rotational, the device is 4346 * not NCQ-capable and the request pattern for bfqq is 4347 * I/O-bound and sequential. 4348 * 4349 * Secondly, and in contrast to the above item (b), idling an 4350 * NCQ-capable flash-based device would not boost the 4351 * throughput even with sequential I/O; rather it would lower 4352 * the throughput in proportion to how fast the device 4353 * is. Accordingly, the next variable is true if any of the 4354 * above conditions (a), (b) or (c) is true, and, in 4355 * particular, happens to be false if bfqd is an NCQ-capable 4356 * flash-based device. 4357 */ 4358 idling_boosts_thr = rot_without_queueing || 4359 ((!blk_queue_nonrot(bfqd->queue) || !bfqd->hw_tag) && 4360 bfqq_sequential_and_IO_bound); 4361 4362 /* 4363 * The return value of this function is equal to that of 4364 * idling_boosts_thr, unless a special case holds. In this 4365 * special case, described below, idling may cause problems to 4366 * weight-raised queues. 4367 * 4368 * When the request pool is saturated (e.g., in the presence 4369 * of write hogs), if the processes associated with 4370 * non-weight-raised queues ask for requests at a lower rate, 4371 * then processes associated with weight-raised queues have a 4372 * higher probability to get a request from the pool 4373 * immediately (or at least soon) when they need one. Thus 4374 * they have a higher probability to actually get a fraction 4375 * of the device throughput proportional to their high 4376 * weight. This is especially true with NCQ-capable drives, 4377 * which enqueue several requests in advance, and further 4378 * reorder internally-queued requests. 4379 * 4380 * For this reason, we force to false the return value if 4381 * there are weight-raised busy queues. In this case, and if 4382 * bfqq is not weight-raised, this guarantees that the device 4383 * is not idled for bfqq (if, instead, bfqq is weight-raised, 4384 * then idling will be guaranteed by another variable, see 4385 * below). Combined with the timestamping rules of BFQ (see 4386 * [1] for details), this behavior causes bfqq, and hence any 4387 * sync non-weight-raised queue, to get a lower number of 4388 * requests served, and thus to ask for a lower number of 4389 * requests from the request pool, before the busy 4390 * weight-raised queues get served again. This often mitigates 4391 * starvation problems in the presence of heavy write 4392 * workloads and NCQ, thereby guaranteeing a higher 4393 * application and system responsiveness in these hostile 4394 * scenarios. 4395 */ 4396 return idling_boosts_thr && 4397 bfqd->wr_busy_queues == 0; 4398} 4399 4400/* 4401 * For a queue that becomes empty, device idling is allowed only if 4402 * this function returns true for that queue. As a consequence, since 4403 * device idling plays a critical role for both throughput boosting 4404 * and service guarantees, the return value of this function plays a 4405 * critical role as well. 4406 * 4407 * In a nutshell, this function returns true only if idling is 4408 * beneficial for throughput or, even if detrimental for throughput, 4409 * idling is however necessary to preserve service guarantees (low 4410 * latency, desired throughput distribution, ...). In particular, on 4411 * NCQ-capable devices, this function tries to return false, so as to 4412 * help keep the drives' internal queues full, whenever this helps the 4413 * device boost the throughput without causing any service-guarantee 4414 * issue. 4415 * 4416 * Most of the issues taken into account to get the return value of 4417 * this function are not trivial. We discuss these issues in the two 4418 * functions providing the main pieces of information needed by this 4419 * function. 4420 */ 4421static bool bfq_better_to_idle(struct bfq_queue *bfqq) 4422{ 4423 struct bfq_data *bfqd = bfqq->bfqd; 4424 bool idling_boosts_thr_with_no_issue, idling_needed_for_service_guar; 4425 4426 /* No point in idling for bfqq if it won't get requests any longer */ 4427 if (unlikely(!bfqq_process_refs(bfqq))) 4428 return false; 4429 4430 if (unlikely(bfqd->strict_guarantees)) 4431 return true; 4432 4433 /* 4434 * Idling is performed only if slice_idle > 0. In addition, we 4435 * do not idle if 4436 * (a) bfqq is async 4437 * (b) bfqq is in the idle io prio class: in this case we do 4438 * not idle because we want to minimize the bandwidth that 4439 * queues in this class can steal to higher-priority queues 4440 */ 4441 if (bfqd->bfq_slice_idle == 0 || !bfq_bfqq_sync(bfqq) || 4442 bfq_class_idle(bfqq)) 4443 return false; 4444 4445 idling_boosts_thr_with_no_issue = 4446 idling_boosts_thr_without_issues(bfqd, bfqq); 4447 4448 idling_needed_for_service_guar = 4449 idling_needed_for_service_guarantees(bfqd, bfqq); 4450 4451 /* 4452 * We have now the two components we need to compute the 4453 * return value of the function, which is true only if idling 4454 * either boosts the throughput (without issues), or is 4455 * necessary to preserve service guarantees. 4456 */ 4457 return idling_boosts_thr_with_no_issue || 4458 idling_needed_for_service_guar; 4459} 4460 4461/* 4462 * If the in-service queue is empty but the function bfq_better_to_idle 4463 * returns true, then: 4464 * 1) the queue must remain in service and cannot be expired, and 4465 * 2) the device must be idled to wait for the possible arrival of a new 4466 * request for the queue. 4467 * See the comments on the function bfq_better_to_idle for the reasons 4468 * why performing device idling is the best choice to boost the throughput 4469 * and preserve service guarantees when bfq_better_to_idle itself 4470 * returns true. 4471 */ 4472static bool bfq_bfqq_must_idle(struct bfq_queue *bfqq) 4473{ 4474 return RB_EMPTY_ROOT(&bfqq->sort_list) && bfq_better_to_idle(bfqq); 4475} 4476 4477/* 4478 * This function chooses the queue from which to pick the next extra 4479 * I/O request to inject, if it finds a compatible queue. See the 4480 * comments on bfq_update_inject_limit() for details on the injection 4481 * mechanism, and for the definitions of the quantities mentioned 4482 * below. 4483 */ 4484static struct bfq_queue * 4485bfq_choose_bfqq_for_injection(struct bfq_data *bfqd) 4486{ 4487 struct bfq_queue *bfqq, *in_serv_bfqq = bfqd->in_service_queue; 4488 unsigned int limit = in_serv_bfqq->inject_limit; 4489 /* 4490 * If 4491 * - bfqq is not weight-raised and therefore does not carry 4492 * time-critical I/O, 4493 * or 4494 * - regardless of whether bfqq is weight-raised, bfqq has 4495 * however a long think time, during which it can absorb the 4496 * effect of an appropriate number of extra I/O requests 4497 * from other queues (see bfq_update_inject_limit for 4498 * details on the computation of this number); 4499 * then injection can be performed without restrictions. 4500 */ 4501 bool in_serv_always_inject = in_serv_bfqq->wr_coeff == 1 || 4502 !bfq_bfqq_has_short_ttime(in_serv_bfqq); 4503 4504 /* 4505 * If 4506 * - the baseline total service time could not be sampled yet, 4507 * so the inject limit happens to be still 0, and 4508 * - a lot of time has elapsed since the plugging of I/O 4509 * dispatching started, so drive speed is being wasted 4510 * significantly; 4511 * then temporarily raise inject limit to one request. 4512 */ 4513 if (limit == 0 && in_serv_bfqq->last_serv_time_ns == 0 && 4514 bfq_bfqq_wait_request(in_serv_bfqq) && 4515 time_is_before_eq_jiffies(bfqd->last_idling_start_jiffies + 4516 bfqd->bfq_slice_idle) 4517 ) 4518 limit = 1; 4519 4520 if (bfqd->rq_in_driver >= limit) 4521 return NULL; 4522 4523 /* 4524 * Linear search of the source queue for injection; but, with 4525 * a high probability, very few steps are needed to find a 4526 * candidate queue, i.e., a queue with enough budget left for 4527 * its next request. In fact: 4528 * - BFQ dynamically updates the budget of every queue so as 4529 * to accommodate the expected backlog of the queue; 4530 * - if a queue gets all its requests dispatched as injected 4531 * service, then the queue is removed from the active list 4532 * (and re-added only if it gets new requests, but then it 4533 * is assigned again enough budget for its new backlog). 4534 */ 4535 list_for_each_entry(bfqq, &bfqd->active_list, bfqq_list) 4536 if (!RB_EMPTY_ROOT(&bfqq->sort_list) && 4537 (in_serv_always_inject || bfqq->wr_coeff > 1) && 4538 bfq_serv_to_charge(bfqq->next_rq, bfqq) <= 4539 bfq_bfqq_budget_left(bfqq)) { 4540 /* 4541 * Allow for only one large in-flight request 4542 * on non-rotational devices, for the 4543 * following reason. On non-rotationl drives, 4544 * large requests take much longer than 4545 * smaller requests to be served. In addition, 4546 * the drive prefers to serve large requests 4547 * w.r.t. to small ones, if it can choose. So, 4548 * having more than one large requests queued 4549 * in the drive may easily make the next first 4550 * request of the in-service queue wait for so 4551 * long to break bfqq's service guarantees. On 4552 * the bright side, large requests let the 4553 * drive reach a very high throughput, even if 4554 * there is only one in-flight large request 4555 * at a time. 4556 */ 4557 if (blk_queue_nonrot(bfqd->queue) && 4558 blk_rq_sectors(bfqq->next_rq) >= 4559 BFQQ_SECT_THR_NONROT) 4560 limit = min_t(unsigned int, 1, limit); 4561 else 4562 limit = in_serv_bfqq->inject_limit; 4563 4564 if (bfqd->rq_in_driver < limit) { 4565 bfqd->rqs_injected = true; 4566 return bfqq; 4567 } 4568 } 4569 4570 return NULL; 4571} 4572 4573/* 4574 * Select a queue for service. If we have a current queue in service, 4575 * check whether to continue servicing it, or retrieve and set a new one. 4576 */ 4577static struct bfq_queue *bfq_select_queue(struct bfq_data *bfqd) 4578{ 4579 struct bfq_queue *bfqq; 4580 struct request *next_rq; 4581 enum bfqq_expiration reason = BFQQE_BUDGET_TIMEOUT; 4582 4583 bfqq = bfqd->in_service_queue; 4584 if (!bfqq) 4585 goto new_queue; 4586 4587 bfq_log_bfqq(bfqd, bfqq, "select_queue: already in-service queue"); 4588 4589 /* 4590 * Do not expire bfqq for budget timeout if bfqq may be about 4591 * to enjoy device idling. The reason why, in this case, we 4592 * prevent bfqq from expiring is the same as in the comments 4593 * on the case where bfq_bfqq_must_idle() returns true, in 4594 * bfq_completed_request(). 4595 */ 4596 if (bfq_may_expire_for_budg_timeout(bfqq) && 4597 !bfq_bfqq_must_idle(bfqq)) 4598 goto expire; 4599 4600check_queue: 4601 /* 4602 * This loop is rarely executed more than once. Even when it 4603 * happens, it is much more convenient to re-execute this loop 4604 * than to return NULL and trigger a new dispatch to get a 4605 * request served. 4606 */ 4607 next_rq = bfqq->next_rq; 4608 /* 4609 * If bfqq has requests queued and it has enough budget left to 4610 * serve them, keep the queue, otherwise expire it. 4611 */ 4612 if (next_rq) { 4613 if (bfq_serv_to_charge(next_rq, bfqq) > 4614 bfq_bfqq_budget_left(bfqq)) { 4615 /* 4616 * Expire the queue for budget exhaustion, 4617 * which makes sure that the next budget is 4618 * enough to serve the next request, even if 4619 * it comes from the fifo expired path. 4620 */ 4621 reason = BFQQE_BUDGET_EXHAUSTED; 4622 goto expire; 4623 } else { 4624 /* 4625 * The idle timer may be pending because we may 4626 * not disable disk idling even when a new request 4627 * arrives. 4628 */ 4629 if (bfq_bfqq_wait_request(bfqq)) { 4630 /* 4631 * If we get here: 1) at least a new request 4632 * has arrived but we have not disabled the 4633 * timer because the request was too small, 4634 * 2) then the block layer has unplugged 4635 * the device, causing the dispatch to be 4636 * invoked. 4637 * 4638 * Since the device is unplugged, now the 4639 * requests are probably large enough to 4640 * provide a reasonable throughput. 4641 * So we disable idling. 4642 */ 4643 bfq_clear_bfqq_wait_request(bfqq); 4644 hrtimer_try_to_cancel(&bfqd->idle_slice_timer); 4645 } 4646 goto keep_queue; 4647 } 4648 } 4649 4650 /* 4651 * No requests pending. However, if the in-service queue is idling 4652 * for a new request, or has requests waiting for a completion and 4653 * may idle after their completion, then keep it anyway. 4654 * 4655 * Yet, inject service from other queues if it boosts 4656 * throughput and is possible. 4657 */ 4658 if (bfq_bfqq_wait_request(bfqq) || 4659 (bfqq->dispatched != 0 && bfq_better_to_idle(bfqq))) { 4660 struct bfq_queue *async_bfqq = 4661 bfqq->bic && bfqq->bic->bfqq[0] && 4662 bfq_bfqq_busy(bfqq->bic->bfqq[0]) && 4663 bfqq->bic->bfqq[0]->next_rq ? 4664 bfqq->bic->bfqq[0] : NULL; 4665 struct bfq_queue *blocked_bfqq = 4666 !hlist_empty(&bfqq->woken_list) ? 4667 container_of(bfqq->woken_list.first, 4668 struct bfq_queue, 4669 woken_list_node) 4670 : NULL; 4671 4672 /* 4673 * The next four mutually-exclusive ifs decide 4674 * whether to try injection, and choose the queue to 4675 * pick an I/O request from. 4676 * 4677 * The first if checks whether the process associated 4678 * with bfqq has also async I/O pending. If so, it 4679 * injects such I/O unconditionally. Injecting async 4680 * I/O from the same process can cause no harm to the 4681 * process. On the contrary, it can only increase 4682 * bandwidth and reduce latency for the process. 4683 * 4684 * The second if checks whether there happens to be a 4685 * non-empty waker queue for bfqq, i.e., a queue whose 4686 * I/O needs to be completed for bfqq to receive new 4687 * I/O. This happens, e.g., if bfqq is associated with 4688 * a process that does some sync. A sync generates 4689 * extra blocking I/O, which must be completed before 4690 * the process associated with bfqq can go on with its 4691 * I/O. If the I/O of the waker queue is not served, 4692 * then bfqq remains empty, and no I/O is dispatched, 4693 * until the idle timeout fires for bfqq. This is 4694 * likely to result in lower bandwidth and higher 4695 * latencies for bfqq, and in a severe loss of total 4696 * throughput. The best action to take is therefore to 4697 * serve the waker queue as soon as possible. So do it 4698 * (without relying on the third alternative below for 4699 * eventually serving waker_bfqq's I/O; see the last 4700 * paragraph for further details). This systematic 4701 * injection of I/O from the waker queue does not 4702 * cause any delay to bfqq's I/O. On the contrary, 4703 * next bfqq's I/O is brought forward dramatically, 4704 * for it is not blocked for milliseconds. 4705 * 4706 * The third if checks whether there is a queue woken 4707 * by bfqq, and currently with pending I/O. Such a 4708 * woken queue does not steal bandwidth from bfqq, 4709 * because it remains soon without I/O if bfqq is not 4710 * served. So there is virtually no risk of loss of 4711 * bandwidth for bfqq if this woken queue has I/O 4712 * dispatched while bfqq is waiting for new I/O. 4713 * 4714 * The fourth if checks whether bfqq is a queue for 4715 * which it is better to avoid injection. It is so if 4716 * bfqq delivers more throughput when served without 4717 * any further I/O from other queues in the middle, or 4718 * if the service times of bfqq's I/O requests both 4719 * count more than overall throughput, and may be 4720 * easily increased by injection (this happens if bfqq 4721 * has a short think time). If none of these 4722 * conditions holds, then a candidate queue for 4723 * injection is looked for through 4724 * bfq_choose_bfqq_for_injection(). Note that the 4725 * latter may return NULL (for example if the inject 4726 * limit for bfqq is currently 0). 4727 * 4728 * NOTE: motivation for the second alternative 4729 * 4730 * Thanks to the way the inject limit is updated in 4731 * bfq_update_has_short_ttime(), it is rather likely 4732 * that, if I/O is being plugged for bfqq and the 4733 * waker queue has pending I/O requests that are 4734 * blocking bfqq's I/O, then the fourth alternative 4735 * above lets the waker queue get served before the 4736 * I/O-plugging timeout fires. So one may deem the 4737 * second alternative superfluous. It is not, because 4738 * the fourth alternative may be way less effective in 4739 * case of a synchronization. For two main 4740 * reasons. First, throughput may be low because the 4741 * inject limit may be too low to guarantee the same 4742 * amount of injected I/O, from the waker queue or 4743 * other queues, that the second alternative 4744 * guarantees (the second alternative unconditionally 4745 * injects a pending I/O request of the waker queue 4746 * for each bfq_dispatch_request()). Second, with the 4747 * fourth alternative, the duration of the plugging, 4748 * i.e., the time before bfqq finally receives new I/O, 4749 * may not be minimized, because the waker queue may 4750 * happen to be served only after other queues. 4751 */ 4752 if (async_bfqq && 4753 icq_to_bic(async_bfqq->next_rq->elv.icq) == bfqq->bic && 4754 bfq_serv_to_charge(async_bfqq->next_rq, async_bfqq) <= 4755 bfq_bfqq_budget_left(async_bfqq)) 4756 bfqq = bfqq->bic->bfqq[0]; 4757 else if (bfqq->waker_bfqq && 4758 bfq_bfqq_busy(bfqq->waker_bfqq) && 4759 bfqq->waker_bfqq->next_rq && 4760 bfq_serv_to_charge(bfqq->waker_bfqq->next_rq, 4761 bfqq->waker_bfqq) <= 4762 bfq_bfqq_budget_left(bfqq->waker_bfqq) 4763 ) 4764 bfqq = bfqq->waker_bfqq; 4765 else if (blocked_bfqq && 4766 bfq_bfqq_busy(blocked_bfqq) && 4767 blocked_bfqq->next_rq && 4768 bfq_serv_to_charge(blocked_bfqq->next_rq, 4769 blocked_bfqq) <= 4770 bfq_bfqq_budget_left(blocked_bfqq) 4771 ) 4772 bfqq = blocked_bfqq; 4773 else if (!idling_boosts_thr_without_issues(bfqd, bfqq) && 4774 (bfqq->wr_coeff == 1 || bfqd->wr_busy_queues > 1 || 4775 !bfq_bfqq_has_short_ttime(bfqq))) 4776 bfqq = bfq_choose_bfqq_for_injection(bfqd); 4777 else 4778 bfqq = NULL; 4779 4780 goto keep_queue; 4781 } 4782 4783 reason = BFQQE_NO_MORE_REQUESTS; 4784expire: 4785 bfq_bfqq_expire(bfqd, bfqq, false, reason); 4786new_queue: 4787 bfqq = bfq_set_in_service_queue(bfqd); 4788 if (bfqq) { 4789 bfq_log_bfqq(bfqd, bfqq, "select_queue: checking new queue"); 4790 goto check_queue; 4791 } 4792keep_queue: 4793 if (bfqq) 4794 bfq_log_bfqq(bfqd, bfqq, "select_queue: returned this queue"); 4795 else 4796 bfq_log(bfqd, "select_queue: no queue returned"); 4797 4798 return bfqq; 4799} 4800 4801static void bfq_update_wr_data(struct bfq_data *bfqd, struct bfq_queue *bfqq) 4802{ 4803 struct bfq_entity *entity = &bfqq->entity; 4804 4805 if (bfqq->wr_coeff > 1) { /* queue is being weight-raised */ 4806 bfq_log_bfqq(bfqd, bfqq, 4807 "raising period dur %u/%u msec, old coeff %u, w %d(%d)", 4808 jiffies_to_msecs(jiffies - bfqq->last_wr_start_finish), 4809 jiffies_to_msecs(bfqq->wr_cur_max_time), 4810 bfqq->wr_coeff, 4811 bfqq->entity.weight, bfqq->entity.orig_weight); 4812 4813 if (entity->prio_changed) 4814 bfq_log_bfqq(bfqd, bfqq, "WARN: pending prio change"); 4815 4816 /* 4817 * If the queue was activated in a burst, or too much 4818 * time has elapsed from the beginning of this 4819 * weight-raising period, then end weight raising. 4820 */ 4821 if (bfq_bfqq_in_large_burst(bfqq)) 4822 bfq_bfqq_end_wr(bfqq); 4823 else if (time_is_before_jiffies(bfqq->last_wr_start_finish + 4824 bfqq->wr_cur_max_time)) { 4825 if (bfqq->wr_cur_max_time != bfqd->bfq_wr_rt_max_time || 4826 time_is_before_jiffies(bfqq->wr_start_at_switch_to_srt + 4827 bfq_wr_duration(bfqd))) { 4828 /* 4829 * Either in interactive weight 4830 * raising, or in soft_rt weight 4831 * raising with the 4832 * interactive-weight-raising period 4833 * elapsed (so no switch back to 4834 * interactive weight raising). 4835 */ 4836 bfq_bfqq_end_wr(bfqq); 4837 } else { /* 4838 * soft_rt finishing while still in 4839 * interactive period, switch back to 4840 * interactive weight raising 4841 */ 4842 switch_back_to_interactive_wr(bfqq, bfqd); 4843 bfqq->entity.prio_changed = 1; 4844 } 4845 } 4846 if (bfqq->wr_coeff > 1 && 4847 bfqq->wr_cur_max_time != bfqd->bfq_wr_rt_max_time && 4848 bfqq->service_from_wr > max_service_from_wr) { 4849 /* see comments on max_service_from_wr */ 4850 bfq_bfqq_end_wr(bfqq); 4851 } 4852 } 4853 /* 4854 * To improve latency (for this or other queues), immediately 4855 * update weight both if it must be raised and if it must be 4856 * lowered. Since, entity may be on some active tree here, and 4857 * might have a pending change of its ioprio class, invoke 4858 * next function with the last parameter unset (see the 4859 * comments on the function). 4860 */ 4861 if ((entity->weight > entity->orig_weight) != (bfqq->wr_coeff > 1)) 4862 __bfq_entity_update_weight_prio(bfq_entity_service_tree(entity), 4863 entity, false); 4864} 4865 4866/* 4867 * Dispatch next request from bfqq. 4868 */ 4869static struct request *bfq_dispatch_rq_from_bfqq(struct bfq_data *bfqd, 4870 struct bfq_queue *bfqq) 4871{ 4872 struct request *rq = bfqq->next_rq; 4873 unsigned long service_to_charge; 4874 4875 service_to_charge = bfq_serv_to_charge(rq, bfqq); 4876 4877 bfq_bfqq_served(bfqq, service_to_charge); 4878 4879 if (bfqq == bfqd->in_service_queue && bfqd->wait_dispatch) { 4880 bfqd->wait_dispatch = false; 4881 bfqd->waited_rq = rq; 4882 } 4883 4884 bfq_dispatch_remove(bfqd->queue, rq); 4885 4886 if (bfqq != bfqd->in_service_queue) 4887 goto return_rq; 4888 4889 /* 4890 * If weight raising has to terminate for bfqq, then next 4891 * function causes an immediate update of bfqq's weight, 4892 * without waiting for next activation. As a consequence, on 4893 * expiration, bfqq will be timestamped as if has never been 4894 * weight-raised during this service slot, even if it has 4895 * received part or even most of the service as a 4896 * weight-raised queue. This inflates bfqq's timestamps, which 4897 * is beneficial, as bfqq is then more willing to leave the 4898 * device immediately to possible other weight-raised queues. 4899 */ 4900 bfq_update_wr_data(bfqd, bfqq); 4901 4902 /* 4903 * Expire bfqq, pretending that its budget expired, if bfqq 4904 * belongs to CLASS_IDLE and other queues are waiting for 4905 * service. 4906 */ 4907 if (!(bfq_tot_busy_queues(bfqd) > 1 && bfq_class_idle(bfqq))) 4908 goto return_rq; 4909 4910 bfq_bfqq_expire(bfqd, bfqq, false, BFQQE_BUDGET_EXHAUSTED); 4911 4912return_rq: 4913 return rq; 4914} 4915 4916static bool bfq_has_work(struct blk_mq_hw_ctx *hctx) 4917{ 4918 struct bfq_data *bfqd = hctx->queue->elevator->elevator_data; 4919 4920 /* 4921 * Avoiding lock: a race on bfqd->busy_queues should cause at 4922 * most a call to dispatch for nothing 4923 */ 4924 return !list_empty_careful(&bfqd->dispatch) || 4925 bfq_tot_busy_queues(bfqd) > 0; 4926} 4927 4928static struct request *__bfq_dispatch_request(struct blk_mq_hw_ctx *hctx) 4929{ 4930 struct bfq_data *bfqd = hctx->queue->elevator->elevator_data; 4931 struct request *rq = NULL; 4932 struct bfq_queue *bfqq = NULL; 4933 4934 if (!list_empty(&bfqd->dispatch)) { 4935 rq = list_first_entry(&bfqd->dispatch, struct request, 4936 queuelist); 4937 list_del_init(&rq->queuelist); 4938 4939 bfqq = RQ_BFQQ(rq); 4940 4941 if (bfqq) { 4942 /* 4943 * Increment counters here, because this 4944 * dispatch does not follow the standard 4945 * dispatch flow (where counters are 4946 * incremented) 4947 */ 4948 bfqq->dispatched++; 4949 4950 goto inc_in_driver_start_rq; 4951 } 4952 4953 /* 4954 * We exploit the bfq_finish_requeue_request hook to 4955 * decrement rq_in_driver, but 4956 * bfq_finish_requeue_request will not be invoked on 4957 * this request. So, to avoid unbalance, just start 4958 * this request, without incrementing rq_in_driver. As 4959 * a negative consequence, rq_in_driver is deceptively 4960 * lower than it should be while this request is in 4961 * service. This may cause bfq_schedule_dispatch to be 4962 * invoked uselessly. 4963 * 4964 * As for implementing an exact solution, the 4965 * bfq_finish_requeue_request hook, if defined, is 4966 * probably invoked also on this request. So, by 4967 * exploiting this hook, we could 1) increment 4968 * rq_in_driver here, and 2) decrement it in 4969 * bfq_finish_requeue_request. Such a solution would 4970 * let the value of the counter be always accurate, 4971 * but it would entail using an extra interface 4972 * function. This cost seems higher than the benefit, 4973 * being the frequency of non-elevator-private 4974 * requests very low. 4975 */ 4976 goto start_rq; 4977 } 4978 4979 bfq_log(bfqd, "dispatch requests: %d busy queues", 4980 bfq_tot_busy_queues(bfqd)); 4981 4982 if (bfq_tot_busy_queues(bfqd) == 0) 4983 goto exit; 4984 4985 /* 4986 * Force device to serve one request at a time if 4987 * strict_guarantees is true. Forcing this service scheme is 4988 * currently the ONLY way to guarantee that the request 4989 * service order enforced by the scheduler is respected by a 4990 * queueing device. Otherwise the device is free even to make 4991 * some unlucky request wait for as long as the device 4992 * wishes. 4993 * 4994 * Of course, serving one request at at time may cause loss of 4995 * throughput. 4996 */ 4997 if (bfqd->strict_guarantees && bfqd->rq_in_driver > 0) 4998 goto exit; 4999 5000 bfqq = bfq_select_queue(bfqd);
5001 if (!bfqq) 5002 goto exit; 5003 5004 rq = bfq_dispatch_rq_from_bfqq(bfqd, bfqq); 5005 5006 if (rq) { 5007inc_in_driver_start_rq: 5008 bfqd->rq_in_driver++; 5009start_rq: 5010 rq->rq_flags |= RQF_STARTED; 5011 } 5012exit: 5013 return rq; 5014} 5015 5016#ifdef CONFIG_BFQ_CGROUP_DEBUG 5017static void bfq_update_dispatch_stats(struct request_queue *q, 5018 struct request *rq, 5019 struct bfq_queue *in_serv_queue, 5020 bool idle_timer_disabled) 5021{ 5022 struct bfq_queue *bfqq = rq ? RQ_BFQQ(rq) : NULL; 5023 5024 if (!idle_timer_disabled && !bfqq) 5025 return; 5026 5027 /* 5028 * rq and bfqq are guaranteed to exist until this function 5029 * ends, for the following reasons. First, rq can be 5030 * dispatched to the device, and then can be completed and 5031 * freed, only after this function ends. Second, rq cannot be 5032 * merged (and thus freed because of a merge) any longer, 5033 * because it has already started. Thus rq cannot be freed 5034 * before this function ends, and, since rq has a reference to 5035 * bfqq, the same guarantee holds for bfqq too. 5036 * 5037 * In addition, the following queue lock guarantees that 5038 * bfqq_group(bfqq) exists as well. 5039 */ 5040 spin_lock_irq(&q->queue_lock); 5041 if (idle_timer_disabled) 5042 /* 5043 * Since the idle timer has been disabled, 5044 * in_serv_queue contained some request when 5045 * __bfq_dispatch_request was invoked above, which 5046 * implies that rq was picked exactly from 5047 * in_serv_queue. Thus in_serv_queue == bfqq, and is 5048 * therefore guaranteed to exist because of the above 5049 * arguments. 5050 */ 5051 bfqg_stats_update_idle_time(bfqq_group(in_serv_queue)); 5052 if (bfqq) { 5053 struct bfq_group *bfqg = bfqq_group(bfqq); 5054 5055 bfqg_stats_update_avg_queue_size(bfqg); 5056 bfqg_stats_set_start_empty_time(bfqg); 5057 bfqg_stats_update_io_remove(bfqg, rq->cmd_flags); 5058 } 5059 spin_unlock_irq(&q->queue_lock); 5060} 5061#else 5062static inline void bfq_update_dispatch_stats(struct request_queue *q, 5063 struct request *rq, 5064 struct bfq_queue *in_serv_queue, 5065 bool idle_timer_disabled) {} 5066#endif /* CONFIG_BFQ_CGROUP_DEBUG */ 5067 5068static struct request *bfq_dispatch_request(struct blk_mq_hw_ctx *hctx) 5069{ 5070 struct bfq_data *bfqd = hctx->queue->elevator->elevator_data; 5071 struct request *rq; 5072 struct bfq_queue *in_serv_queue; 5073 bool waiting_rq, idle_timer_disabled; 5074 5075 spin_lock_irq(&bfqd->lock); 5076 5077 in_serv_queue = bfqd->in_service_queue; 5078 waiting_rq = in_serv_queue && bfq_bfqq_wait_request(in_serv_queue); 5079 5080 rq = __bfq_dispatch_request(hctx); 5081 5082 idle_timer_disabled = 5083 waiting_rq && !bfq_bfqq_wait_request(in_serv_queue); 5084 5085 spin_unlock_irq(&bfqd->lock); 5086 5087 bfq_update_dispatch_stats(hctx->queue, rq, in_serv_queue, 5088 idle_timer_disabled); 5089 5090 return rq; 5091} 5092 5093/* 5094 * Task holds one reference to the queue, dropped when task exits. Each rq 5095 * in-flight on this queue also holds a reference, dropped when rq is freed. 5096 * 5097 * Scheduler lock must be held here. Recall not to use bfqq after calling 5098 * this function on it. 5099 */ 5100void bfq_put_queue(struct bfq_queue *bfqq) 5101{ 5102 struct bfq_queue *item; 5103 struct hlist_node *n; 5104 struct bfq_group *bfqg = bfqq_group(bfqq); 5105 5106 if (bfqq->bfqd) 5107 bfq_log_bfqq(bfqq->bfqd, bfqq, "put_queue: %p %d", 5108 bfqq, bfqq->ref); 5109 5110 bfqq->ref--; 5111 if (bfqq->ref) 5112 return; 5113 5114 if (!hlist_unhashed(&bfqq->burst_list_node)) { 5115 hlist_del_init(&bfqq->burst_list_node); 5116 /* 5117 * Decrement also burst size after the removal, if the 5118 * process associated with bfqq is exiting, and thus 5119 * does not contribute to the burst any longer. This 5120 * decrement helps filter out false positives of large 5121 * bursts, when some short-lived process (often due to 5122 * the execution of commands by some service) happens 5123 * to start and exit while a complex application is 5124 * starting, and thus spawning several processes that 5125 * do I/O (and that *must not* be treated as a large 5126 * burst, see comments on bfq_handle_burst). 5127 * 5128 * In particular, the decrement is performed only if: 5129 * 1) bfqq is not a merged queue, because, if it is, 5130 * then this free of bfqq is not triggered by the exit 5131 * of the process bfqq is associated with, but exactly 5132 * by the fact that bfqq has just been merged. 5133 * 2) burst_size is greater than 0, to handle 5134 * unbalanced decrements. Unbalanced decrements may 5135 * happen in te following case: bfqq is inserted into 5136 * the current burst list--without incrementing 5137 * bust_size--because of a split, but the current 5138 * burst list is not the burst list bfqq belonged to 5139 * (see comments on the case of a split in 5140 * bfq_set_request). 5141 */ 5142 if (bfqq->bic && bfqq->bfqd->burst_size > 0) 5143 bfqq->bfqd->burst_size--; 5144 } 5145 5146 /* 5147 * bfqq does not exist any longer, so it cannot be woken by 5148 * any other queue, and cannot wake any other queue. Then bfqq 5149 * must be removed from the woken list of its possible waker 5150 * queue, and all queues in the woken list of bfqq must stop 5151 * having a waker queue. Strictly speaking, these updates 5152 * should be performed when bfqq remains with no I/O source 5153 * attached to it, which happens before bfqq gets freed. In 5154 * particular, this happens when the last process associated 5155 * with bfqq exits or gets associated with a different 5156 * queue. However, both events lead to bfqq being freed soon, 5157 * and dangling references would come out only after bfqq gets 5158 * freed. So these updates are done here, as a simple and safe 5159 * way to handle all cases. 5160 */ 5161 /* remove bfqq from woken list */ 5162 if (!hlist_unhashed(&bfqq->woken_list_node)) 5163 hlist_del_init(&bfqq->woken_list_node); 5164 5165 /* reset waker for all queues in woken list */ 5166 hlist_for_each_entry_safe(item, n, &bfqq->woken_list, 5167 woken_list_node) { 5168 item->waker_bfqq = NULL; 5169 hlist_del_init(&item->woken_list_node); 5170 } 5171 5172 if (bfqq->bfqd && bfqq->bfqd->last_completed_rq_bfqq == bfqq) 5173 bfqq->bfqd->last_completed_rq_bfqq = NULL; 5174 5175 kmem_cache_free(bfq_pool, bfqq); 5176 bfqg_and_blkg_put(bfqg); 5177} 5178 5179static void bfq_put_stable_ref(struct bfq_queue *bfqq) 5180{ 5181 bfqq->stable_ref--; 5182 bfq_put_queue(bfqq); 5183} 5184 5185static void bfq_put_cooperator(struct bfq_queue *bfqq) 5186{ 5187 struct bfq_queue *__bfqq, *next; 5188 5189 /* 5190 * If this queue was scheduled to merge with another queue, be 5191 * sure to drop the reference taken on that queue (and others in 5192 * the merge chain). See bfq_setup_merge and bfq_merge_bfqqs. 5193 */ 5194 __bfqq = bfqq->new_bfqq; 5195 while (__bfqq) { 5196 if (__bfqq == bfqq) 5197 break; 5198 next = __bfqq->new_bfqq; 5199 bfq_put_queue(__bfqq); 5200 __bfqq = next; 5201 } 5202} 5203 5204static void bfq_exit_bfqq(struct bfq_data *bfqd, struct bfq_queue *bfqq) 5205{ 5206 if (bfqq == bfqd->in_service_queue) { 5207 __bfq_bfqq_expire(bfqd, bfqq, BFQQE_BUDGET_TIMEOUT); 5208 bfq_schedule_dispatch(bfqd); 5209 } 5210 5211 bfq_log_bfqq(bfqd, bfqq, "exit_bfqq: %p, %d", bfqq, bfqq->ref); 5212 5213 bfq_put_cooperator(bfqq); 5214 5215 bfq_release_process_ref(bfqd, bfqq); 5216} 5217 5218static void bfq_exit_icq_bfqq(struct bfq_io_cq *bic, bool is_sync) 5219{ 5220 struct bfq_queue *bfqq = bic_to_bfqq(bic, is_sync); 5221 struct bfq_data *bfqd; 5222 5223 if (bfqq) 5224 bfqd = bfqq->bfqd; /* NULL if scheduler already exited */ 5225 5226 if (bfqq && bfqd) { 5227 unsigned long flags; 5228 5229 spin_lock_irqsave(&bfqd->lock, flags); 5230 bfq_exit_bfqq(bfqd, bfqq); 5231 bic_set_bfqq(bic, NULL, is_sync); 5232 spin_unlock_irqrestore(&bfqd->lock, flags); 5233 } 5234} 5235 5236static void bfq_exit_icq(struct io_cq *icq) 5237{ 5238 struct bfq_io_cq *bic = icq_to_bic(icq); 5239 5240 if (bic->stable_merge_bfqq) { 5241 struct bfq_data *bfqd = bic->stable_merge_bfqq->bfqd; 5242 5243 /* 5244 * bfqd is NULL if scheduler already exited, and in 5245 * that case this is the last time bfqq is accessed. 5246 */ 5247 if (bfqd) { 5248 unsigned long flags; 5249 5250 spin_lock_irqsave(&bfqd->lock, flags); 5251 bfq_put_stable_ref(bic->stable_merge_bfqq); 5252 spin_unlock_irqrestore(&bfqd->lock, flags); 5253 } else { 5254 bfq_put_stable_ref(bic->stable_merge_bfqq); 5255 } 5256 } 5257 5258 bfq_exit_icq_bfqq(bic, true); 5259 bfq_exit_icq_bfqq(bic, false); 5260} 5261 5262/* 5263 * Update the entity prio values; note that the new values will not 5264 * be used until the next (re)activation. 5265 */ 5266static void 5267bfq_set_next_ioprio_data(struct bfq_queue *bfqq, struct bfq_io_cq *bic) 5268{ 5269 struct task_struct *tsk = current; 5270 int ioprio_class; 5271 struct bfq_data *bfqd = bfqq->bfqd; 5272 5273 if (!bfqd) 5274 return; 5275 5276 ioprio_class = IOPRIO_PRIO_CLASS(bic->ioprio); 5277 switch (ioprio_class) { 5278 default: 5279 pr_err("bdi %s: bfq: bad prio class %d\n", 5280 bdi_dev_name(bfqq->bfqd->queue->backing_dev_info), 5281 ioprio_class); 5282 /* fall through */ 5283 case IOPRIO_CLASS_NONE: 5284 /* 5285 * No prio set, inherit CPU scheduling settings. 5286 */ 5287 bfqq->new_ioprio = task_nice_ioprio(tsk); 5288 bfqq->new_ioprio_class = task_nice_ioclass(tsk); 5289 break; 5290 case IOPRIO_CLASS_RT: 5291 bfqq->new_ioprio = IOPRIO_PRIO_DATA(bic->ioprio); 5292 bfqq->new_ioprio_class = IOPRIO_CLASS_RT; 5293 break; 5294 case IOPRIO_CLASS_BE: 5295 bfqq->new_ioprio = IOPRIO_PRIO_DATA(bic->ioprio); 5296 bfqq->new_ioprio_class = IOPRIO_CLASS_BE; 5297 break; 5298 case IOPRIO_CLASS_IDLE: 5299 bfqq->new_ioprio_class = IOPRIO_CLASS_IDLE; 5300 bfqq->new_ioprio = 7; 5301 break; 5302 } 5303 5304 if (bfqq->new_ioprio >= IOPRIO_BE_NR) { 5305 pr_crit("bfq_set_next_ioprio_data: new_ioprio %d\n", 5306 bfqq->new_ioprio); 5307 bfqq->new_ioprio = IOPRIO_BE_NR; 5308 } 5309 5310 bfqq->entity.new_weight = bfq_ioprio_to_weight(bfqq->new_ioprio); 5311 bfq_log_bfqq(bfqd, bfqq, "new_ioprio %d new_weight %d", 5312 bfqq->new_ioprio, bfqq->entity.new_weight); 5313 bfqq->entity.prio_changed = 1; 5314} 5315 5316static struct bfq_queue *bfq_get_queue(struct bfq_data *bfqd, 5317 struct bio *bio, bool is_sync, 5318 struct bfq_io_cq *bic, 5319 bool respawn); 5320 5321static void bfq_check_ioprio_change(struct bfq_io_cq *bic, struct bio *bio) 5322{ 5323 struct bfq_data *bfqd = bic_to_bfqd(bic); 5324 struct bfq_queue *bfqq; 5325 int ioprio = bic->icq.ioc->ioprio; 5326 5327 /* 5328 * This condition may trigger on a newly created bic, be sure to 5329 * drop the lock before returning. 5330 */ 5331 if (unlikely(!bfqd) || likely(bic->ioprio == ioprio)) 5332 return; 5333 5334 bic->ioprio = ioprio; 5335 5336 bfqq = bic_to_bfqq(bic, false); 5337 if (bfqq) { 5338 bfq_release_process_ref(bfqd, bfqq); 5339 bfqq = bfq_get_queue(bfqd, bio, BLK_RW_ASYNC, bic, true); 5340 bic_set_bfqq(bic, bfqq, false); 5341 } 5342 5343 bfqq = bic_to_bfqq(bic, true); 5344 if (bfqq) 5345 bfq_set_next_ioprio_data(bfqq, bic); 5346} 5347 5348static void bfq_init_bfqq(struct bfq_data *bfqd, struct bfq_queue *bfqq, 5349 struct bfq_io_cq *bic, pid_t pid, int is_sync) 5350{ 5351 u64 now_ns = ktime_get_ns(); 5352 5353 RB_CLEAR_NODE(&bfqq->entity.rb_node); 5354 INIT_LIST_HEAD(&bfqq->fifo); 5355 INIT_HLIST_NODE(&bfqq->burst_list_node); 5356 INIT_HLIST_NODE(&bfqq->woken_list_node); 5357 INIT_HLIST_HEAD(&bfqq->woken_list); 5358 5359 bfqq->ref = 0; 5360 bfqq->bfqd = bfqd; 5361 5362 if (bic) 5363 bfq_set_next_ioprio_data(bfqq, bic); 5364 5365 if (is_sync) { 5366 /* 5367 * No need to mark as has_short_ttime if in 5368 * idle_class, because no device idling is performed 5369 * for queues in idle class 5370 */ 5371 if (!bfq_class_idle(bfqq)) 5372 /* tentatively mark as has_short_ttime */ 5373 bfq_mark_bfqq_has_short_ttime(bfqq); 5374 bfq_mark_bfqq_sync(bfqq); 5375 bfq_mark_bfqq_just_created(bfqq); 5376 } else 5377 bfq_clear_bfqq_sync(bfqq); 5378 5379 /* set end request to minus infinity from now */ 5380 bfqq->ttime.last_end_request = now_ns + 1; 5381 5382 bfqq->creation_time = jiffies; 5383 5384 bfqq->io_start_time = now_ns; 5385 5386 bfq_mark_bfqq_IO_bound(bfqq); 5387 5388 bfqq->pid = pid; 5389 5390 /* Tentative initial value to trade off between thr and lat */ 5391 bfqq->max_budget = (2 * bfq_max_budget(bfqd)) / 3; 5392 bfqq->budget_timeout = bfq_smallest_from_now(); 5393 5394 bfqq->wr_coeff = 1; 5395 bfqq->last_wr_start_finish = jiffies; 5396 bfqq->wr_start_at_switch_to_srt = bfq_smallest_from_now(); 5397 bfqq->split_time = bfq_smallest_from_now(); 5398 5399 /* 5400 * To not forget the possibly high bandwidth consumed by a 5401 * process/queue in the recent past, 5402 * bfq_bfqq_softrt_next_start() returns a value at least equal 5403 * to the current value of bfqq->soft_rt_next_start (see 5404 * comments on bfq_bfqq_softrt_next_start). Set 5405 * soft_rt_next_start to now, to mean that bfqq has consumed 5406 * no bandwidth so far. 5407 */ 5408 bfqq->soft_rt_next_start = jiffies; 5409 5410 /* first request is almost certainly seeky */ 5411 bfqq->seek_history = 1; 5412} 5413 5414static struct bfq_queue **bfq_async_queue_prio(struct bfq_data *bfqd, 5415 struct bfq_group *bfqg, 5416 int ioprio_class, int ioprio) 5417{ 5418 switch (ioprio_class) { 5419 case IOPRIO_CLASS_RT: 5420 return &bfqg->async_bfqq[0][ioprio]; 5421 case IOPRIO_CLASS_NONE: 5422 ioprio = IOPRIO_NORM; 5423 /* fall through */ 5424 case IOPRIO_CLASS_BE: 5425 return &bfqg->async_bfqq[1][ioprio]; 5426 case IOPRIO_CLASS_IDLE: 5427 return &bfqg->async_idle_bfqq; 5428 default: 5429 return NULL; 5430 } 5431} 5432 5433static struct bfq_queue * 5434bfq_do_early_stable_merge(struct bfq_data *bfqd, struct bfq_queue *bfqq, 5435 struct bfq_io_cq *bic, 5436 struct bfq_queue *last_bfqq_created) 5437{ 5438 struct bfq_queue *new_bfqq = 5439 bfq_setup_merge(bfqq, last_bfqq_created); 5440 5441 if (!new_bfqq) 5442 return bfqq; 5443 5444 if (new_bfqq->bic) 5445 new_bfqq->bic->stably_merged = true; 5446 bic->stably_merged = true; 5447 5448 /* 5449 * Reusing merge functions. This implies that 5450 * bfqq->bic must be set too, for 5451 * bfq_merge_bfqqs to correctly save bfqq's 5452 * state before killing it. 5453 */ 5454 bfqq->bic = bic; 5455 bfq_merge_bfqqs(bfqd, bic, bfqq, new_bfqq); 5456 5457 return new_bfqq; 5458} 5459 5460/* 5461 * Many throughput-sensitive workloads are made of several parallel 5462 * I/O flows, with all flows generated by the same application, or 5463 * more generically by the same task (e.g., system boot). The most 5464 * counterproductive action with these workloads is plugging I/O 5465 * dispatch when one of the bfq_queues associated with these flows 5466 * remains temporarily empty. 5467 * 5468 * To avoid this plugging, BFQ has been using a burst-handling 5469 * mechanism for years now. This mechanism has proven effective for 5470 * throughput, and not detrimental for service guarantees. The 5471 * following function pushes this mechanism a little bit further, 5472 * basing on the following two facts. 5473 * 5474 * First, all the I/O flows of a the same application or task 5475 * contribute to the execution/completion of that common application 5476 * or task. So the performance figures that matter are total 5477 * throughput of the flows and task-wide I/O latency. In particular, 5478 * these flows do not need to be protected from each other, in terms 5479 * of individual bandwidth or latency. 5480 * 5481 * Second, the above fact holds regardless of the number of flows. 5482 * 5483 * Putting these two facts together, this commits merges stably the 5484 * bfq_queues associated with these I/O flows, i.e., with the 5485 * processes that generate these IO/ flows, regardless of how many the 5486 * involved processes are. 5487 * 5488 * To decide whether a set of bfq_queues is actually associated with 5489 * the I/O flows of a common application or task, and to merge these 5490 * queues stably, this function operates as follows: given a bfq_queue, 5491 * say Q2, currently being created, and the last bfq_queue, say Q1, 5492 * created before Q2, Q2 is merged stably with Q1 if 5493 * - very little time has elapsed since when Q1 was created 5494 * - Q2 has the same ioprio as Q1 5495 * - Q2 belongs to the same group as Q1 5496 * 5497 * Merging bfq_queues also reduces scheduling overhead. A fio test 5498 * with ten random readers on /dev/nullb shows a throughput boost of 5499 * 40%, with a quadcore. Since BFQ's execution time amounts to ~50% of 5500 * the total per-request processing time, the above throughput boost 5501 * implies that BFQ's overhead is reduced by more than 50%. 5502 * 5503 * This new mechanism most certainly obsoletes the current 5504 * burst-handling heuristics. We keep those heuristics for the moment. 5505 */ 5506static struct bfq_queue *bfq_do_or_sched_stable_merge(struct bfq_data *bfqd, 5507 struct bfq_queue *bfqq, 5508 struct bfq_io_cq *bic) 5509{ 5510 struct bfq_queue **source_bfqq = bfqq->entity.parent ? 5511 &bfqq->entity.parent->last_bfqq_created : 5512 &bfqd->last_bfqq_created; 5513 5514 struct bfq_queue *last_bfqq_created = *source_bfqq; 5515 5516 /* 5517 * If last_bfqq_created has not been set yet, then init it. If 5518 * it has been set already, but too long ago, then move it 5519 * forward to bfqq. Finally, move also if bfqq belongs to a 5520 * different group than last_bfqq_created, or if bfqq has a 5521 * different ioprio or ioprio_class. If none of these 5522 * conditions holds true, then try an early stable merge or 5523 * schedule a delayed stable merge. 5524 * 5525 * A delayed merge is scheduled (instead of performing an 5526 * early merge), in case bfqq might soon prove to be more 5527 * throughput-beneficial if not merged. Currently this is 5528 * possible only if bfqd is rotational with no queueing. For 5529 * such a drive, not merging bfqq is better for throughput if 5530 * bfqq happens to contain sequential I/O. So, we wait a 5531 * little bit for enough I/O to flow through bfqq. After that, 5532 * if such an I/O is sequential, then the merge is 5533 * canceled. Otherwise the merge is finally performed. 5534 */ 5535 if (!last_bfqq_created || 5536 time_before(last_bfqq_created->creation_time + 5537 msecs_to_jiffies(bfq_activation_stable_merging), 5538 bfqq->creation_time) || 5539 bfqq->entity.parent != last_bfqq_created->entity.parent || 5540 bfqq->ioprio != last_bfqq_created->ioprio || 5541 bfqq->ioprio_class != last_bfqq_created->ioprio_class) 5542 *source_bfqq = bfqq; 5543 else if (time_after_eq(last_bfqq_created->creation_time + 5544 bfqd->bfq_burst_interval, 5545 bfqq->creation_time)) { 5546 if (likely(bfqd->nonrot_with_queueing)) 5547 /* 5548 * With this type of drive, leaving 5549 * bfqq alone may provide no 5550 * throughput benefits compared with 5551 * merging bfqq. So merge bfqq now. 5552 */ 5553 bfqq = bfq_do_early_stable_merge(bfqd, bfqq, 5554 bic, 5555 last_bfqq_created); 5556 else { /* schedule tentative stable merge */ 5557 /* 5558 * get reference on last_bfqq_created, 5559 * to prevent it from being freed, 5560 * until we decide whether to merge 5561 */ 5562 last_bfqq_created->ref++; 5563 /* 5564 * need to keep track of stable refs, to 5565 * compute process refs correctly 5566 */ 5567 last_bfqq_created->stable_ref++; 5568 /* 5569 * Record the bfqq to merge to. 5570 */ 5571 bic->stable_merge_bfqq = last_bfqq_created; 5572 } 5573 } 5574 5575 return bfqq; 5576} 5577 5578 5579static struct bfq_queue *bfq_get_queue(struct bfq_data *bfqd, 5580 struct bio *bio, bool is_sync, 5581 struct bfq_io_cq *bic, 5582 bool respawn) 5583{ 5584 const int ioprio = IOPRIO_PRIO_DATA(bic->ioprio); 5585 const int ioprio_class = IOPRIO_PRIO_CLASS(bic->ioprio); 5586 struct bfq_queue **async_bfqq = NULL; 5587 struct bfq_queue *bfqq; 5588 struct bfq_group *bfqg; 5589 5590 rcu_read_lock(); 5591 5592 bfqg = bfq_find_set_group(bfqd, __bio_blkcg(bio)); 5593 if (!bfqg) { 5594 bfqq = &bfqd->oom_bfqq; 5595 goto out; 5596 } 5597 5598 if (!is_sync) { 5599 async_bfqq = bfq_async_queue_prio(bfqd, bfqg, ioprio_class, 5600 ioprio); 5601 bfqq = *async_bfqq; 5602 if (bfqq) 5603 goto out; 5604 } 5605 5606 bfqq = kmem_cache_alloc_node(bfq_pool, 5607 GFP_NOWAIT | __GFP_ZERO | __GFP_NOWARN, 5608 bfqd->queue->node); 5609 5610 if (bfqq) { 5611 bfq_init_bfqq(bfqd, bfqq, bic, current->pid, 5612 is_sync); 5613 bfq_init_entity(&bfqq->entity, bfqg); 5614 bfq_log_bfqq(bfqd, bfqq, "allocated"); 5615 } else { 5616 bfqq = &bfqd->oom_bfqq; 5617 bfq_log_bfqq(bfqd, bfqq, "using oom bfqq"); 5618 goto out; 5619 } 5620 5621 /* 5622 * Pin the queue now that it's allocated, scheduler exit will 5623 * prune it. 5624 */ 5625 if (async_bfqq) { 5626 bfqq->ref++; /* 5627 * Extra group reference, w.r.t. sync 5628 * queue. This extra reference is removed 5629 * only if bfqq->bfqg disappears, to 5630 * guarantee that this queue is not freed 5631 * until its group goes away. 5632 */ 5633 bfq_log_bfqq(bfqd, bfqq, "get_queue, bfqq not in async: %p, %d", 5634 bfqq, bfqq->ref); 5635 *async_bfqq = bfqq; 5636 } 5637 5638out: 5639 bfqq->ref++; /* get a process reference to this queue */ 5640 5641 if (bfqq != &bfqd->oom_bfqq && is_sync && !respawn) 5642 bfqq = bfq_do_or_sched_stable_merge(bfqd, bfqq, bic); 5643 5644 rcu_read_unlock(); 5645 return bfqq; 5646} 5647 5648static void bfq_update_io_thinktime(struct bfq_data *bfqd, 5649 struct bfq_queue *bfqq) 5650{ 5651 struct bfq_ttime *ttime = &bfqq->ttime; 5652 u64 elapsed; 5653 5654 /* 5655 * We are really interested in how long it takes for the queue to 5656 * become busy when there is no outstanding IO for this queue. So 5657 * ignore cases when the bfq queue has already IO queued. 5658 */ 5659 if (bfqq->dispatched || bfq_bfqq_busy(bfqq)) 5660 return; 5661 elapsed = ktime_get_ns() - bfqq->ttime.last_end_request; 5662 elapsed = min_t(u64, elapsed, 2ULL * bfqd->bfq_slice_idle); 5663 5664 ttime->ttime_samples = (7*ttime->ttime_samples + 256) / 8; 5665 ttime->ttime_total = div_u64(7*ttime->ttime_total + 256*elapsed, 8); 5666 ttime->ttime_mean = div64_ul(ttime->ttime_total + 128, 5667 ttime->ttime_samples); 5668} 5669 5670static void 5671bfq_update_io_seektime(struct bfq_data *bfqd, struct bfq_queue *bfqq, 5672 struct request *rq) 5673{ 5674 bfqq->seek_history <<= 1; 5675 bfqq->seek_history |= BFQ_RQ_SEEKY(bfqd, bfqq->last_request_pos, rq); 5676 5677 if (bfqq->wr_coeff > 1 && 5678 bfqq->wr_cur_max_time == bfqd->bfq_wr_rt_max_time && 5679 BFQQ_TOTALLY_SEEKY(bfqq)) { 5680 if (time_is_before_jiffies(bfqq->wr_start_at_switch_to_srt + 5681 bfq_wr_duration(bfqd))) { 5682 /* 5683 * In soft_rt weight raising with the 5684 * interactive-weight-raising period 5685 * elapsed (so no switch back to 5686 * interactive weight raising). 5687 */ 5688 bfq_bfqq_end_wr(bfqq); 5689 } else { /* 5690 * stopping soft_rt weight raising 5691 * while still in interactive period, 5692 * switch back to interactive weight 5693 * raising 5694 */ 5695 switch_back_to_interactive_wr(bfqq, bfqd); 5696 bfqq->entity.prio_changed = 1; 5697 } 5698 } 5699} 5700 5701static void bfq_update_has_short_ttime(struct bfq_data *bfqd, 5702 struct bfq_queue *bfqq, 5703 struct bfq_io_cq *bic) 5704{ 5705 bool has_short_ttime = true, state_changed; 5706 5707 /* 5708 * No need to update has_short_ttime if bfqq is async or in 5709 * idle io prio class, or if bfq_slice_idle is zero, because 5710 * no device idling is performed for bfqq in this case. 5711 */ 5712 if (!bfq_bfqq_sync(bfqq) || bfq_class_idle(bfqq) || 5713 bfqd->bfq_slice_idle == 0) 5714 return; 5715 5716 /* Idle window just restored, statistics are meaningless. */ 5717 if (time_is_after_eq_jiffies(bfqq->split_time + 5718 bfqd->bfq_wr_min_idle_time)) 5719 return; 5720 5721 /* Think time is infinite if no process is linked to 5722 * bfqq. Otherwise check average think time to decide whether 5723 * to mark as has_short_ttime. To this goal, compare average 5724 * think time with half the I/O-plugging timeout. 5725 */ 5726 if (atomic_read(&bic->icq.ioc->active_ref) == 0 || 5727 (bfq_sample_valid(bfqq->ttime.ttime_samples) && 5728 bfqq->ttime.ttime_mean > bfqd->bfq_slice_idle>>1)) 5729 has_short_ttime = false; 5730 5731 state_changed = has_short_ttime != bfq_bfqq_has_short_ttime(bfqq); 5732 5733 if (has_short_ttime) 5734 bfq_mark_bfqq_has_short_ttime(bfqq); 5735 else 5736 bfq_clear_bfqq_has_short_ttime(bfqq); 5737 5738 /* 5739 * Until the base value for the total service time gets 5740 * finally computed for bfqq, the inject limit does depend on 5741 * the think-time state (short|long). In particular, the limit 5742 * is 0 or 1 if the think time is deemed, respectively, as 5743 * short or long (details in the comments in 5744 * bfq_update_inject_limit()). Accordingly, the next 5745 * instructions reset the inject limit if the think-time state 5746 * has changed and the above base value is still to be 5747 * computed. 5748 * 5749 * However, the reset is performed only if more than 100 ms 5750 * have elapsed since the last update of the inject limit, or 5751 * (inclusive) if the change is from short to long think 5752 * time. The reason for this waiting is as follows. 5753 * 5754 * bfqq may have a long think time because of a 5755 * synchronization with some other queue, i.e., because the 5756 * I/O of some other queue may need to be completed for bfqq 5757 * to receive new I/O. Details in the comments on the choice 5758 * of the queue for injection in bfq_select_queue(). 5759 * 5760 * As stressed in those comments, if such a synchronization is 5761 * actually in place, then, without injection on bfqq, the 5762 * blocking I/O cannot happen to served while bfqq is in 5763 * service. As a consequence, if bfqq is granted 5764 * I/O-dispatch-plugging, then bfqq remains empty, and no I/O 5765 * is dispatched, until the idle timeout fires. This is likely 5766 * to result in lower bandwidth and higher latencies for bfqq, 5767 * and in a severe loss of total throughput. 5768 * 5769 * On the opposite end, a non-zero inject limit may allow the 5770 * I/O that blocks bfqq to be executed soon, and therefore 5771 * bfqq to receive new I/O soon. 5772 * 5773 * But, if the blocking gets actually eliminated, then the 5774 * next think-time sample for bfqq may be very low. This in 5775 * turn may cause bfqq's think time to be deemed 5776 * short. Without the 100 ms barrier, this new state change 5777 * would cause the body of the next if to be executed 5778 * immediately. But this would set to 0 the inject 5779 * limit. Without injection, the blocking I/O would cause the 5780 * think time of bfqq to become long again, and therefore the 5781 * inject limit to be raised again, and so on. The only effect 5782 * of such a steady oscillation between the two think-time 5783 * states would be to prevent effective injection on bfqq. 5784 * 5785 * In contrast, if the inject limit is not reset during such a 5786 * long time interval as 100 ms, then the number of short 5787 * think time samples can grow significantly before the reset 5788 * is performed. As a consequence, the think time state can 5789 * become stable before the reset. Therefore there will be no 5790 * state change when the 100 ms elapse, and no reset of the 5791 * inject limit. The inject limit remains steadily equal to 1 5792 * both during and after the 100 ms. So injection can be 5793 * performed at all times, and throughput gets boosted. 5794 * 5795 * An inject limit equal to 1 is however in conflict, in 5796 * general, with the fact that the think time of bfqq is 5797 * short, because injection may be likely to delay bfqq's I/O 5798 * (as explained in the comments in 5799 * bfq_update_inject_limit()). But this does not happen in 5800 * this special case, because bfqq's low think time is due to 5801 * an effective handling of a synchronization, through 5802 * injection. In this special case, bfqq's I/O does not get 5803 * delayed by injection; on the contrary, bfqq's I/O is 5804 * brought forward, because it is not blocked for 5805 * milliseconds. 5806 * 5807 * In addition, serving the blocking I/O much sooner, and much 5808 * more frequently than once per I/O-plugging timeout, makes 5809 * it much quicker to detect a waker queue (the concept of 5810 * waker queue is defined in the comments in 5811 * bfq_add_request()). This makes it possible to start sooner 5812 * to boost throughput more effectively, by injecting the I/O 5813 * of the waker queue unconditionally on every 5814 * bfq_dispatch_request(). 5815 * 5816 * One last, important benefit of not resetting the inject 5817 * limit before 100 ms is that, during this time interval, the 5818 * base value for the total service time is likely to get 5819 * finally computed for bfqq, freeing the inject limit from 5820 * its relation with the think time. 5821 */ 5822 if (state_changed && bfqq->last_serv_time_ns == 0 && 5823 (time_is_before_eq_jiffies(bfqq->decrease_time_jif + 5824 msecs_to_jiffies(100)) || 5825 !has_short_ttime)) 5826 bfq_reset_inject_limit(bfqd, bfqq); 5827} 5828 5829/* 5830 * Called when a new fs request (rq) is added to bfqq. Check if there's 5831 * something we should do about it. 5832 */ 5833static void bfq_rq_enqueued(struct bfq_data *bfqd, struct bfq_queue *bfqq, 5834 struct request *rq) 5835{ 5836 if (rq->cmd_flags & REQ_META) 5837 bfqq->meta_pending++; 5838 5839 bfqq->last_request_pos = blk_rq_pos(rq) + blk_rq_sectors(rq); 5840 5841 if (bfqq == bfqd->in_service_queue && bfq_bfqq_wait_request(bfqq)) { 5842 bool small_req = bfqq->queued[rq_is_sync(rq)] == 1 && 5843 blk_rq_sectors(rq) < 32; 5844 bool budget_timeout = bfq_bfqq_budget_timeout(bfqq); 5845 5846 /* 5847 * There is just this request queued: if 5848 * - the request is small, and 5849 * - we are idling to boost throughput, and 5850 * - the queue is not to be expired, 5851 * then just exit. 5852 * 5853 * In this way, if the device is being idled to wait 5854 * for a new request from the in-service queue, we 5855 * avoid unplugging the device and committing the 5856 * device to serve just a small request. In contrast 5857 * we wait for the block layer to decide when to 5858 * unplug the device: hopefully, new requests will be 5859 * merged to this one quickly, then the device will be 5860 * unplugged and larger requests will be dispatched. 5861 */ 5862 if (small_req && idling_boosts_thr_without_issues(bfqd, bfqq) && 5863 !budget_timeout) 5864 return; 5865 5866 /* 5867 * A large enough request arrived, or idling is being 5868 * performed to preserve service guarantees, or 5869 * finally the queue is to be expired: in all these 5870 * cases disk idling is to be stopped, so clear 5871 * wait_request flag and reset timer. 5872 */ 5873 bfq_clear_bfqq_wait_request(bfqq); 5874 hrtimer_try_to_cancel(&bfqd->idle_slice_timer); 5875 5876 /* 5877 * The queue is not empty, because a new request just 5878 * arrived. Hence we can safely expire the queue, in 5879 * case of budget timeout, without risking that the 5880 * timestamps of the queue are not updated correctly. 5881 * See [1] for more details. 5882 */ 5883 if (budget_timeout) 5884 bfq_bfqq_expire(bfqd, bfqq, false, 5885 BFQQE_BUDGET_TIMEOUT); 5886 } 5887} 5888 5889/* returns true if it causes the idle timer to be disabled */ 5890static bool __bfq_insert_request(struct bfq_data *bfqd, struct request *rq) 5891{ 5892 struct bfq_queue *bfqq = RQ_BFQQ(rq), 5893 *new_bfqq = bfq_setup_cooperator(bfqd, bfqq, rq, true, 5894 RQ_BIC(rq)); 5895 bool waiting, idle_timer_disabled = false; 5896 5897 if (new_bfqq) { 5898 /* 5899 * Release the request's reference to the old bfqq 5900 * and make sure one is taken to the shared queue. 5901 */ 5902 new_bfqq->allocated++; 5903 bfqq->allocated--; 5904 new_bfqq->ref++; 5905 /* 5906 * If the bic associated with the process 5907 * issuing this request still points to bfqq 5908 * (and thus has not been already redirected 5909 * to new_bfqq or even some other bfq_queue), 5910 * then complete the merge and redirect it to 5911 * new_bfqq. 5912 */ 5913 if (bic_to_bfqq(RQ_BIC(rq), 1) == bfqq) 5914 bfq_merge_bfqqs(bfqd, RQ_BIC(rq), 5915 bfqq, new_bfqq); 5916 5917 bfq_clear_bfqq_just_created(bfqq); 5918 /* 5919 * rq is about to be enqueued into new_bfqq, 5920 * release rq reference on bfqq 5921 */ 5922 bfq_put_queue(bfqq); 5923 rq->elv.priv[1] = new_bfqq; 5924 bfqq = new_bfqq; 5925 } 5926 5927 bfq_update_io_thinktime(bfqd, bfqq); 5928 bfq_update_has_short_ttime(bfqd, bfqq, RQ_BIC(rq)); 5929 bfq_update_io_seektime(bfqd, bfqq, rq); 5930 5931 waiting = bfqq && bfq_bfqq_wait_request(bfqq); 5932 bfq_add_request(rq); 5933 idle_timer_disabled = waiting && !bfq_bfqq_wait_request(bfqq); 5934 5935 rq->fifo_time = ktime_get_ns() + bfqd->bfq_fifo_expire[rq_is_sync(rq)]; 5936 list_add_tail(&rq->queuelist, &bfqq->fifo); 5937 5938 bfq_rq_enqueued(bfqd, bfqq, rq); 5939 5940 return idle_timer_disabled; 5941} 5942 5943#ifdef CONFIG_BFQ_CGROUP_DEBUG 5944static void bfq_update_insert_stats(struct request_queue *q, 5945 struct bfq_queue *bfqq, 5946 bool idle_timer_disabled, 5947 unsigned int cmd_flags) 5948{ 5949 if (!bfqq) 5950 return; 5951 5952 /* 5953 * bfqq still exists, because it can disappear only after 5954 * either it is merged with another queue, or the process it 5955 * is associated with exits. But both actions must be taken by 5956 * the same process currently executing this flow of 5957 * instructions. 5958 * 5959 * In addition, the following queue lock guarantees that 5960 * bfqq_group(bfqq) exists as well. 5961 */ 5962 spin_lock_irq(&q->queue_lock); 5963 bfqg_stats_update_io_add(bfqq_group(bfqq), bfqq, cmd_flags); 5964 if (idle_timer_disabled) 5965 bfqg_stats_update_idle_time(bfqq_group(bfqq)); 5966 spin_unlock_irq(&q->queue_lock); 5967} 5968#else 5969static inline void bfq_update_insert_stats(struct request_queue *q, 5970 struct bfq_queue *bfqq, 5971 bool idle_timer_disabled, 5972 unsigned int cmd_flags) {} 5973#endif /* CONFIG_BFQ_CGROUP_DEBUG */ 5974 5975static void bfq_insert_request(struct blk_mq_hw_ctx *hctx, struct request *rq, 5976 bool at_head) 5977{ 5978 struct request_queue *q = hctx->queue; 5979 struct bfq_data *bfqd = q->elevator->elevator_data; 5980 struct bfq_queue *bfqq; 5981 bool idle_timer_disabled = false; 5982 unsigned int cmd_flags; 5983 LIST_HEAD(free); 5984 5985#ifdef CONFIG_BFQ_GROUP_IOSCHED 5986 if (!cgroup_subsys_on_dfl(io_cgrp_subsys) && rq->bio) 5987 bfqg_stats_update_legacy_io(q, rq); 5988#endif 5989 spin_lock_irq(&bfqd->lock); 5990 if (blk_mq_sched_try_insert_merge(q, rq, &free)) { 5991 spin_unlock_irq(&bfqd->lock); 5992 blk_mq_free_requests(&free); 5993 return; 5994 } 5995 5996 spin_unlock_irq(&bfqd->lock); 5997 5998 trace_block_rq_insert(rq); 5999 6000 spin_lock_irq(&bfqd->lock);
6001 bfqq = bfq_init_rq(rq); 6002 6003 /* 6004 * Reqs with at_head or passthrough flags set are to be put 6005 * directly into dispatch list. Additional case for putting rq 6006 * directly into the dispatch queue: the only active 6007 * bfq_queues are bfqq and either its waker bfq_queue or one 6008 * of its woken bfq_queues. The rationale behind this 6009 * additional condition is as follows: 6010 * - consider a bfq_queue, say Q1, detected as a waker of 6011 * another bfq_queue, say Q2 6012 * - by definition of a waker, Q1 blocks the I/O of Q2, i.e., 6013 * some I/O of Q1 needs to be completed for new I/O of Q2 6014 * to arrive. A notable example of waker is journald 6015 * - so, Q1 and Q2 are in any respect the queues of two 6016 * cooperating processes (or of two cooperating sets of 6017 * processes): the goal of Q1's I/O is doing what needs to 6018 * be done so that new Q2's I/O can finally be 6019 * issued. Therefore, if the service of Q1's I/O is delayed, 6020 * then Q2's I/O is delayed too. Conversely, if Q2's I/O is 6021 * delayed, the goal of Q1's I/O is hindered. 6022 * - as a consequence, if some I/O of Q1/Q2 arrives while 6023 * Q2/Q1 is the only queue in service, there is absolutely 6024 * no point in delaying the service of such an I/O. The 6025 * only possible result is a throughput loss 6026 * - so, when the above condition holds, the best option is to 6027 * have the new I/O dispatched as soon as possible 6028 * - the most effective and efficient way to attain the above 6029 * goal is to put the new I/O directly in the dispatch 6030 * list 6031 * - as an additional restriction, Q1 and Q2 must be the only 6032 * busy queues for this commit to put the I/O of Q2/Q1 in 6033 * the dispatch list. This is necessary, because, if also 6034 * other queues are waiting for service, then putting new 6035 * I/O directly in the dispatch list may evidently cause a 6036 * violation of service guarantees for the other queues 6037 */ 6038 if (!bfqq || 6039 (bfqq != bfqd->in_service_queue && 6040 bfqd->in_service_queue != NULL && 6041 bfq_tot_busy_queues(bfqd) == 1 + bfq_bfqq_busy(bfqq) && 6042 (bfqq->waker_bfqq == bfqd->in_service_queue || 6043 bfqd->in_service_queue->waker_bfqq == bfqq)) || at_head) { 6044 if (at_head) 6045 list_add(&rq->queuelist, &bfqd->dispatch); 6046 else 6047 list_add_tail(&rq->queuelist, &bfqd->dispatch); 6048 } else { 6049 idle_timer_disabled = __bfq_insert_request(bfqd, rq); 6050 /* 6051 * Update bfqq, because, if a queue merge has occurred 6052 * in __bfq_insert_request, then rq has been 6053 * redirected into a new queue. 6054 */ 6055 bfqq = RQ_BFQQ(rq); 6056 6057 if (rq_mergeable(rq)) { 6058 elv_rqhash_add(q, rq); 6059 if (!q->last_merge) 6060 q->last_merge = rq; 6061 } 6062 } 6063 6064 /* 6065 * Cache cmd_flags before releasing scheduler lock, because rq 6066 * may disappear afterwards (for example, because of a request 6067 * merge). 6068 */ 6069 cmd_flags = rq->cmd_flags; 6070 6071 spin_unlock_irq(&bfqd->lock); 6072 6073 bfq_update_insert_stats(q, bfqq, idle_timer_disabled, 6074 cmd_flags); 6075} 6076 6077static void bfq_insert_requests(struct blk_mq_hw_ctx *hctx, 6078 struct list_head *list, bool at_head) 6079{ 6080 while (!list_empty(list)) { 6081 struct request *rq; 6082 6083 rq = list_first_entry(list, struct request, queuelist); 6084 list_del_init(&rq->queuelist); 6085 bfq_insert_request(hctx, rq, at_head); 6086 } 6087} 6088 6089static void bfq_update_hw_tag(struct bfq_data *bfqd) 6090{ 6091 struct bfq_queue *bfqq = bfqd->in_service_queue; 6092 6093 bfqd->max_rq_in_driver = max_t(int, bfqd->max_rq_in_driver, 6094 bfqd->rq_in_driver); 6095 6096 if (bfqd->hw_tag == 1) 6097 return; 6098 6099 /* 6100 * This sample is valid if the number of outstanding requests 6101 * is large enough to allow a queueing behavior. Note that the 6102 * sum is not exact, as it's not taking into account deactivated 6103 * requests. 6104 */ 6105 if (bfqd->rq_in_driver + bfqd->queued <= BFQ_HW_QUEUE_THRESHOLD) 6106 return; 6107 6108 /* 6109 * If active queue hasn't enough requests and can idle, bfq might not 6110 * dispatch sufficient requests to hardware. Don't zero hw_tag in this 6111 * case 6112 */ 6113 if (bfqq && bfq_bfqq_has_short_ttime(bfqq) && 6114 bfqq->dispatched + bfqq->queued[0] + bfqq->queued[1] < 6115 BFQ_HW_QUEUE_THRESHOLD && 6116 bfqd->rq_in_driver < BFQ_HW_QUEUE_THRESHOLD) 6117 return; 6118 6119 if (bfqd->hw_tag_samples++ < BFQ_HW_QUEUE_SAMPLES) 6120 return; 6121 6122 bfqd->hw_tag = bfqd->max_rq_in_driver > BFQ_HW_QUEUE_THRESHOLD; 6123 bfqd->max_rq_in_driver = 0; 6124 bfqd->hw_tag_samples = 0; 6125 6126 bfqd->nonrot_with_queueing = 6127 blk_queue_nonrot(bfqd->queue) && bfqd->hw_tag; 6128} 6129 6130static void bfq_completed_request(struct bfq_queue *bfqq, struct bfq_data *bfqd) 6131{ 6132 u64 now_ns; 6133 u32 delta_us; 6134 6135 bfq_update_hw_tag(bfqd); 6136 6137 bfqd->rq_in_driver--; 6138 bfqq->dispatched--; 6139 6140 if (!bfqq->dispatched && !bfq_bfqq_busy(bfqq)) { 6141 /* 6142 * Set budget_timeout (which we overload to store the 6143 * time at which the queue remains with no backlog and 6144 * no outstanding request; used by the weight-raising 6145 * mechanism). 6146 */ 6147 bfqq->budget_timeout = jiffies; 6148 6149 bfq_weights_tree_remove(bfqd, bfqq); 6150 } 6151 6152 now_ns = ktime_get_ns(); 6153 6154 bfqq->ttime.last_end_request = now_ns; 6155 6156 /* 6157 * Using us instead of ns, to get a reasonable precision in 6158 * computing rate in next check. 6159 */ 6160 delta_us = div_u64(now_ns - bfqd->last_completion, NSEC_PER_USEC); 6161 6162 /* 6163 * If the request took rather long to complete, and, according 6164 * to the maximum request size recorded, this completion latency 6165 * implies that the request was certainly served at a very low 6166 * rate (less than 1M sectors/sec), then the whole observation 6167 * interval that lasts up to this time instant cannot be a 6168 * valid time interval for computing a new peak rate. Invoke 6169 * bfq_update_rate_reset to have the following three steps 6170 * taken: 6171 * - close the observation interval at the last (previous) 6172 * request dispatch or completion 6173 * - compute rate, if possible, for that observation interval 6174 * - reset to zero samples, which will trigger a proper 6175 * re-initialization of the observation interval on next 6176 * dispatch 6177 */ 6178 if (delta_us > BFQ_MIN_TT/NSEC_PER_USEC && 6179 (bfqd->last_rq_max_size<<BFQ_RATE_SHIFT)/delta_us < 6180 1UL<<(BFQ_RATE_SHIFT - 10)) 6181 bfq_update_rate_reset(bfqd, NULL); 6182 bfqd->last_completion = now_ns; 6183 /* 6184 * Shared queues are likely to receive I/O at a high 6185 * rate. This may deceptively let them be considered as wakers 6186 * of other queues. But a false waker will unjustly steal 6187 * bandwidth to its supposedly woken queue. So considering 6188 * also shared queues in the waking mechanism may cause more 6189 * control troubles than throughput benefits. Then reset 6190 * last_completed_rq_bfqq if bfqq is a shared queue. 6191 */ 6192 if (!bfq_bfqq_coop(bfqq)) 6193 bfqd->last_completed_rq_bfqq = bfqq; 6194 else 6195 bfqd->last_completed_rq_bfqq = NULL; 6196 6197 /* 6198 * If we are waiting to discover whether the request pattern 6199 * of the task associated with the queue is actually 6200 * isochronous, and both requisites for this condition to hold 6201 * are now satisfied, then compute soft_rt_next_start (see the 6202 * comments on the function bfq_bfqq_softrt_next_start()). We 6203 * do not compute soft_rt_next_start if bfqq is in interactive 6204 * weight raising (see the comments in bfq_bfqq_expire() for 6205 * an explanation). We schedule this delayed update when bfqq 6206 * expires, if it still has in-flight requests. 6207 */ 6208 if (bfq_bfqq_softrt_update(bfqq) && bfqq->dispatched == 0 && 6209 RB_EMPTY_ROOT(&bfqq->sort_list) && 6210 bfqq->wr_coeff != bfqd->bfq_wr_coeff) 6211 bfqq->soft_rt_next_start = 6212 bfq_bfqq_softrt_next_start(bfqd, bfqq); 6213 6214 /* 6215 * If this is the in-service queue, check if it needs to be expired, 6216 * or if we want to idle in case it has no pending requests. 6217 */ 6218 if (bfqd->in_service_queue == bfqq) { 6219 if (bfq_bfqq_must_idle(bfqq)) { 6220 if (bfqq->dispatched == 0) 6221 bfq_arm_slice_timer(bfqd); 6222 /* 6223 * If we get here, we do not expire bfqq, even 6224 * if bfqq was in budget timeout or had no 6225 * more requests (as controlled in the next 6226 * conditional instructions). The reason for 6227 * not expiring bfqq is as follows. 6228 * 6229 * Here bfqq->dispatched > 0 holds, but 6230 * bfq_bfqq_must_idle() returned true. This 6231 * implies that, even if no request arrives 6232 * for bfqq before bfqq->dispatched reaches 0, 6233 * bfqq will, however, not be expired on the 6234 * completion event that causes bfqq->dispatch 6235 * to reach zero. In contrast, on this event, 6236 * bfqq will start enjoying device idling 6237 * (I/O-dispatch plugging). 6238 * 6239 * But, if we expired bfqq here, bfqq would 6240 * not have the chance to enjoy device idling 6241 * when bfqq->dispatched finally reaches 6242 * zero. This would expose bfqq to violation 6243 * of its reserved service guarantees. 6244 */ 6245 return; 6246 } else if (bfq_may_expire_for_budg_timeout(bfqq)) 6247 bfq_bfqq_expire(bfqd, bfqq, false, 6248 BFQQE_BUDGET_TIMEOUT); 6249 else if (RB_EMPTY_ROOT(&bfqq->sort_list) && 6250 (bfqq->dispatched == 0 || 6251 !bfq_better_to_idle(bfqq))) 6252 bfq_bfqq_expire(bfqd, bfqq, false, 6253 BFQQE_NO_MORE_REQUESTS); 6254 } 6255 6256 if (!bfqd->rq_in_driver) 6257 bfq_schedule_dispatch(bfqd); 6258} 6259 6260static void bfq_finish_requeue_request_body(struct bfq_queue *bfqq) 6261{ 6262 bfqq->allocated--; 6263 6264 bfq_put_queue(bfqq); 6265} 6266 6267/* 6268 * The processes associated with bfqq may happen to generate their 6269 * cumulative I/O at a lower rate than the rate at which the device 6270 * could serve the same I/O. This is rather probable, e.g., if only 6271 * one process is associated with bfqq and the device is an SSD. It 6272 * results in bfqq becoming often empty while in service. In this 6273 * respect, if BFQ is allowed to switch to another queue when bfqq 6274 * remains empty, then the device goes on being fed with I/O requests, 6275 * and the throughput is not affected. In contrast, if BFQ is not 6276 * allowed to switch to another queue---because bfqq is sync and 6277 * I/O-dispatch needs to be plugged while bfqq is temporarily 6278 * empty---then, during the service of bfqq, there will be frequent 6279 * "service holes", i.e., time intervals during which bfqq gets empty 6280 * and the device can only consume the I/O already queued in its 6281 * hardware queues. During service holes, the device may even get to 6282 * remaining idle. In the end, during the service of bfqq, the device 6283 * is driven at a lower speed than the one it can reach with the kind 6284 * of I/O flowing through bfqq. 6285 * 6286 * To counter this loss of throughput, BFQ implements a "request 6287 * injection mechanism", which tries to fill the above service holes 6288 * with I/O requests taken from other queues. The hard part in this 6289 * mechanism is finding the right amount of I/O to inject, so as to 6290 * both boost throughput and not break bfqq's bandwidth and latency 6291 * guarantees. In this respect, the mechanism maintains a per-queue 6292 * inject limit, computed as below. While bfqq is empty, the injection 6293 * mechanism dispatches extra I/O requests only until the total number 6294 * of I/O requests in flight---i.e., already dispatched but not yet 6295 * completed---remains lower than this limit. 6296 * 6297 * A first definition comes in handy to introduce the algorithm by 6298 * which the inject limit is computed. We define as first request for 6299 * bfqq, an I/O request for bfqq that arrives while bfqq is in 6300 * service, and causes bfqq to switch from empty to non-empty. The 6301 * algorithm updates the limit as a function of the effect of 6302 * injection on the service times of only the first requests of 6303 * bfqq. The reason for this restriction is that these are the 6304 * requests whose service time is affected most, because they are the 6305 * first to arrive after injection possibly occurred. 6306 * 6307 * To evaluate the effect of injection, the algorithm measures the 6308 * "total service time" of first requests. We define as total service 6309 * time of an I/O request, the time that elapses since when the 6310 * request is enqueued into bfqq, to when it is completed. This 6311 * quantity allows the whole effect of injection to be measured. It is 6312 * easy to see why. Suppose that some requests of other queues are 6313 * actually injected while bfqq is empty, and that a new request R 6314 * then arrives for bfqq. If the device does start to serve all or 6315 * part of the injected requests during the service hole, then, 6316 * because of this extra service, it may delay the next invocation of 6317 * the dispatch hook of BFQ. Then, even after R gets eventually 6318 * dispatched, the device may delay the actual service of R if it is 6319 * still busy serving the extra requests, or if it decides to serve, 6320 * before R, some extra request still present in its queues. As a 6321 * conclusion, the cumulative extra delay caused by injection can be 6322 * easily evaluated by just comparing the total service time of first 6323 * requests with and without injection. 6324 * 6325 * The limit-update algorithm works as follows. On the arrival of a 6326 * first request of bfqq, the algorithm measures the total time of the 6327 * request only if one of the three cases below holds, and, for each 6328 * case, it updates the limit as described below: 6329 * 6330 * (1) If there is no in-flight request. This gives a baseline for the 6331 * total service time of the requests of bfqq. If the baseline has 6332 * not been computed yet, then, after computing it, the limit is 6333 * set to 1, to start boosting throughput, and to prepare the 6334 * ground for the next case. If the baseline has already been 6335 * computed, then it is updated, in case it results to be lower 6336 * than the previous value. 6337 * 6338 * (2) If the limit is higher than 0 and there are in-flight 6339 * requests. By comparing the total service time in this case with 6340 * the above baseline, it is possible to know at which extent the 6341 * current value of the limit is inflating the total service 6342 * time. If the inflation is below a certain threshold, then bfqq 6343 * is assumed to be suffering from no perceivable loss of its 6344 * service guarantees, and the limit is even tentatively 6345 * increased. If the inflation is above the threshold, then the 6346 * limit is decreased. Due to the lack of any hysteresis, this 6347 * logic makes the limit oscillate even in steady workload 6348 * conditions. Yet we opted for it, because it is fast in reaching 6349 * the best value for the limit, as a function of the current I/O 6350 * workload. To reduce oscillations, this step is disabled for a 6351 * short time interval after the limit happens to be decreased. 6352 * 6353 * (3) Periodically, after resetting the limit, to make sure that the 6354 * limit eventually drops in case the workload changes. This is 6355 * needed because, after the limit has gone safely up for a 6356 * certain workload, it is impossible to guess whether the 6357 * baseline total service time may have changed, without measuring 6358 * it again without injection. A more effective version of this 6359 * step might be to just sample the baseline, by interrupting 6360 * injection only once, and then to reset/lower the limit only if 6361 * the total service time with the current limit does happen to be 6362 * too large. 6363 * 6364 * More details on each step are provided in the comments on the 6365 * pieces of code that implement these steps: the branch handling the 6366 * transition from empty to non empty in bfq_add_request(), the branch 6367 * handling injection in bfq_select_queue(), and the function 6368 * bfq_choose_bfqq_for_injection(). These comments also explain some 6369 * exceptions, made by the injection mechanism in some special cases. 6370 */ 6371static void bfq_update_inject_limit(struct bfq_data *bfqd, 6372 struct bfq_queue *bfqq) 6373{ 6374 u64 tot_time_ns = ktime_get_ns() - bfqd->last_empty_occupied_ns; 6375 unsigned int old_limit = bfqq->inject_limit; 6376 6377 if (bfqq->last_serv_time_ns > 0 && bfqd->rqs_injected) { 6378 u64 threshold = (bfqq->last_serv_time_ns * 3)>>1; 6379 6380 if (tot_time_ns >= threshold && old_limit > 0) { 6381 bfqq->inject_limit--; 6382 bfqq->decrease_time_jif = jiffies; 6383 } else if (tot_time_ns < threshold && 6384 old_limit <= bfqd->max_rq_in_driver) 6385 bfqq->inject_limit++; 6386 } 6387 6388 /* 6389 * Either we still have to compute the base value for the 6390 * total service time, and there seem to be the right 6391 * conditions to do it, or we can lower the last base value 6392 * computed. 6393 * 6394 * NOTE: (bfqd->rq_in_driver == 1) means that there is no I/O 6395 * request in flight, because this function is in the code 6396 * path that handles the completion of a request of bfqq, and, 6397 * in particular, this function is executed before 6398 * bfqd->rq_in_driver is decremented in such a code path. 6399 */ 6400 if ((bfqq->last_serv_time_ns == 0 && bfqd->rq_in_driver == 1) || 6401 tot_time_ns < bfqq->last_serv_time_ns) { 6402 if (bfqq->last_serv_time_ns == 0) { 6403 /* 6404 * Now we certainly have a base value: make sure we 6405 * start trying injection. 6406 */ 6407 bfqq->inject_limit = max_t(unsigned int, 1, old_limit); 6408 } 6409 bfqq->last_serv_time_ns = tot_time_ns; 6410 } else if (!bfqd->rqs_injected && bfqd->rq_in_driver == 1) 6411 /* 6412 * No I/O injected and no request still in service in 6413 * the drive: these are the exact conditions for 6414 * computing the base value of the total service time 6415 * for bfqq. So let's update this value, because it is 6416 * rather variable. For example, it varies if the size 6417 * or the spatial locality of the I/O requests in bfqq 6418 * change. 6419 */ 6420 bfqq->last_serv_time_ns = tot_time_ns; 6421 6422 6423 /* update complete, not waiting for any request completion any longer */ 6424 bfqd->waited_rq = NULL; 6425 bfqd->rqs_injected = false; 6426} 6427 6428/* 6429 * Handle either a requeue or a finish for rq. The things to do are 6430 * the same in both cases: all references to rq are to be dropped. In 6431 * particular, rq is considered completed from the point of view of 6432 * the scheduler. 6433 */ 6434static void bfq_finish_requeue_request(struct request *rq) 6435{ 6436 struct bfq_queue *bfqq = RQ_BFQQ(rq); 6437 struct bfq_data *bfqd; 6438 unsigned long flags; 6439 6440 /* 6441 * Requeue and finish hooks are invoked in blk-mq without 6442 * checking whether the involved request is actually still 6443 * referenced in the scheduler. To handle this fact, the 6444 * following two checks make this function exit in case of 6445 * spurious invocations, for which there is nothing to do. 6446 * 6447 * First, check whether rq has nothing to do with an elevator. 6448 */ 6449 if (unlikely(!(rq->rq_flags & RQF_ELVPRIV))) 6450 return; 6451 6452 /* 6453 * rq either is not associated with any icq, or is an already 6454 * requeued request that has not (yet) been re-inserted into 6455 * a bfq_queue. 6456 */ 6457 if (!rq->elv.icq || !bfqq) 6458 return; 6459 6460 bfqd = bfqq->bfqd; 6461 6462 if (rq->rq_flags & RQF_STARTED) 6463 bfqg_stats_update_completion(bfqq_group(bfqq), 6464 rq->start_time_ns, 6465 rq->io_start_time_ns, 6466 rq->cmd_flags); 6467 6468 spin_lock_irqsave(&bfqd->lock, flags); 6469 if (likely(rq->rq_flags & RQF_STARTED)) { 6470 if (rq == bfqd->waited_rq) 6471 bfq_update_inject_limit(bfqd, bfqq); 6472 6473 bfq_completed_request(bfqq, bfqd); 6474 } 6475 bfq_finish_requeue_request_body(bfqq); 6476 spin_unlock_irqrestore(&bfqd->lock, flags); 6477 6478 /* 6479 * Reset private fields. In case of a requeue, this allows 6480 * this function to correctly do nothing if it is spuriously 6481 * invoked again on this same request (see the check at the 6482 * beginning of the function). Probably, a better general 6483 * design would be to prevent blk-mq from invoking the requeue 6484 * or finish hooks of an elevator, for a request that is not 6485 * referred by that elevator. 6486 * 6487 * Resetting the following fields would break the 6488 * request-insertion logic if rq is re-inserted into a bfq 6489 * internal queue, without a re-preparation. Here we assume 6490 * that re-insertions of requeued requests, without 6491 * re-preparation, can happen only for pass_through or at_head 6492 * requests (which are not re-inserted into bfq internal 6493 * queues). 6494 */ 6495 rq->elv.priv[0] = NULL; 6496 rq->elv.priv[1] = NULL; 6497} 6498 6499/* 6500 * Removes the association between the current task and bfqq, assuming 6501 * that bic points to the bfq iocontext of the task. 6502 * Returns NULL if a new bfqq should be allocated, or the old bfqq if this 6503 * was the last process referring to that bfqq. 6504 */ 6505static struct bfq_queue * 6506bfq_split_bfqq(struct bfq_io_cq *bic, struct bfq_queue *bfqq) 6507{ 6508 bfq_log_bfqq(bfqq->bfqd, bfqq, "splitting queue"); 6509 6510 if (bfqq_process_refs(bfqq) == 1) { 6511 bfqq->pid = current->pid; 6512 bfq_clear_bfqq_coop(bfqq); 6513 bfq_clear_bfqq_split_coop(bfqq); 6514 return bfqq; 6515 } 6516 6517 bic_set_bfqq(bic, NULL, 1); 6518 6519 bfq_put_cooperator(bfqq); 6520 6521 bfq_release_process_ref(bfqq->bfqd, bfqq); 6522 return NULL; 6523} 6524 6525static struct bfq_queue *bfq_get_bfqq_handle_split(struct bfq_data *bfqd, 6526 struct bfq_io_cq *bic, 6527 struct bio *bio, 6528 bool split, bool is_sync, 6529 bool *new_queue) 6530{ 6531 struct bfq_queue *bfqq = bic_to_bfqq(bic, is_sync); 6532 6533 if (likely(bfqq && bfqq != &bfqd->oom_bfqq)) 6534 return bfqq; 6535 6536 if (new_queue) 6537 *new_queue = true; 6538 6539 if (bfqq) 6540 bfq_put_queue(bfqq); 6541 bfqq = bfq_get_queue(bfqd, bio, is_sync, bic, split); 6542 6543 bic_set_bfqq(bic, bfqq, is_sync); 6544 if (split && is_sync) { 6545 if ((bic->was_in_burst_list && bfqd->large_burst) || 6546 bic->saved_in_large_burst) 6547 bfq_mark_bfqq_in_large_burst(bfqq); 6548 else { 6549 bfq_clear_bfqq_in_large_burst(bfqq); 6550 if (bic->was_in_burst_list) 6551 /* 6552 * If bfqq was in the current 6553 * burst list before being 6554 * merged, then we have to add 6555 * it back. And we do not need 6556 * to increase burst_size, as 6557 * we did not decrement 6558 * burst_size when we removed 6559 * bfqq from the burst list as 6560 * a consequence of a merge 6561 * (see comments in 6562 * bfq_put_queue). In this 6563 * respect, it would be rather 6564 * costly to know whether the 6565 * current burst list is still 6566 * the same burst list from 6567 * which bfqq was removed on 6568 * the merge. To avoid this 6569 * cost, if bfqq was in a 6570 * burst list, then we add 6571 * bfqq to the current burst 6572 * list without any further 6573 * check. This can cause 6574 * inappropriate insertions, 6575 * but rarely enough to not 6576 * harm the detection of large 6577 * bursts significantly. 6578 */ 6579 hlist_add_head(&bfqq->burst_list_node, 6580 &bfqd->burst_list); 6581 } 6582 bfqq->split_time = jiffies; 6583 } 6584 6585 return bfqq; 6586} 6587 6588/* 6589 * Only reset private fields. The actual request preparation will be 6590 * performed by bfq_init_rq, when rq is either inserted or merged. See 6591 * comments on bfq_init_rq for the reason behind this delayed 6592 * preparation. 6593 */ 6594static void bfq_prepare_request(struct request *rq, struct bio *bio) 6595{ 6596 /* 6597 * Regardless of whether we have an icq attached, we have to 6598 * clear the scheduler pointers, as they might point to 6599 * previously allocated bic/bfqq structs. 6600 */ 6601 rq->elv.priv[0] = rq->elv.priv[1] = NULL; 6602} 6603 6604/* 6605 * If needed, init rq, allocate bfq data structures associated with 6606 * rq, and increment reference counters in the destination bfq_queue 6607 * for rq. Return the destination bfq_queue for rq, or NULL is rq is 6608 * not associated with any bfq_queue. 6609 * 6610 * This function is invoked by the functions that perform rq insertion 6611 * or merging. One may have expected the above preparation operations 6612 * to be performed in bfq_prepare_request, and not delayed to when rq 6613 * is inserted or merged. The rationale behind this delayed 6614 * preparation is that, after the prepare_request hook is invoked for 6615 * rq, rq may still be transformed into a request with no icq, i.e., a 6616 * request not associated with any queue. No bfq hook is invoked to 6617 * signal this tranformation. As a consequence, should these 6618 * preparation operations be performed when the prepare_request hook 6619 * is invoked, and should rq be transformed one moment later, bfq 6620 * would end up in an inconsistent state, because it would have 6621 * incremented some queue counters for an rq destined to 6622 * transformation, without any chance to correctly lower these 6623 * counters back. In contrast, no transformation can still happen for 6624 * rq after rq has been inserted or merged. So, it is safe to execute 6625 * these preparation operations when rq is finally inserted or merged. 6626 */ 6627static struct bfq_queue *bfq_init_rq(struct request *rq) 6628{ 6629 struct request_queue *q = rq->q; 6630 struct bio *bio = rq->bio; 6631 struct bfq_data *bfqd = q->elevator->elevator_data; 6632 struct bfq_io_cq *bic; 6633 const int is_sync = rq_is_sync(rq); 6634 struct bfq_queue *bfqq; 6635 bool new_queue = false; 6636 bool bfqq_already_existing = false, split = false; 6637 6638 if (unlikely(!rq->elv.icq)) 6639 return NULL; 6640 6641 /* 6642 * Assuming that elv.priv[1] is set only if everything is set 6643 * for this rq. This holds true, because this function is 6644 * invoked only for insertion or merging, and, after such 6645 * events, a request cannot be manipulated any longer before 6646 * being removed from bfq. 6647 */ 6648 if (rq->elv.priv[1]) 6649 return rq->elv.priv[1]; 6650 6651 bic = icq_to_bic(rq->elv.icq); 6652 6653 bfq_check_ioprio_change(bic, bio); 6654 6655 bfq_bic_update_cgroup(bic, bio); 6656 6657 bfqq = bfq_get_bfqq_handle_split(bfqd, bic, bio, false, is_sync, 6658 &new_queue); 6659 6660 if (likely(!new_queue)) { 6661 /* If the queue was seeky for too long, break it apart. */ 6662 if (bfq_bfqq_coop(bfqq) && bfq_bfqq_split_coop(bfqq) && 6663 !bic->stably_merged) { 6664 struct bfq_queue *old_bfqq = bfqq; 6665 6666 /* Update bic before losing reference to bfqq */ 6667 if (bfq_bfqq_in_large_burst(bfqq)) 6668 bic->saved_in_large_burst = true; 6669 6670 bfqq = bfq_split_bfqq(bic, bfqq); 6671 split = true; 6672 6673 if (!bfqq) { 6674 bfqq = bfq_get_bfqq_handle_split(bfqd, bic, bio, 6675 true, is_sync, 6676 NULL); 6677 bfqq->waker_bfqq = old_bfqq->waker_bfqq; 6678 bfqq->tentative_waker_bfqq = NULL; 6679 6680 /* 6681 * If the waker queue disappears, then 6682 * new_bfqq->waker_bfqq must be 6683 * reset. So insert new_bfqq into the 6684 * woken_list of the waker. See 6685 * bfq_check_waker for details. 6686 */ 6687 if (bfqq->waker_bfqq) 6688 hlist_add_head(&bfqq->woken_list_node, 6689 &bfqq->waker_bfqq->woken_list); 6690 } else 6691 bfqq_already_existing = true; 6692 } 6693 } 6694 6695 bfqq->allocated++; 6696 bfqq->ref++; 6697 bfq_log_bfqq(bfqd, bfqq, "get_request %p: bfqq %p, %d", 6698 rq, bfqq, bfqq->ref); 6699 6700 rq->elv.priv[0] = bic; 6701 rq->elv.priv[1] = bfqq; 6702 6703 /* 6704 * If a bfq_queue has only one process reference, it is owned 6705 * by only this bic: we can then set bfqq->bic = bic. in 6706 * addition, if the queue has also just been split, we have to 6707 * resume its state. 6708 */ 6709 if (likely(bfqq != &bfqd->oom_bfqq) && bfqq_process_refs(bfqq) == 1) { 6710 bfqq->bic = bic; 6711 if (split) { 6712 /* 6713 * The queue has just been split from a shared 6714 * queue: restore the idle window and the 6715 * possible weight raising period. 6716 */ 6717 bfq_bfqq_resume_state(bfqq, bfqd, bic, 6718 bfqq_already_existing); 6719 } 6720 } 6721 6722 /* 6723 * Consider bfqq as possibly belonging to a burst of newly 6724 * created queues only if: 6725 * 1) A burst is actually happening (bfqd->burst_size > 0) 6726 * or 6727 * 2) There is no other active queue. In fact, if, in 6728 * contrast, there are active queues not belonging to the 6729 * possible burst bfqq may belong to, then there is no gain 6730 * in considering bfqq as belonging to a burst, and 6731 * therefore in not weight-raising bfqq. See comments on 6732 * bfq_handle_burst(). 6733 * 6734 * This filtering also helps eliminating false positives, 6735 * occurring when bfqq does not belong to an actual large 6736 * burst, but some background task (e.g., a service) happens 6737 * to trigger the creation of new queues very close to when 6738 * bfqq and its possible companion queues are created. See 6739 * comments on bfq_handle_burst() for further details also on 6740 * this issue. 6741 */ 6742 if (unlikely(bfq_bfqq_just_created(bfqq) && 6743 (bfqd->burst_size > 0 || 6744 bfq_tot_busy_queues(bfqd) == 0))) 6745 bfq_handle_burst(bfqd, bfqq); 6746 6747 return bfqq; 6748} 6749 6750static void 6751bfq_idle_slice_timer_body(struct bfq_data *bfqd, struct bfq_queue *bfqq) 6752{ 6753 enum bfqq_expiration reason; 6754 unsigned long flags; 6755 6756 spin_lock_irqsave(&bfqd->lock, flags); 6757 6758 /* 6759 * Considering that bfqq may be in race, we should firstly check 6760 * whether bfqq is in service before doing something on it. If 6761 * the bfqq in race is not in service, it has already been expired 6762 * through __bfq_bfqq_expire func and its wait_request flags has 6763 * been cleared in __bfq_bfqd_reset_in_service func. 6764 */ 6765 if (bfqq != bfqd->in_service_queue) { 6766 spin_unlock_irqrestore(&bfqd->lock, flags); 6767 return; 6768 } 6769 6770 bfq_clear_bfqq_wait_request(bfqq); 6771 6772 if (bfq_bfqq_budget_timeout(bfqq)) 6773 /* 6774 * Also here the queue can be safely expired 6775 * for budget timeout without wasting 6776 * guarantees 6777 */ 6778 reason = BFQQE_BUDGET_TIMEOUT; 6779 else if (bfqq->queued[0] == 0 && bfqq->queued[1] == 0) 6780 /* 6781 * The queue may not be empty upon timer expiration, 6782 * because we may not disable the timer when the 6783 * first request of the in-service queue arrives 6784 * during disk idling. 6785 */ 6786 reason = BFQQE_TOO_IDLE; 6787 else 6788 goto schedule_dispatch; 6789 6790 bfq_bfqq_expire(bfqd, bfqq, true, reason); 6791 6792schedule_dispatch: 6793 spin_unlock_irqrestore(&bfqd->lock, flags); 6794 bfq_schedule_dispatch(bfqd); 6795} 6796 6797/* 6798 * Handler of the expiration of the timer running if the in-service queue 6799 * is idling inside its time slice. 6800 */ 6801static enum hrtimer_restart bfq_idle_slice_timer(struct hrtimer *timer) 6802{ 6803 struct bfq_data *bfqd = container_of(timer, struct bfq_data, 6804 idle_slice_timer); 6805 struct bfq_queue *bfqq = bfqd->in_service_queue; 6806 6807 /* 6808 * Theoretical race here: the in-service queue can be NULL or 6809 * different from the queue that was idling if a new request 6810 * arrives for the current queue and there is a full dispatch 6811 * cycle that changes the in-service queue. This can hardly 6812 * happen, but in the worst case we just expire a queue too 6813 * early. 6814 */ 6815 if (bfqq) 6816 bfq_idle_slice_timer_body(bfqd, bfqq); 6817 6818 return HRTIMER_NORESTART; 6819} 6820 6821static void __bfq_put_async_bfqq(struct bfq_data *bfqd, 6822 struct bfq_queue **bfqq_ptr) 6823{ 6824 struct bfq_queue *bfqq = *bfqq_ptr; 6825 6826 bfq_log(bfqd, "put_async_bfqq: %p", bfqq); 6827 if (bfqq) { 6828 bfq_bfqq_move(bfqd, bfqq, bfqd->root_group); 6829 6830 bfq_log_bfqq(bfqd, bfqq, "put_async_bfqq: putting %p, %d", 6831 bfqq, bfqq->ref); 6832 bfq_put_queue(bfqq); 6833 *bfqq_ptr = NULL; 6834 } 6835} 6836 6837/* 6838 * Release all the bfqg references to its async queues. If we are 6839 * deallocating the group these queues may still contain requests, so 6840 * we reparent them to the root cgroup (i.e., the only one that will 6841 * exist for sure until all the requests on a device are gone). 6842 */ 6843void bfq_put_async_queues(struct bfq_data *bfqd, struct bfq_group *bfqg) 6844{ 6845 int i, j; 6846 6847 for (i = 0; i < 2; i++) 6848 for (j = 0; j < IOPRIO_BE_NR; j++) 6849 __bfq_put_async_bfqq(bfqd, &bfqg->async_bfqq[i][j]); 6850 6851 __bfq_put_async_bfqq(bfqd, &bfqg->async_idle_bfqq); 6852} 6853 6854/* 6855 * See the comments on bfq_limit_depth for the purpose of 6856 * the depths set in the function. Return minimum shallow depth we'll use. 6857 */ 6858static unsigned int bfq_update_depths(struct bfq_data *bfqd, 6859 struct sbitmap_queue *bt) 6860{ 6861 unsigned int i, j, min_shallow = UINT_MAX; 6862 6863 /* 6864 * In-word depths if no bfq_queue is being weight-raised: 6865 * leaving 25% of tags only for sync reads. 6866 * 6867 * In next formulas, right-shift the value 6868 * (1U<<bt->sb.shift), instead of computing directly 6869 * (1U<<(bt->sb.shift - something)), to be robust against 6870 * any possible value of bt->sb.shift, without having to 6871 * limit 'something'. 6872 */ 6873 /* no more than 50% of tags for async I/O */ 6874 bfqd->word_depths[0][0] = max((1U << bt->sb.shift) >> 1, 1U); 6875 /* 6876 * no more than 75% of tags for sync writes (25% extra tags 6877 * w.r.t. async I/O, to prevent async I/O from starving sync 6878 * writes) 6879 */ 6880 bfqd->word_depths[0][1] = max(((1U << bt->sb.shift) * 3) >> 2, 1U); 6881 6882 /* 6883 * In-word depths in case some bfq_queue is being weight- 6884 * raised: leaving ~63% of tags for sync reads. This is the 6885 * highest percentage for which, in our tests, application 6886 * start-up times didn't suffer from any regression due to tag 6887 * shortage. 6888 */ 6889 /* no more than ~18% of tags for async I/O */ 6890 bfqd->word_depths[1][0] = max(((1U << bt->sb.shift) * 3) >> 4, 1U); 6891 /* no more than ~37% of tags for sync writes (~20% extra tags) */ 6892 bfqd->word_depths[1][1] = max(((1U << bt->sb.shift) * 6) >> 4, 1U); 6893 6894 for (i = 0; i < 2; i++) 6895 for (j = 0; j < 2; j++) 6896 min_shallow = min(min_shallow, bfqd->word_depths[i][j]); 6897 6898 return min_shallow; 6899} 6900 6901static void bfq_depth_updated(struct blk_mq_hw_ctx *hctx) 6902{ 6903 struct bfq_data *bfqd = hctx->queue->elevator->elevator_data; 6904 struct blk_mq_tags *tags = hctx->sched_tags; 6905 unsigned int min_shallow; 6906 6907 min_shallow = bfq_update_depths(bfqd, tags->bitmap_tags); 6908 sbitmap_queue_min_shallow_depth(tags->bitmap_tags, min_shallow); 6909} 6910 6911static int bfq_init_hctx(struct blk_mq_hw_ctx *hctx, unsigned int index) 6912{ 6913 bfq_depth_updated(hctx); 6914 return 0; 6915} 6916 6917static void bfq_exit_queue(struct elevator_queue *e) 6918{ 6919 struct bfq_data *bfqd = e->elevator_data; 6920 struct bfq_queue *bfqq, *n; 6921 6922 hrtimer_cancel(&bfqd->idle_slice_timer); 6923 6924 spin_lock_irq(&bfqd->lock); 6925 list_for_each_entry_safe(bfqq, n, &bfqd->idle_list, bfqq_list) 6926 bfq_deactivate_bfqq(bfqd, bfqq, false, false); 6927 spin_unlock_irq(&bfqd->lock); 6928 6929 hrtimer_cancel(&bfqd->idle_slice_timer); 6930 6931 /* release oom-queue reference to root group */ 6932 bfqg_and_blkg_put(bfqd->root_group); 6933 6934#ifdef CONFIG_BFQ_GROUP_IOSCHED 6935 blkcg_deactivate_policy(bfqd->queue, &blkcg_policy_bfq); 6936#else 6937 spin_lock_irq(&bfqd->lock); 6938 bfq_put_async_queues(bfqd, bfqd->root_group); 6939 kfree(bfqd->root_group); 6940 spin_unlock_irq(&bfqd->lock); 6941#endif 6942 6943 kfree(bfqd); 6944} 6945 6946static void bfq_init_root_group(struct bfq_group *root_group, 6947 struct bfq_data *bfqd) 6948{ 6949 int i; 6950 6951#ifdef CONFIG_BFQ_GROUP_IOSCHED 6952 root_group->entity.parent = NULL; 6953 root_group->my_entity = NULL; 6954 root_group->bfqd = bfqd; 6955#endif 6956 root_group->rq_pos_tree = RB_ROOT; 6957 for (i = 0; i < BFQ_IOPRIO_CLASSES; i++) 6958 root_group->sched_data.service_tree[i] = BFQ_SERVICE_TREE_INIT; 6959 root_group->sched_data.bfq_class_idle_last_service = jiffies; 6960} 6961 6962static int bfq_init_queue(struct request_queue *q, struct elevator_type *e) 6963{ 6964 struct bfq_data *bfqd; 6965 struct elevator_queue *eq; 6966 6967 eq = elevator_alloc(q, e); 6968 if (!eq) 6969 return -ENOMEM; 6970 6971 bfqd = kzalloc_node(sizeof(*bfqd), GFP_KERNEL, q->node); 6972 if (!bfqd) { 6973 kobject_put(&eq->kobj); 6974 return -ENOMEM; 6975 } 6976 eq->elevator_data = bfqd; 6977 6978 spin_lock_irq(&q->queue_lock); 6979 q->elevator = eq; 6980 spin_unlock_irq(&q->queue_lock); 6981 6982 /* 6983 * Our fallback bfqq if bfq_find_alloc_queue() runs into OOM issues. 6984 * Grab a permanent reference to it, so that the normal code flow 6985 * will not attempt to free it. 6986 */ 6987 bfq_init_bfqq(bfqd, &bfqd->oom_bfqq, NULL, 1, 0); 6988 bfqd->oom_bfqq.ref++; 6989 bfqd->oom_bfqq.new_ioprio = BFQ_DEFAULT_QUEUE_IOPRIO; 6990 bfqd->oom_bfqq.new_ioprio_class = IOPRIO_CLASS_BE; 6991 bfqd->oom_bfqq.entity.new_weight = 6992 bfq_ioprio_to_weight(bfqd->oom_bfqq.new_ioprio); 6993 6994 /* oom_bfqq does not participate to bursts */ 6995 bfq_clear_bfqq_just_created(&bfqd->oom_bfqq); 6996 6997 /* 6998 * Trigger weight initialization, according to ioprio, at the 6999 * oom_bfqq's first activation. The oom_bfqq's ioprio and ioprio 7000 * class won't be changed any more.
7001 */ 7002 bfqd->oom_bfqq.entity.prio_changed = 1; 7003 7004 bfqd->queue = q; 7005 7006 INIT_LIST_HEAD(&bfqd->dispatch); 7007 7008 hrtimer_init(&bfqd->idle_slice_timer, CLOCK_MONOTONIC, 7009 HRTIMER_MODE_REL); 7010 bfqd->idle_slice_timer.function = bfq_idle_slice_timer; 7011 7012 bfqd->queue_weights_tree = RB_ROOT_CACHED; 7013 bfqd->num_groups_with_pending_reqs = 0; 7014 7015 INIT_LIST_HEAD(&bfqd->active_list); 7016 INIT_LIST_HEAD(&bfqd->idle_list); 7017 INIT_HLIST_HEAD(&bfqd->burst_list); 7018 7019 bfqd->hw_tag = -1; 7020 bfqd->nonrot_with_queueing = blk_queue_nonrot(bfqd->queue); 7021 7022 bfqd->bfq_max_budget = bfq_default_max_budget; 7023 7024 bfqd->bfq_fifo_expire[0] = bfq_fifo_expire[0]; 7025 bfqd->bfq_fifo_expire[1] = bfq_fifo_expire[1]; 7026 bfqd->bfq_back_max = bfq_back_max; 7027 bfqd->bfq_back_penalty = bfq_back_penalty; 7028 bfqd->bfq_slice_idle = bfq_slice_idle; 7029 bfqd->bfq_timeout = bfq_timeout; 7030 7031 bfqd->bfq_large_burst_thresh = 8; 7032 bfqd->bfq_burst_interval = msecs_to_jiffies(180); 7033 7034 bfqd->low_latency = true; 7035 7036 /* 7037 * Trade-off between responsiveness and fairness. 7038 */ 7039 bfqd->bfq_wr_coeff = 30; 7040 bfqd->bfq_wr_rt_max_time = msecs_to_jiffies(300); 7041 bfqd->bfq_wr_max_time = 0; 7042 bfqd->bfq_wr_min_idle_time = msecs_to_jiffies(2000); 7043 bfqd->bfq_wr_min_inter_arr_async = msecs_to_jiffies(500); 7044 bfqd->bfq_wr_max_softrt_rate = 7000; /* 7045 * Approximate rate required 7046 * to playback or record a 7047 * high-definition compressed 7048 * video. 7049 */ 7050 bfqd->wr_busy_queues = 0; 7051 7052 /* 7053 * Begin by assuming, optimistically, that the device peak 7054 * rate is equal to 2/3 of the highest reference rate. 7055 */ 7056 bfqd->rate_dur_prod = ref_rate[blk_queue_nonrot(bfqd->queue)] * 7057 ref_wr_duration[blk_queue_nonrot(bfqd->queue)]; 7058 bfqd->peak_rate = ref_rate[blk_queue_nonrot(bfqd->queue)] * 2 / 3; 7059 7060 spin_lock_init(&bfqd->lock); 7061 7062 /* 7063 * The invocation of the next bfq_create_group_hierarchy 7064 * function is the head of a chain of function calls 7065 * (bfq_create_group_hierarchy->blkcg_activate_policy-> 7066 * blk_mq_freeze_queue) that may lead to the invocation of the 7067 * has_work hook function. For this reason, 7068 * bfq_create_group_hierarchy is invoked only after all 7069 * scheduler data has been initialized, apart from the fields 7070 * that can be initialized only after invoking 7071 * bfq_create_group_hierarchy. This, in particular, enables 7072 * has_work to correctly return false. Of course, to avoid 7073 * other inconsistencies, the blk-mq stack must then refrain 7074 * from invoking further scheduler hooks before this init 7075 * function is finished. 7076 */ 7077 bfqd->root_group = bfq_create_group_hierarchy(bfqd, q->node); 7078 if (!bfqd->root_group) 7079 goto out_free; 7080 bfq_init_root_group(bfqd->root_group, bfqd); 7081 bfq_init_entity(&bfqd->oom_bfqq.entity, bfqd->root_group); 7082 7083 wbt_disable_default(q); 7084 return 0; 7085 7086out_free: 7087 kfree(bfqd); 7088 kobject_put(&eq->kobj); 7089 return -ENOMEM; 7090} 7091 7092static void bfq_slab_kill(void) 7093{ 7094 kmem_cache_destroy(bfq_pool); 7095} 7096 7097static int __init bfq_slab_setup(void) 7098{ 7099 bfq_pool = KMEM_CACHE(bfq_queue, 0); 7100 if (!bfq_pool) 7101 return -ENOMEM; 7102 return 0; 7103} 7104 7105static ssize_t bfq_var_show(unsigned int var, char *page) 7106{ 7107 return sprintf(page, "%u\n", var); 7108} 7109 7110static int bfq_var_store(unsigned long *var, const char *page) 7111{ 7112 unsigned long new_val; 7113 int ret = kstrtoul(page, 10, &new_val); 7114 7115 if (ret) 7116 return ret; 7117 *var = new_val; 7118 return 0; 7119} 7120 7121#define SHOW_FUNCTION(__FUNC, __VAR, __CONV) \ 7122static ssize_t __FUNC(struct elevator_queue *e, char *page) \ 7123{ \ 7124 struct bfq_data *bfqd = e->elevator_data; \ 7125 u64 __data = __VAR; \ 7126 if (__CONV == 1) \ 7127 __data = jiffies_to_msecs(__data); \ 7128 else if (__CONV == 2) \ 7129 __data = div_u64(__data, NSEC_PER_MSEC); \ 7130 return bfq_var_show(__data, (page)); \ 7131} 7132SHOW_FUNCTION(bfq_fifo_expire_sync_show, bfqd->bfq_fifo_expire[1], 2); 7133SHOW_FUNCTION(bfq_fifo_expire_async_show, bfqd->bfq_fifo_expire[0], 2); 7134SHOW_FUNCTION(bfq_back_seek_max_show, bfqd->bfq_back_max, 0); 7135SHOW_FUNCTION(bfq_back_seek_penalty_show, bfqd->bfq_back_penalty, 0); 7136SHOW_FUNCTION(bfq_slice_idle_show, bfqd->bfq_slice_idle, 2); 7137SHOW_FUNCTION(bfq_max_budget_show, bfqd->bfq_user_max_budget, 0); 7138SHOW_FUNCTION(bfq_timeout_sync_show, bfqd->bfq_timeout, 1); 7139SHOW_FUNCTION(bfq_strict_guarantees_show, bfqd->strict_guarantees, 0); 7140SHOW_FUNCTION(bfq_low_latency_show, bfqd->low_latency, 0); 7141#undef SHOW_FUNCTION 7142 7143#define USEC_SHOW_FUNCTION(__FUNC, __VAR) \ 7144static ssize_t __FUNC(struct elevator_queue *e, char *page) \ 7145{ \ 7146 struct bfq_data *bfqd = e->elevator_data; \ 7147 u64 __data = __VAR; \ 7148 __data = div_u64(__data, NSEC_PER_USEC); \ 7149 return bfq_var_show(__data, (page)); \ 7150} 7151USEC_SHOW_FUNCTION(bfq_slice_idle_us_show, bfqd->bfq_slice_idle); 7152#undef USEC_SHOW_FUNCTION 7153 7154#define STORE_FUNCTION(__FUNC, __PTR, MIN, MAX, __CONV) \ 7155static ssize_t \ 7156__FUNC(struct elevator_queue *e, const char *page, size_t count) \ 7157{ \ 7158 struct bfq_data *bfqd = e->elevator_data; \ 7159 unsigned long __data, __min = (MIN), __max = (MAX); \ 7160 int ret; \ 7161 \ 7162 ret = bfq_var_store(&__data, (page)); \ 7163 if (ret) \ 7164 return ret; \ 7165 if (__data < __min) \ 7166 __data = __min; \ 7167 else if (__data > __max) \ 7168 __data = __max; \ 7169 if (__CONV == 1) \ 7170 *(__PTR) = msecs_to_jiffies(__data); \ 7171 else if (__CONV == 2) \ 7172 *(__PTR) = (u64)__data * NSEC_PER_MSEC; \ 7173 else \ 7174 *(__PTR) = __data; \ 7175 return count; \ 7176} 7177STORE_FUNCTION(bfq_fifo_expire_sync_store, &bfqd->bfq_fifo_expire[1], 1, 7178 INT_MAX, 2); 7179STORE_FUNCTION(bfq_fifo_expire_async_store, &bfqd->bfq_fifo_expire[0], 1, 7180 INT_MAX, 2); 7181STORE_FUNCTION(bfq_back_seek_max_store, &bfqd->bfq_back_max, 0, INT_MAX, 0); 7182STORE_FUNCTION(bfq_back_seek_penalty_store, &bfqd->bfq_back_penalty, 1, 7183 INT_MAX, 0); 7184STORE_FUNCTION(bfq_slice_idle_store, &bfqd->bfq_slice_idle, 0, INT_MAX, 2); 7185#undef STORE_FUNCTION 7186 7187#define USEC_STORE_FUNCTION(__FUNC, __PTR, MIN, MAX) \ 7188static ssize_t __FUNC(struct elevator_queue *e, const char *page, size_t count)\ 7189{ \ 7190 struct bfq_data *bfqd = e->elevator_data; \ 7191 unsigned long __data, __min = (MIN), __max = (MAX); \ 7192 int ret; \ 7193 \ 7194 ret = bfq_var_store(&__data, (page)); \ 7195 if (ret) \ 7196 return ret; \ 7197 if (__data < __min) \ 7198 __data = __min; \ 7199 else if (__data > __max) \ 7200 __data = __max; \ 7201 *(__PTR) = (u64)__data * NSEC_PER_USEC; \ 7202 return count; \ 7203} 7204USEC_STORE_FUNCTION(bfq_slice_idle_us_store, &bfqd->bfq_slice_idle, 0, 7205 UINT_MAX); 7206#undef USEC_STORE_FUNCTION 7207 7208static ssize_t bfq_max_budget_store(struct elevator_queue *e, 7209 const char *page, size_t count) 7210{ 7211 struct bfq_data *bfqd = e->elevator_data; 7212 unsigned long __data; 7213 int ret; 7214 7215 ret = bfq_var_store(&__data, (page)); 7216 if (ret) 7217 return ret; 7218 7219 if (__data == 0) 7220 bfqd->bfq_max_budget = bfq_calc_max_budget(bfqd); 7221 else { 7222 if (__data > INT_MAX) 7223 __data = INT_MAX; 7224 bfqd->bfq_max_budget = __data; 7225 } 7226 7227 bfqd->bfq_user_max_budget = __data; 7228 7229 return count; 7230} 7231 7232/* 7233 * Leaving this name to preserve name compatibility with cfq 7234 * parameters, but this timeout is used for both sync and async. 7235 */ 7236static ssize_t bfq_timeout_sync_store(struct elevator_queue *e, 7237 const char *page, size_t count) 7238{ 7239 struct bfq_data *bfqd = e->elevator_data; 7240 unsigned long __data; 7241 int ret; 7242 7243 ret = bfq_var_store(&__data, (page)); 7244 if (ret) 7245 return ret; 7246 7247 if (__data < 1) 7248 __data = 1; 7249 else if (__data > INT_MAX) 7250 __data = INT_MAX; 7251 7252 bfqd->bfq_timeout = msecs_to_jiffies(__data); 7253 if (bfqd->bfq_user_max_budget == 0) 7254 bfqd->bfq_max_budget = bfq_calc_max_budget(bfqd); 7255 7256 return count; 7257} 7258 7259static ssize_t bfq_strict_guarantees_store(struct elevator_queue *e, 7260 const char *page, size_t count) 7261{ 7262 struct bfq_data *bfqd = e->elevator_data; 7263 unsigned long __data; 7264 int ret; 7265 7266 ret = bfq_var_store(&__data, (page)); 7267 if (ret) 7268 return ret; 7269 7270 if (__data > 1) 7271 __data = 1; 7272 if (!bfqd->strict_guarantees && __data == 1 7273 && bfqd->bfq_slice_idle < 8 * NSEC_PER_MSEC) 7274 bfqd->bfq_slice_idle = 8 * NSEC_PER_MSEC; 7275 7276 bfqd->strict_guarantees = __data; 7277 7278 return count; 7279} 7280 7281static ssize_t bfq_low_latency_store(struct elevator_queue *e, 7282 const char *page, size_t count) 7283{ 7284 struct bfq_data *bfqd = e->elevator_data; 7285 unsigned long __data; 7286 int ret; 7287 7288 ret = bfq_var_store(&__data, (page)); 7289 if (ret) 7290 return ret; 7291 7292 if (__data > 1) 7293 __data = 1; 7294 if (__data == 0 && bfqd->low_latency != 0) 7295 bfq_end_wr(bfqd); 7296 bfqd->low_latency = __data; 7297 7298 return count; 7299} 7300 7301#define BFQ_ATTR(name) \ 7302 __ATTR(name, 0644, bfq_##name##_show, bfq_##name##_store) 7303 7304static struct elv_fs_entry bfq_attrs[] = { 7305 BFQ_ATTR(fifo_expire_sync), 7306 BFQ_ATTR(fifo_expire_async), 7307 BFQ_ATTR(back_seek_max), 7308 BFQ_ATTR(back_seek_penalty), 7309 BFQ_ATTR(slice_idle), 7310 BFQ_ATTR(slice_idle_us), 7311 BFQ_ATTR(max_budget), 7312 BFQ_ATTR(timeout_sync), 7313 BFQ_ATTR(strict_guarantees), 7314 BFQ_ATTR(low_latency), 7315 __ATTR_NULL 7316}; 7317 7318static struct elevator_type iosched_bfq_mq = { 7319 .ops = { 7320 .limit_depth = bfq_limit_depth, 7321 .prepare_request = bfq_prepare_request, 7322 .requeue_request = bfq_finish_requeue_request, 7323 .finish_request = bfq_finish_requeue_request, 7324 .exit_icq = bfq_exit_icq, 7325 .insert_requests = bfq_insert_requests, 7326 .dispatch_request = bfq_dispatch_request, 7327 .next_request = elv_rb_latter_request, 7328 .former_request = elv_rb_former_request, 7329 .allow_merge = bfq_allow_bio_merge, 7330 .bio_merge = bfq_bio_merge, 7331 .request_merge = bfq_request_merge, 7332 .requests_merged = bfq_requests_merged, 7333 .request_merged = bfq_request_merged, 7334 .has_work = bfq_has_work, 7335 .depth_updated = bfq_depth_updated, 7336 .init_hctx = bfq_init_hctx, 7337 .init_sched = bfq_init_queue, 7338 .exit_sched = bfq_exit_queue, 7339 }, 7340 7341 .icq_size = sizeof(struct bfq_io_cq), 7342 .icq_align = __alignof__(struct bfq_io_cq), 7343 .elevator_attrs = bfq_attrs, 7344 .elevator_name = "bfq", 7345 .elevator_owner = THIS_MODULE, 7346}; 7347MODULE_ALIAS("bfq-iosched"); 7348 7349static int __init bfq_init(void) 7350{ 7351 int ret; 7352 7353#ifdef CONFIG_BFQ_GROUP_IOSCHED 7354 ret = blkcg_policy_register(&blkcg_policy_bfq); 7355 if (ret) 7356 return ret; 7357#endif 7358 7359 ret = -ENOMEM; 7360 if (bfq_slab_setup()) 7361 goto err_pol_unreg; 7362 7363 /* 7364 * Times to load large popular applications for the typical 7365 * systems installed on the reference devices (see the 7366 * comments before the definition of the next 7367 * array). Actually, we use slightly lower values, as the 7368 * estimated peak rate tends to be smaller than the actual 7369 * peak rate. The reason for this last fact is that estimates 7370 * are computed over much shorter time intervals than the long 7371 * intervals typically used for benchmarking. Why? First, to 7372 * adapt more quickly to variations. Second, because an I/O 7373 * scheduler cannot rely on a peak-rate-evaluation workload to 7374 * be run for a long time. 7375 */ 7376 ref_wr_duration[0] = msecs_to_jiffies(7000); /* actually 8 sec */ 7377 ref_wr_duration[1] = msecs_to_jiffies(2500); /* actually 3 sec */ 7378 7379 ret = elv_register(&iosched_bfq_mq); 7380 if (ret) 7381 goto slab_kill; 7382 7383 return 0; 7384 7385slab_kill: 7386 bfq_slab_kill(); 7387err_pol_unreg: 7388#ifdef CONFIG_BFQ_GROUP_IOSCHED 7389 blkcg_policy_unregister(&blkcg_policy_bfq); 7390#endif 7391 return ret; 7392} 7393 7394static void __exit bfq_exit(void) 7395{ 7396 elv_unregister(&iosched_bfq_mq); 7397#ifdef CONFIG_BFQ_GROUP_IOSCHED 7398 blkcg_policy_unregister(&blkcg_policy_bfq); 7399#endif 7400 bfq_slab_kill(); 7401} 7402 7403module_init(bfq_init); 7404module_exit(bfq_exit); 7405 7406MODULE_AUTHOR("Paolo Valente"); 7407MODULE_LICENSE("GPL"); 7408MODULE_DESCRIPTION("MQ Budget Fair Queueing I/O Scheduler"); 7409