]> git.proxmox.com Git - mirror_ubuntu-artful-kernel.git/blob - block/cfq-iosched.c
UBUNTU: Ubuntu-4.13.0-45.50
[mirror_ubuntu-artful-kernel.git] / block / cfq-iosched.c
1 /*
2 * CFQ, or complete fairness queueing, disk scheduler.
3 *
4 * Based on ideas from a previously unfinished io
5 * scheduler (round robin per-process disk scheduling) and Andrea Arcangeli.
6 *
7 * Copyright (C) 2003 Jens Axboe <axboe@kernel.dk>
8 */
9 #include <linux/module.h>
10 #include <linux/slab.h>
11 #include <linux/sched/clock.h>
12 #include <linux/blkdev.h>
13 #include <linux/elevator.h>
14 #include <linux/ktime.h>
15 #include <linux/rbtree.h>
16 #include <linux/ioprio.h>
17 #include <linux/blktrace_api.h>
18 #include <linux/blk-cgroup.h>
19 #include "blk.h"
20 #include "blk-wbt.h"
21
22 /*
23 * tunables
24 */
25 /* max queue in one round of service */
26 static const int cfq_quantum = 8;
27 static const u64 cfq_fifo_expire[2] = { NSEC_PER_SEC / 4, NSEC_PER_SEC / 8 };
28 /* maximum backwards seek, in KiB */
29 static const int cfq_back_max = 16 * 1024;
30 /* penalty of a backwards seek */
31 static const int cfq_back_penalty = 2;
32 static const u64 cfq_slice_sync = NSEC_PER_SEC / 10;
33 static u64 cfq_slice_async = NSEC_PER_SEC / 25;
34 static const int cfq_slice_async_rq = 2;
35 static u64 cfq_slice_idle = NSEC_PER_SEC / 125;
36 static u64 cfq_group_idle = NSEC_PER_SEC / 125;
37 static const u64 cfq_target_latency = (u64)NSEC_PER_SEC * 3/10; /* 300 ms */
38 static const int cfq_hist_divisor = 4;
39
40 /*
41 * offset from end of queue service tree for idle class
42 */
43 #define CFQ_IDLE_DELAY (NSEC_PER_SEC / 5)
44 /* offset from end of group service tree under time slice mode */
45 #define CFQ_SLICE_MODE_GROUP_DELAY (NSEC_PER_SEC / 5)
46 /* offset from end of group service under IOPS mode */
47 #define CFQ_IOPS_MODE_GROUP_DELAY (HZ / 5)
48
49 /*
50 * below this threshold, we consider thinktime immediate
51 */
52 #define CFQ_MIN_TT (2 * NSEC_PER_SEC / HZ)
53
54 #define CFQ_SLICE_SCALE (5)
55 #define CFQ_HW_QUEUE_MIN (5)
56 #define CFQ_SERVICE_SHIFT 12
57
58 #define CFQQ_SEEK_THR (sector_t)(8 * 100)
59 #define CFQQ_CLOSE_THR (sector_t)(8 * 1024)
60 #define CFQQ_SECT_THR_NONROT (sector_t)(2 * 32)
61 #define CFQQ_SEEKY(cfqq) (hweight32(cfqq->seek_history) > 32/8)
62
63 #define RQ_CIC(rq) icq_to_cic((rq)->elv.icq)
64 #define RQ_CFQQ(rq) (struct cfq_queue *) ((rq)->elv.priv[0])
65 #define RQ_CFQG(rq) (struct cfq_group *) ((rq)->elv.priv[1])
66
67 static struct kmem_cache *cfq_pool;
68
69 #define CFQ_PRIO_LISTS IOPRIO_BE_NR
70 #define cfq_class_idle(cfqq) ((cfqq)->ioprio_class == IOPRIO_CLASS_IDLE)
71 #define cfq_class_rt(cfqq) ((cfqq)->ioprio_class == IOPRIO_CLASS_RT)
72
73 #define sample_valid(samples) ((samples) > 80)
74 #define rb_entry_cfqg(node) rb_entry((node), struct cfq_group, rb_node)
75
76 /* blkio-related constants */
77 #define CFQ_WEIGHT_LEGACY_MIN 10
78 #define CFQ_WEIGHT_LEGACY_DFL 500
79 #define CFQ_WEIGHT_LEGACY_MAX 1000
80
81 struct cfq_ttime {
82 u64 last_end_request;
83
84 u64 ttime_total;
85 u64 ttime_mean;
86 unsigned long ttime_samples;
87 };
88
89 /*
90 * Most of our rbtree usage is for sorting with min extraction, so
91 * if we cache the leftmost node we don't have to walk down the tree
92 * to find it. Idea borrowed from Ingo Molnars CFS scheduler. We should
93 * move this into the elevator for the rq sorting as well.
94 */
95 struct cfq_rb_root {
96 struct rb_root rb;
97 struct rb_node *left;
98 unsigned count;
99 u64 min_vdisktime;
100 struct cfq_ttime ttime;
101 };
102 #define CFQ_RB_ROOT (struct cfq_rb_root) { .rb = RB_ROOT, \
103 .ttime = {.last_end_request = ktime_get_ns(),},}
104
105 /*
106 * Per process-grouping structure
107 */
108 struct cfq_queue {
109 /* reference count */
110 int ref;
111 /* various state flags, see below */
112 unsigned int flags;
113 /* parent cfq_data */
114 struct cfq_data *cfqd;
115 /* service_tree member */
116 struct rb_node rb_node;
117 /* service_tree key */
118 u64 rb_key;
119 /* prio tree member */
120 struct rb_node p_node;
121 /* prio tree root we belong to, if any */
122 struct rb_root *p_root;
123 /* sorted list of pending requests */
124 struct rb_root sort_list;
125 /* if fifo isn't expired, next request to serve */
126 struct request *next_rq;
127 /* requests queued in sort_list */
128 int queued[2];
129 /* currently allocated requests */
130 int allocated[2];
131 /* fifo list of requests in sort_list */
132 struct list_head fifo;
133
134 /* time when queue got scheduled in to dispatch first request. */
135 u64 dispatch_start;
136 u64 allocated_slice;
137 u64 slice_dispatch;
138 /* time when first request from queue completed and slice started. */
139 u64 slice_start;
140 u64 slice_end;
141 s64 slice_resid;
142
143 /* pending priority requests */
144 int prio_pending;
145 /* number of requests that are on the dispatch list or inside driver */
146 int dispatched;
147
148 /* io prio of this group */
149 unsigned short ioprio, org_ioprio;
150 unsigned short ioprio_class, org_ioprio_class;
151
152 pid_t pid;
153
154 u32 seek_history;
155 sector_t last_request_pos;
156
157 struct cfq_rb_root *service_tree;
158 struct cfq_queue *new_cfqq;
159 struct cfq_group *cfqg;
160 /* Number of sectors dispatched from queue in single dispatch round */
161 unsigned long nr_sectors;
162 };
163
164 /*
165 * First index in the service_trees.
166 * IDLE is handled separately, so it has negative index
167 */
168 enum wl_class_t {
169 BE_WORKLOAD = 0,
170 RT_WORKLOAD = 1,
171 IDLE_WORKLOAD = 2,
172 CFQ_PRIO_NR,
173 };
174
175 /*
176 * Second index in the service_trees.
177 */
178 enum wl_type_t {
179 ASYNC_WORKLOAD = 0,
180 SYNC_NOIDLE_WORKLOAD = 1,
181 SYNC_WORKLOAD = 2
182 };
183
184 struct cfqg_stats {
185 #ifdef CONFIG_CFQ_GROUP_IOSCHED
186 /* number of ios merged */
187 struct blkg_rwstat merged;
188 /* total time spent on device in ns, may not be accurate w/ queueing */
189 struct blkg_rwstat service_time;
190 /* total time spent waiting in scheduler queue in ns */
191 struct blkg_rwstat wait_time;
192 /* number of IOs queued up */
193 struct blkg_rwstat queued;
194 /* total disk time and nr sectors dispatched by this group */
195 struct blkg_stat time;
196 #ifdef CONFIG_DEBUG_BLK_CGROUP
197 /* time not charged to this cgroup */
198 struct blkg_stat unaccounted_time;
199 /* sum of number of ios queued across all samples */
200 struct blkg_stat avg_queue_size_sum;
201 /* count of samples taken for average */
202 struct blkg_stat avg_queue_size_samples;
203 /* how many times this group has been removed from service tree */
204 struct blkg_stat dequeue;
205 /* total time spent waiting for it to be assigned a timeslice. */
206 struct blkg_stat group_wait_time;
207 /* time spent idling for this blkcg_gq */
208 struct blkg_stat idle_time;
209 /* total time with empty current active q with other requests queued */
210 struct blkg_stat empty_time;
211 /* fields after this shouldn't be cleared on stat reset */
212 uint64_t start_group_wait_time;
213 uint64_t start_idle_time;
214 uint64_t start_empty_time;
215 uint16_t flags;
216 #endif /* CONFIG_DEBUG_BLK_CGROUP */
217 #endif /* CONFIG_CFQ_GROUP_IOSCHED */
218 };
219
220 /* Per-cgroup data */
221 struct cfq_group_data {
222 /* must be the first member */
223 struct blkcg_policy_data cpd;
224
225 unsigned int weight;
226 unsigned int leaf_weight;
227 };
228
229 /* This is per cgroup per device grouping structure */
230 struct cfq_group {
231 /* must be the first member */
232 struct blkg_policy_data pd;
233
234 /* group service_tree member */
235 struct rb_node rb_node;
236
237 /* group service_tree key */
238 u64 vdisktime;
239
240 /*
241 * The number of active cfqgs and sum of their weights under this
242 * cfqg. This covers this cfqg's leaf_weight and all children's
243 * weights, but does not cover weights of further descendants.
244 *
245 * If a cfqg is on the service tree, it's active. An active cfqg
246 * also activates its parent and contributes to the children_weight
247 * of the parent.
248 */
249 int nr_active;
250 unsigned int children_weight;
251
252 /*
253 * vfraction is the fraction of vdisktime that the tasks in this
254 * cfqg are entitled to. This is determined by compounding the
255 * ratios walking up from this cfqg to the root.
256 *
257 * It is in fixed point w/ CFQ_SERVICE_SHIFT and the sum of all
258 * vfractions on a service tree is approximately 1. The sum may
259 * deviate a bit due to rounding errors and fluctuations caused by
260 * cfqgs entering and leaving the service tree.
261 */
262 unsigned int vfraction;
263
264 /*
265 * There are two weights - (internal) weight is the weight of this
266 * cfqg against the sibling cfqgs. leaf_weight is the wight of
267 * this cfqg against the child cfqgs. For the root cfqg, both
268 * weights are kept in sync for backward compatibility.
269 */
270 unsigned int weight;
271 unsigned int new_weight;
272 unsigned int dev_weight;
273
274 unsigned int leaf_weight;
275 unsigned int new_leaf_weight;
276 unsigned int dev_leaf_weight;
277
278 /* number of cfqq currently on this group */
279 int nr_cfqq;
280
281 /*
282 * Per group busy queues average. Useful for workload slice calc. We
283 * create the array for each prio class but at run time it is used
284 * only for RT and BE class and slot for IDLE class remains unused.
285 * This is primarily done to avoid confusion and a gcc warning.
286 */
287 unsigned int busy_queues_avg[CFQ_PRIO_NR];
288 /*
289 * rr lists of queues with requests. We maintain service trees for
290 * RT and BE classes. These trees are subdivided in subclasses
291 * of SYNC, SYNC_NOIDLE and ASYNC based on workload type. For IDLE
292 * class there is no subclassification and all the cfq queues go on
293 * a single tree service_tree_idle.
294 * Counts are embedded in the cfq_rb_root
295 */
296 struct cfq_rb_root service_trees[2][3];
297 struct cfq_rb_root service_tree_idle;
298
299 u64 saved_wl_slice;
300 enum wl_type_t saved_wl_type;
301 enum wl_class_t saved_wl_class;
302
303 /* number of requests that are on the dispatch list or inside driver */
304 int dispatched;
305 struct cfq_ttime ttime;
306 struct cfqg_stats stats; /* stats for this cfqg */
307
308 /* async queue for each priority case */
309 struct cfq_queue *async_cfqq[2][IOPRIO_BE_NR];
310 struct cfq_queue *async_idle_cfqq;
311
312 };
313
314 struct cfq_io_cq {
315 struct io_cq icq; /* must be the first member */
316 struct cfq_queue *cfqq[2];
317 struct cfq_ttime ttime;
318 int ioprio; /* the current ioprio */
319 #ifdef CONFIG_CFQ_GROUP_IOSCHED
320 uint64_t blkcg_serial_nr; /* the current blkcg serial */
321 #endif
322 };
323
324 /*
325 * Per block device queue structure
326 */
327 struct cfq_data {
328 struct request_queue *queue;
329 /* Root service tree for cfq_groups */
330 struct cfq_rb_root grp_service_tree;
331 struct cfq_group *root_group;
332
333 /*
334 * The priority currently being served
335 */
336 enum wl_class_t serving_wl_class;
337 enum wl_type_t serving_wl_type;
338 u64 workload_expires;
339 struct cfq_group *serving_group;
340
341 /*
342 * Each priority tree is sorted by next_request position. These
343 * trees are used when determining if two or more queues are
344 * interleaving requests (see cfq_close_cooperator).
345 */
346 struct rb_root prio_trees[CFQ_PRIO_LISTS];
347
348 unsigned int busy_queues;
349 unsigned int busy_sync_queues;
350
351 int rq_in_driver;
352 int rq_in_flight[2];
353
354 /*
355 * queue-depth detection
356 */
357 int rq_queued;
358 int hw_tag;
359 /*
360 * hw_tag can be
361 * -1 => indeterminate, (cfq will behave as if NCQ is present, to allow better detection)
362 * 1 => NCQ is present (hw_tag_est_depth is the estimated max depth)
363 * 0 => no NCQ
364 */
365 int hw_tag_est_depth;
366 unsigned int hw_tag_samples;
367
368 /*
369 * idle window management
370 */
371 struct hrtimer idle_slice_timer;
372 struct work_struct unplug_work;
373
374 struct cfq_queue *active_queue;
375 struct cfq_io_cq *active_cic;
376
377 sector_t last_position;
378
379 /*
380 * tunables, see top of file
381 */
382 unsigned int cfq_quantum;
383 unsigned int cfq_back_penalty;
384 unsigned int cfq_back_max;
385 unsigned int cfq_slice_async_rq;
386 unsigned int cfq_latency;
387 u64 cfq_fifo_expire[2];
388 u64 cfq_slice[2];
389 u64 cfq_slice_idle;
390 u64 cfq_group_idle;
391 u64 cfq_target_latency;
392
393 /*
394 * Fallback dummy cfqq for extreme OOM conditions
395 */
396 struct cfq_queue oom_cfqq;
397
398 u64 last_delayed_sync;
399 };
400
401 static struct cfq_group *cfq_get_next_cfqg(struct cfq_data *cfqd);
402 static void cfq_put_queue(struct cfq_queue *cfqq);
403
404 static struct cfq_rb_root *st_for(struct cfq_group *cfqg,
405 enum wl_class_t class,
406 enum wl_type_t type)
407 {
408 if (!cfqg)
409 return NULL;
410
411 if (class == IDLE_WORKLOAD)
412 return &cfqg->service_tree_idle;
413
414 return &cfqg->service_trees[class][type];
415 }
416
417 enum cfqq_state_flags {
418 CFQ_CFQQ_FLAG_on_rr = 0, /* on round-robin busy list */
419 CFQ_CFQQ_FLAG_wait_request, /* waiting for a request */
420 CFQ_CFQQ_FLAG_must_dispatch, /* must be allowed a dispatch */
421 CFQ_CFQQ_FLAG_must_alloc_slice, /* per-slice must_alloc flag */
422 CFQ_CFQQ_FLAG_fifo_expire, /* FIFO checked in this slice */
423 CFQ_CFQQ_FLAG_idle_window, /* slice idling enabled */
424 CFQ_CFQQ_FLAG_prio_changed, /* task priority has changed */
425 CFQ_CFQQ_FLAG_slice_new, /* no requests dispatched in slice */
426 CFQ_CFQQ_FLAG_sync, /* synchronous queue */
427 CFQ_CFQQ_FLAG_coop, /* cfqq is shared */
428 CFQ_CFQQ_FLAG_split_coop, /* shared cfqq will be splitted */
429 CFQ_CFQQ_FLAG_deep, /* sync cfqq experienced large depth */
430 CFQ_CFQQ_FLAG_wait_busy, /* Waiting for next request */
431 };
432
433 #define CFQ_CFQQ_FNS(name) \
434 static inline void cfq_mark_cfqq_##name(struct cfq_queue *cfqq) \
435 { \
436 (cfqq)->flags |= (1 << CFQ_CFQQ_FLAG_##name); \
437 } \
438 static inline void cfq_clear_cfqq_##name(struct cfq_queue *cfqq) \
439 { \
440 (cfqq)->flags &= ~(1 << CFQ_CFQQ_FLAG_##name); \
441 } \
442 static inline int cfq_cfqq_##name(const struct cfq_queue *cfqq) \
443 { \
444 return ((cfqq)->flags & (1 << CFQ_CFQQ_FLAG_##name)) != 0; \
445 }
446
447 CFQ_CFQQ_FNS(on_rr);
448 CFQ_CFQQ_FNS(wait_request);
449 CFQ_CFQQ_FNS(must_dispatch);
450 CFQ_CFQQ_FNS(must_alloc_slice);
451 CFQ_CFQQ_FNS(fifo_expire);
452 CFQ_CFQQ_FNS(idle_window);
453 CFQ_CFQQ_FNS(prio_changed);
454 CFQ_CFQQ_FNS(slice_new);
455 CFQ_CFQQ_FNS(sync);
456 CFQ_CFQQ_FNS(coop);
457 CFQ_CFQQ_FNS(split_coop);
458 CFQ_CFQQ_FNS(deep);
459 CFQ_CFQQ_FNS(wait_busy);
460 #undef CFQ_CFQQ_FNS
461
462 #if defined(CONFIG_CFQ_GROUP_IOSCHED) && defined(CONFIG_DEBUG_BLK_CGROUP)
463
464 /* cfqg stats flags */
465 enum cfqg_stats_flags {
466 CFQG_stats_waiting = 0,
467 CFQG_stats_idling,
468 CFQG_stats_empty,
469 };
470
471 #define CFQG_FLAG_FNS(name) \
472 static inline void cfqg_stats_mark_##name(struct cfqg_stats *stats) \
473 { \
474 stats->flags |= (1 << CFQG_stats_##name); \
475 } \
476 static inline void cfqg_stats_clear_##name(struct cfqg_stats *stats) \
477 { \
478 stats->flags &= ~(1 << CFQG_stats_##name); \
479 } \
480 static inline int cfqg_stats_##name(struct cfqg_stats *stats) \
481 { \
482 return (stats->flags & (1 << CFQG_stats_##name)) != 0; \
483 } \
484
485 CFQG_FLAG_FNS(waiting)
486 CFQG_FLAG_FNS(idling)
487 CFQG_FLAG_FNS(empty)
488 #undef CFQG_FLAG_FNS
489
490 /* This should be called with the queue_lock held. */
491 static void cfqg_stats_update_group_wait_time(struct cfqg_stats *stats)
492 {
493 unsigned long long now;
494
495 if (!cfqg_stats_waiting(stats))
496 return;
497
498 now = sched_clock();
499 if (time_after64(now, stats->start_group_wait_time))
500 blkg_stat_add(&stats->group_wait_time,
501 now - stats->start_group_wait_time);
502 cfqg_stats_clear_waiting(stats);
503 }
504
505 /* This should be called with the queue_lock held. */
506 static void cfqg_stats_set_start_group_wait_time(struct cfq_group *cfqg,
507 struct cfq_group *curr_cfqg)
508 {
509 struct cfqg_stats *stats = &cfqg->stats;
510
511 if (cfqg_stats_waiting(stats))
512 return;
513 if (cfqg == curr_cfqg)
514 return;
515 stats->start_group_wait_time = sched_clock();
516 cfqg_stats_mark_waiting(stats);
517 }
518
519 /* This should be called with the queue_lock held. */
520 static void cfqg_stats_end_empty_time(struct cfqg_stats *stats)
521 {
522 unsigned long long now;
523
524 if (!cfqg_stats_empty(stats))
525 return;
526
527 now = sched_clock();
528 if (time_after64(now, stats->start_empty_time))
529 blkg_stat_add(&stats->empty_time,
530 now - stats->start_empty_time);
531 cfqg_stats_clear_empty(stats);
532 }
533
534 static void cfqg_stats_update_dequeue(struct cfq_group *cfqg)
535 {
536 blkg_stat_add(&cfqg->stats.dequeue, 1);
537 }
538
539 static void cfqg_stats_set_start_empty_time(struct cfq_group *cfqg)
540 {
541 struct cfqg_stats *stats = &cfqg->stats;
542
543 if (blkg_rwstat_total(&stats->queued))
544 return;
545
546 /*
547 * group is already marked empty. This can happen if cfqq got new
548 * request in parent group and moved to this group while being added
549 * to service tree. Just ignore the event and move on.
550 */
551 if (cfqg_stats_empty(stats))
552 return;
553
554 stats->start_empty_time = sched_clock();
555 cfqg_stats_mark_empty(stats);
556 }
557
558 static void cfqg_stats_update_idle_time(struct cfq_group *cfqg)
559 {
560 struct cfqg_stats *stats = &cfqg->stats;
561
562 if (cfqg_stats_idling(stats)) {
563 unsigned long long now = sched_clock();
564
565 if (time_after64(now, stats->start_idle_time))
566 blkg_stat_add(&stats->idle_time,
567 now - stats->start_idle_time);
568 cfqg_stats_clear_idling(stats);
569 }
570 }
571
572 static void cfqg_stats_set_start_idle_time(struct cfq_group *cfqg)
573 {
574 struct cfqg_stats *stats = &cfqg->stats;
575
576 BUG_ON(cfqg_stats_idling(stats));
577
578 stats->start_idle_time = sched_clock();
579 cfqg_stats_mark_idling(stats);
580 }
581
582 static void cfqg_stats_update_avg_queue_size(struct cfq_group *cfqg)
583 {
584 struct cfqg_stats *stats = &cfqg->stats;
585
586 blkg_stat_add(&stats->avg_queue_size_sum,
587 blkg_rwstat_total(&stats->queued));
588 blkg_stat_add(&stats->avg_queue_size_samples, 1);
589 cfqg_stats_update_group_wait_time(stats);
590 }
591
592 #else /* CONFIG_CFQ_GROUP_IOSCHED && CONFIG_DEBUG_BLK_CGROUP */
593
594 static inline void cfqg_stats_set_start_group_wait_time(struct cfq_group *cfqg, struct cfq_group *curr_cfqg) { }
595 static inline void cfqg_stats_end_empty_time(struct cfqg_stats *stats) { }
596 static inline void cfqg_stats_update_dequeue(struct cfq_group *cfqg) { }
597 static inline void cfqg_stats_set_start_empty_time(struct cfq_group *cfqg) { }
598 static inline void cfqg_stats_update_idle_time(struct cfq_group *cfqg) { }
599 static inline void cfqg_stats_set_start_idle_time(struct cfq_group *cfqg) { }
600 static inline void cfqg_stats_update_avg_queue_size(struct cfq_group *cfqg) { }
601
602 #endif /* CONFIG_CFQ_GROUP_IOSCHED && CONFIG_DEBUG_BLK_CGROUP */
603
604 #ifdef CONFIG_CFQ_GROUP_IOSCHED
605
606 static inline struct cfq_group *pd_to_cfqg(struct blkg_policy_data *pd)
607 {
608 return pd ? container_of(pd, struct cfq_group, pd) : NULL;
609 }
610
611 static struct cfq_group_data
612 *cpd_to_cfqgd(struct blkcg_policy_data *cpd)
613 {
614 return cpd ? container_of(cpd, struct cfq_group_data, cpd) : NULL;
615 }
616
617 static inline struct blkcg_gq *cfqg_to_blkg(struct cfq_group *cfqg)
618 {
619 return pd_to_blkg(&cfqg->pd);
620 }
621
622 static struct blkcg_policy blkcg_policy_cfq;
623
624 static inline struct cfq_group *blkg_to_cfqg(struct blkcg_gq *blkg)
625 {
626 return pd_to_cfqg(blkg_to_pd(blkg, &blkcg_policy_cfq));
627 }
628
629 static struct cfq_group_data *blkcg_to_cfqgd(struct blkcg *blkcg)
630 {
631 return cpd_to_cfqgd(blkcg_to_cpd(blkcg, &blkcg_policy_cfq));
632 }
633
634 static inline struct cfq_group *cfqg_parent(struct cfq_group *cfqg)
635 {
636 struct blkcg_gq *pblkg = cfqg_to_blkg(cfqg)->parent;
637
638 return pblkg ? blkg_to_cfqg(pblkg) : NULL;
639 }
640
641 static inline bool cfqg_is_descendant(struct cfq_group *cfqg,
642 struct cfq_group *ancestor)
643 {
644 return cgroup_is_descendant(cfqg_to_blkg(cfqg)->blkcg->css.cgroup,
645 cfqg_to_blkg(ancestor)->blkcg->css.cgroup);
646 }
647
648 static inline void cfqg_get(struct cfq_group *cfqg)
649 {
650 return blkg_get(cfqg_to_blkg(cfqg));
651 }
652
653 static inline void cfqg_put(struct cfq_group *cfqg)
654 {
655 return blkg_put(cfqg_to_blkg(cfqg));
656 }
657
658 #define cfq_log_cfqq(cfqd, cfqq, fmt, args...) do { \
659 char __pbuf[128]; \
660 \
661 blkg_path(cfqg_to_blkg((cfqq)->cfqg), __pbuf, sizeof(__pbuf)); \
662 blk_add_trace_msg((cfqd)->queue, "cfq%d%c%c %s " fmt, (cfqq)->pid, \
663 cfq_cfqq_sync((cfqq)) ? 'S' : 'A', \
664 cfqq_type((cfqq)) == SYNC_NOIDLE_WORKLOAD ? 'N' : ' ',\
665 __pbuf, ##args); \
666 } while (0)
667
668 #define cfq_log_cfqg(cfqd, cfqg, fmt, args...) do { \
669 char __pbuf[128]; \
670 \
671 blkg_path(cfqg_to_blkg(cfqg), __pbuf, sizeof(__pbuf)); \
672 blk_add_trace_msg((cfqd)->queue, "%s " fmt, __pbuf, ##args); \
673 } while (0)
674
675 static inline void cfqg_stats_update_io_add(struct cfq_group *cfqg,
676 struct cfq_group *curr_cfqg,
677 unsigned int op)
678 {
679 blkg_rwstat_add(&cfqg->stats.queued, op, 1);
680 cfqg_stats_end_empty_time(&cfqg->stats);
681 cfqg_stats_set_start_group_wait_time(cfqg, curr_cfqg);
682 }
683
684 static inline void cfqg_stats_update_timeslice_used(struct cfq_group *cfqg,
685 uint64_t time, unsigned long unaccounted_time)
686 {
687 blkg_stat_add(&cfqg->stats.time, time);
688 #ifdef CONFIG_DEBUG_BLK_CGROUP
689 blkg_stat_add(&cfqg->stats.unaccounted_time, unaccounted_time);
690 #endif
691 }
692
693 static inline void cfqg_stats_update_io_remove(struct cfq_group *cfqg,
694 unsigned int op)
695 {
696 blkg_rwstat_add(&cfqg->stats.queued, op, -1);
697 }
698
699 static inline void cfqg_stats_update_io_merged(struct cfq_group *cfqg,
700 unsigned int op)
701 {
702 blkg_rwstat_add(&cfqg->stats.merged, op, 1);
703 }
704
705 static inline void cfqg_stats_update_completion(struct cfq_group *cfqg,
706 uint64_t start_time, uint64_t io_start_time,
707 unsigned int op)
708 {
709 struct cfqg_stats *stats = &cfqg->stats;
710 unsigned long long now = sched_clock();
711
712 if (time_after64(now, io_start_time))
713 blkg_rwstat_add(&stats->service_time, op, now - io_start_time);
714 if (time_after64(io_start_time, start_time))
715 blkg_rwstat_add(&stats->wait_time, op,
716 io_start_time - start_time);
717 }
718
719 /* @stats = 0 */
720 static void cfqg_stats_reset(struct cfqg_stats *stats)
721 {
722 /* queued stats shouldn't be cleared */
723 blkg_rwstat_reset(&stats->merged);
724 blkg_rwstat_reset(&stats->service_time);
725 blkg_rwstat_reset(&stats->wait_time);
726 blkg_stat_reset(&stats->time);
727 #ifdef CONFIG_DEBUG_BLK_CGROUP
728 blkg_stat_reset(&stats->unaccounted_time);
729 blkg_stat_reset(&stats->avg_queue_size_sum);
730 blkg_stat_reset(&stats->avg_queue_size_samples);
731 blkg_stat_reset(&stats->dequeue);
732 blkg_stat_reset(&stats->group_wait_time);
733 blkg_stat_reset(&stats->idle_time);
734 blkg_stat_reset(&stats->empty_time);
735 #endif
736 }
737
738 /* @to += @from */
739 static void cfqg_stats_add_aux(struct cfqg_stats *to, struct cfqg_stats *from)
740 {
741 /* queued stats shouldn't be cleared */
742 blkg_rwstat_add_aux(&to->merged, &from->merged);
743 blkg_rwstat_add_aux(&to->service_time, &from->service_time);
744 blkg_rwstat_add_aux(&to->wait_time, &from->wait_time);
745 blkg_stat_add_aux(&from->time, &from->time);
746 #ifdef CONFIG_DEBUG_BLK_CGROUP
747 blkg_stat_add_aux(&to->unaccounted_time, &from->unaccounted_time);
748 blkg_stat_add_aux(&to->avg_queue_size_sum, &from->avg_queue_size_sum);
749 blkg_stat_add_aux(&to->avg_queue_size_samples, &from->avg_queue_size_samples);
750 blkg_stat_add_aux(&to->dequeue, &from->dequeue);
751 blkg_stat_add_aux(&to->group_wait_time, &from->group_wait_time);
752 blkg_stat_add_aux(&to->idle_time, &from->idle_time);
753 blkg_stat_add_aux(&to->empty_time, &from->empty_time);
754 #endif
755 }
756
757 /*
758 * Transfer @cfqg's stats to its parent's aux counts so that the ancestors'
759 * recursive stats can still account for the amount used by this cfqg after
760 * it's gone.
761 */
762 static void cfqg_stats_xfer_dead(struct cfq_group *cfqg)
763 {
764 struct cfq_group *parent = cfqg_parent(cfqg);
765
766 lockdep_assert_held(cfqg_to_blkg(cfqg)->q->queue_lock);
767
768 if (unlikely(!parent))
769 return;
770
771 cfqg_stats_add_aux(&parent->stats, &cfqg->stats);
772 cfqg_stats_reset(&cfqg->stats);
773 }
774
775 #else /* CONFIG_CFQ_GROUP_IOSCHED */
776
777 static inline struct cfq_group *cfqg_parent(struct cfq_group *cfqg) { return NULL; }
778 static inline bool cfqg_is_descendant(struct cfq_group *cfqg,
779 struct cfq_group *ancestor)
780 {
781 return true;
782 }
783 static inline void cfqg_get(struct cfq_group *cfqg) { }
784 static inline void cfqg_put(struct cfq_group *cfqg) { }
785
786 #define cfq_log_cfqq(cfqd, cfqq, fmt, args...) \
787 blk_add_trace_msg((cfqd)->queue, "cfq%d%c%c " fmt, (cfqq)->pid, \
788 cfq_cfqq_sync((cfqq)) ? 'S' : 'A', \
789 cfqq_type((cfqq)) == SYNC_NOIDLE_WORKLOAD ? 'N' : ' ',\
790 ##args)
791 #define cfq_log_cfqg(cfqd, cfqg, fmt, args...) do {} while (0)
792
793 static inline void cfqg_stats_update_io_add(struct cfq_group *cfqg,
794 struct cfq_group *curr_cfqg, unsigned int op) { }
795 static inline void cfqg_stats_update_timeslice_used(struct cfq_group *cfqg,
796 uint64_t time, unsigned long unaccounted_time) { }
797 static inline void cfqg_stats_update_io_remove(struct cfq_group *cfqg,
798 unsigned int op) { }
799 static inline void cfqg_stats_update_io_merged(struct cfq_group *cfqg,
800 unsigned int op) { }
801 static inline void cfqg_stats_update_completion(struct cfq_group *cfqg,
802 uint64_t start_time, uint64_t io_start_time,
803 unsigned int op) { }
804
805 #endif /* CONFIG_CFQ_GROUP_IOSCHED */
806
807 #define cfq_log(cfqd, fmt, args...) \
808 blk_add_trace_msg((cfqd)->queue, "cfq " fmt, ##args)
809
810 /* Traverses through cfq group service trees */
811 #define for_each_cfqg_st(cfqg, i, j, st) \
812 for (i = 0; i <= IDLE_WORKLOAD; i++) \
813 for (j = 0, st = i < IDLE_WORKLOAD ? &cfqg->service_trees[i][j]\
814 : &cfqg->service_tree_idle; \
815 (i < IDLE_WORKLOAD && j <= SYNC_WORKLOAD) || \
816 (i == IDLE_WORKLOAD && j == 0); \
817 j++, st = i < IDLE_WORKLOAD ? \
818 &cfqg->service_trees[i][j]: NULL) \
819
820 static inline bool cfq_io_thinktime_big(struct cfq_data *cfqd,
821 struct cfq_ttime *ttime, bool group_idle)
822 {
823 u64 slice;
824 if (!sample_valid(ttime->ttime_samples))
825 return false;
826 if (group_idle)
827 slice = cfqd->cfq_group_idle;
828 else
829 slice = cfqd->cfq_slice_idle;
830 return ttime->ttime_mean > slice;
831 }
832
833 static inline bool iops_mode(struct cfq_data *cfqd)
834 {
835 /*
836 * If we are not idling on queues and it is a NCQ drive, parallel
837 * execution of requests is on and measuring time is not possible
838 * in most of the cases until and unless we drive shallower queue
839 * depths and that becomes a performance bottleneck. In such cases
840 * switch to start providing fairness in terms of number of IOs.
841 */
842 if (!cfqd->cfq_slice_idle && cfqd->hw_tag)
843 return true;
844 else
845 return false;
846 }
847
848 static inline enum wl_class_t cfqq_class(struct cfq_queue *cfqq)
849 {
850 if (cfq_class_idle(cfqq))
851 return IDLE_WORKLOAD;
852 if (cfq_class_rt(cfqq))
853 return RT_WORKLOAD;
854 return BE_WORKLOAD;
855 }
856
857
858 static enum wl_type_t cfqq_type(struct cfq_queue *cfqq)
859 {
860 if (!cfq_cfqq_sync(cfqq))
861 return ASYNC_WORKLOAD;
862 if (!cfq_cfqq_idle_window(cfqq))
863 return SYNC_NOIDLE_WORKLOAD;
864 return SYNC_WORKLOAD;
865 }
866
867 static inline int cfq_group_busy_queues_wl(enum wl_class_t wl_class,
868 struct cfq_data *cfqd,
869 struct cfq_group *cfqg)
870 {
871 if (wl_class == IDLE_WORKLOAD)
872 return cfqg->service_tree_idle.count;
873
874 return cfqg->service_trees[wl_class][ASYNC_WORKLOAD].count +
875 cfqg->service_trees[wl_class][SYNC_NOIDLE_WORKLOAD].count +
876 cfqg->service_trees[wl_class][SYNC_WORKLOAD].count;
877 }
878
879 static inline int cfqg_busy_async_queues(struct cfq_data *cfqd,
880 struct cfq_group *cfqg)
881 {
882 return cfqg->service_trees[RT_WORKLOAD][ASYNC_WORKLOAD].count +
883 cfqg->service_trees[BE_WORKLOAD][ASYNC_WORKLOAD].count;
884 }
885
886 static void cfq_dispatch_insert(struct request_queue *, struct request *);
887 static struct cfq_queue *cfq_get_queue(struct cfq_data *cfqd, bool is_sync,
888 struct cfq_io_cq *cic, struct bio *bio);
889
890 static inline struct cfq_io_cq *icq_to_cic(struct io_cq *icq)
891 {
892 /* cic->icq is the first member, %NULL will convert to %NULL */
893 return container_of(icq, struct cfq_io_cq, icq);
894 }
895
896 static inline struct cfq_io_cq *cfq_cic_lookup(struct cfq_data *cfqd,
897 struct io_context *ioc)
898 {
899 if (ioc)
900 return icq_to_cic(ioc_lookup_icq(ioc, cfqd->queue));
901 return NULL;
902 }
903
904 static inline struct cfq_queue *cic_to_cfqq(struct cfq_io_cq *cic, bool is_sync)
905 {
906 return cic->cfqq[is_sync];
907 }
908
909 static inline void cic_set_cfqq(struct cfq_io_cq *cic, struct cfq_queue *cfqq,
910 bool is_sync)
911 {
912 cic->cfqq[is_sync] = cfqq;
913 }
914
915 static inline struct cfq_data *cic_to_cfqd(struct cfq_io_cq *cic)
916 {
917 return cic->icq.q->elevator->elevator_data;
918 }
919
920 /*
921 * scheduler run of queue, if there are requests pending and no one in the
922 * driver that will restart queueing
923 */
924 static inline void cfq_schedule_dispatch(struct cfq_data *cfqd)
925 {
926 if (cfqd->busy_queues) {
927 cfq_log(cfqd, "schedule dispatch");
928 kblockd_schedule_work(&cfqd->unplug_work);
929 }
930 }
931
932 /*
933 * Scale schedule slice based on io priority. Use the sync time slice only
934 * if a queue is marked sync and has sync io queued. A sync queue with async
935 * io only, should not get full sync slice length.
936 */
937 static inline u64 cfq_prio_slice(struct cfq_data *cfqd, bool sync,
938 unsigned short prio)
939 {
940 u64 base_slice = cfqd->cfq_slice[sync];
941 u64 slice = div_u64(base_slice, CFQ_SLICE_SCALE);
942
943 WARN_ON(prio >= IOPRIO_BE_NR);
944
945 return base_slice + (slice * (4 - prio));
946 }
947
948 static inline u64
949 cfq_prio_to_slice(struct cfq_data *cfqd, struct cfq_queue *cfqq)
950 {
951 return cfq_prio_slice(cfqd, cfq_cfqq_sync(cfqq), cfqq->ioprio);
952 }
953
954 /**
955 * cfqg_scale_charge - scale disk time charge according to cfqg weight
956 * @charge: disk time being charged
957 * @vfraction: vfraction of the cfqg, fixed point w/ CFQ_SERVICE_SHIFT
958 *
959 * Scale @charge according to @vfraction, which is in range (0, 1]. The
960 * scaling is inversely proportional.
961 *
962 * scaled = charge / vfraction
963 *
964 * The result is also in fixed point w/ CFQ_SERVICE_SHIFT.
965 */
966 static inline u64 cfqg_scale_charge(u64 charge,
967 unsigned int vfraction)
968 {
969 u64 c = charge << CFQ_SERVICE_SHIFT; /* make it fixed point */
970
971 /* charge / vfraction */
972 c <<= CFQ_SERVICE_SHIFT;
973 return div_u64(c, vfraction);
974 }
975
976 static inline u64 max_vdisktime(u64 min_vdisktime, u64 vdisktime)
977 {
978 s64 delta = (s64)(vdisktime - min_vdisktime);
979 if (delta > 0)
980 min_vdisktime = vdisktime;
981
982 return min_vdisktime;
983 }
984
985 static void update_min_vdisktime(struct cfq_rb_root *st)
986 {
987 struct cfq_group *cfqg;
988
989 if (st->left) {
990 cfqg = rb_entry_cfqg(st->left);
991 st->min_vdisktime = max_vdisktime(st->min_vdisktime,
992 cfqg->vdisktime);
993 }
994 }
995
996 /*
997 * get averaged number of queues of RT/BE priority.
998 * average is updated, with a formula that gives more weight to higher numbers,
999 * to quickly follows sudden increases and decrease slowly
1000 */
1001
1002 static inline unsigned cfq_group_get_avg_queues(struct cfq_data *cfqd,
1003 struct cfq_group *cfqg, bool rt)
1004 {
1005 unsigned min_q, max_q;
1006 unsigned mult = cfq_hist_divisor - 1;
1007 unsigned round = cfq_hist_divisor / 2;
1008 unsigned busy = cfq_group_busy_queues_wl(rt, cfqd, cfqg);
1009
1010 min_q = min(cfqg->busy_queues_avg[rt], busy);
1011 max_q = max(cfqg->busy_queues_avg[rt], busy);
1012 cfqg->busy_queues_avg[rt] = (mult * max_q + min_q + round) /
1013 cfq_hist_divisor;
1014 return cfqg->busy_queues_avg[rt];
1015 }
1016
1017 static inline u64
1018 cfq_group_slice(struct cfq_data *cfqd, struct cfq_group *cfqg)
1019 {
1020 return cfqd->cfq_target_latency * cfqg->vfraction >> CFQ_SERVICE_SHIFT;
1021 }
1022
1023 static inline u64
1024 cfq_scaled_cfqq_slice(struct cfq_data *cfqd, struct cfq_queue *cfqq)
1025 {
1026 u64 slice = cfq_prio_to_slice(cfqd, cfqq);
1027 if (cfqd->cfq_latency) {
1028 /*
1029 * interested queues (we consider only the ones with the same
1030 * priority class in the cfq group)
1031 */
1032 unsigned iq = cfq_group_get_avg_queues(cfqd, cfqq->cfqg,
1033 cfq_class_rt(cfqq));
1034 u64 sync_slice = cfqd->cfq_slice[1];
1035 u64 expect_latency = sync_slice * iq;
1036 u64 group_slice = cfq_group_slice(cfqd, cfqq->cfqg);
1037
1038 if (expect_latency > group_slice) {
1039 u64 base_low_slice = 2 * cfqd->cfq_slice_idle;
1040 u64 low_slice;
1041
1042 /* scale low_slice according to IO priority
1043 * and sync vs async */
1044 low_slice = div64_u64(base_low_slice*slice, sync_slice);
1045 low_slice = min(slice, low_slice);
1046 /* the adapted slice value is scaled to fit all iqs
1047 * into the target latency */
1048 slice = div64_u64(slice*group_slice, expect_latency);
1049 slice = max(slice, low_slice);
1050 }
1051 }
1052 return slice;
1053 }
1054
1055 static inline void
1056 cfq_set_prio_slice(struct cfq_data *cfqd, struct cfq_queue *cfqq)
1057 {
1058 u64 slice = cfq_scaled_cfqq_slice(cfqd, cfqq);
1059 u64 now = ktime_get_ns();
1060
1061 cfqq->slice_start = now;
1062 cfqq->slice_end = now + slice;
1063 cfqq->allocated_slice = slice;
1064 cfq_log_cfqq(cfqd, cfqq, "set_slice=%llu", cfqq->slice_end - now);
1065 }
1066
1067 /*
1068 * We need to wrap this check in cfq_cfqq_slice_new(), since ->slice_end
1069 * isn't valid until the first request from the dispatch is activated
1070 * and the slice time set.
1071 */
1072 static inline bool cfq_slice_used(struct cfq_queue *cfqq)
1073 {
1074 if (cfq_cfqq_slice_new(cfqq))
1075 return false;
1076 if (ktime_get_ns() < cfqq->slice_end)
1077 return false;
1078
1079 return true;
1080 }
1081
1082 /*
1083 * Lifted from AS - choose which of rq1 and rq2 that is best served now.
1084 * We choose the request that is closest to the head right now. Distance
1085 * behind the head is penalized and only allowed to a certain extent.
1086 */
1087 static struct request *
1088 cfq_choose_req(struct cfq_data *cfqd, struct request *rq1, struct request *rq2, sector_t last)
1089 {
1090 sector_t s1, s2, d1 = 0, d2 = 0;
1091 unsigned long back_max;
1092 #define CFQ_RQ1_WRAP 0x01 /* request 1 wraps */
1093 #define CFQ_RQ2_WRAP 0x02 /* request 2 wraps */
1094 unsigned wrap = 0; /* bit mask: requests behind the disk head? */
1095
1096 if (rq1 == NULL || rq1 == rq2)
1097 return rq2;
1098 if (rq2 == NULL)
1099 return rq1;
1100
1101 if (rq_is_sync(rq1) != rq_is_sync(rq2))
1102 return rq_is_sync(rq1) ? rq1 : rq2;
1103
1104 if ((rq1->cmd_flags ^ rq2->cmd_flags) & REQ_PRIO)
1105 return rq1->cmd_flags & REQ_PRIO ? rq1 : rq2;
1106
1107 s1 = blk_rq_pos(rq1);
1108 s2 = blk_rq_pos(rq2);
1109
1110 /*
1111 * by definition, 1KiB is 2 sectors
1112 */
1113 back_max = cfqd->cfq_back_max * 2;
1114
1115 /*
1116 * Strict one way elevator _except_ in the case where we allow
1117 * short backward seeks which are biased as twice the cost of a
1118 * similar forward seek.
1119 */
1120 if (s1 >= last)
1121 d1 = s1 - last;
1122 else if (s1 + back_max >= last)
1123 d1 = (last - s1) * cfqd->cfq_back_penalty;
1124 else
1125 wrap |= CFQ_RQ1_WRAP;
1126
1127 if (s2 >= last)
1128 d2 = s2 - last;
1129 else if (s2 + back_max >= last)
1130 d2 = (last - s2) * cfqd->cfq_back_penalty;
1131 else
1132 wrap |= CFQ_RQ2_WRAP;
1133
1134 /* Found required data */
1135
1136 /*
1137 * By doing switch() on the bit mask "wrap" we avoid having to
1138 * check two variables for all permutations: --> faster!
1139 */
1140 switch (wrap) {
1141 case 0: /* common case for CFQ: rq1 and rq2 not wrapped */
1142 if (d1 < d2)
1143 return rq1;
1144 else if (d2 < d1)
1145 return rq2;
1146 else {
1147 if (s1 >= s2)
1148 return rq1;
1149 else
1150 return rq2;
1151 }
1152
1153 case CFQ_RQ2_WRAP:
1154 return rq1;
1155 case CFQ_RQ1_WRAP:
1156 return rq2;
1157 case (CFQ_RQ1_WRAP|CFQ_RQ2_WRAP): /* both rqs wrapped */
1158 default:
1159 /*
1160 * Since both rqs are wrapped,
1161 * start with the one that's further behind head
1162 * (--> only *one* back seek required),
1163 * since back seek takes more time than forward.
1164 */
1165 if (s1 <= s2)
1166 return rq1;
1167 else
1168 return rq2;
1169 }
1170 }
1171
1172 /*
1173 * The below is leftmost cache rbtree addon
1174 */
1175 static struct cfq_queue *cfq_rb_first(struct cfq_rb_root *root)
1176 {
1177 /* Service tree is empty */
1178 if (!root->count)
1179 return NULL;
1180
1181 if (!root->left)
1182 root->left = rb_first(&root->rb);
1183
1184 if (root->left)
1185 return rb_entry(root->left, struct cfq_queue, rb_node);
1186
1187 return NULL;
1188 }
1189
1190 static struct cfq_group *cfq_rb_first_group(struct cfq_rb_root *root)
1191 {
1192 if (!root->left)
1193 root->left = rb_first(&root->rb);
1194
1195 if (root->left)
1196 return rb_entry_cfqg(root->left);
1197
1198 return NULL;
1199 }
1200
1201 static void rb_erase_init(struct rb_node *n, struct rb_root *root)
1202 {
1203 rb_erase(n, root);
1204 RB_CLEAR_NODE(n);
1205 }
1206
1207 static void cfq_rb_erase(struct rb_node *n, struct cfq_rb_root *root)
1208 {
1209 if (root->left == n)
1210 root->left = NULL;
1211 rb_erase_init(n, &root->rb);
1212 --root->count;
1213 }
1214
1215 /*
1216 * would be nice to take fifo expire time into account as well
1217 */
1218 static struct request *
1219 cfq_find_next_rq(struct cfq_data *cfqd, struct cfq_queue *cfqq,
1220 struct request *last)
1221 {
1222 struct rb_node *rbnext = rb_next(&last->rb_node);
1223 struct rb_node *rbprev = rb_prev(&last->rb_node);
1224 struct request *next = NULL, *prev = NULL;
1225
1226 BUG_ON(RB_EMPTY_NODE(&last->rb_node));
1227
1228 if (rbprev)
1229 prev = rb_entry_rq(rbprev);
1230
1231 if (rbnext)
1232 next = rb_entry_rq(rbnext);
1233 else {
1234 rbnext = rb_first(&cfqq->sort_list);
1235 if (rbnext && rbnext != &last->rb_node)
1236 next = rb_entry_rq(rbnext);
1237 }
1238
1239 return cfq_choose_req(cfqd, next, prev, blk_rq_pos(last));
1240 }
1241
1242 static u64 cfq_slice_offset(struct cfq_data *cfqd,
1243 struct cfq_queue *cfqq)
1244 {
1245 /*
1246 * just an approximation, should be ok.
1247 */
1248 return (cfqq->cfqg->nr_cfqq - 1) * (cfq_prio_slice(cfqd, 1, 0) -
1249 cfq_prio_slice(cfqd, cfq_cfqq_sync(cfqq), cfqq->ioprio));
1250 }
1251
1252 static inline s64
1253 cfqg_key(struct cfq_rb_root *st, struct cfq_group *cfqg)
1254 {
1255 return cfqg->vdisktime - st->min_vdisktime;
1256 }
1257
1258 static void
1259 __cfq_group_service_tree_add(struct cfq_rb_root *st, struct cfq_group *cfqg)
1260 {
1261 struct rb_node **node = &st->rb.rb_node;
1262 struct rb_node *parent = NULL;
1263 struct cfq_group *__cfqg;
1264 s64 key = cfqg_key(st, cfqg);
1265 int left = 1;
1266
1267 while (*node != NULL) {
1268 parent = *node;
1269 __cfqg = rb_entry_cfqg(parent);
1270
1271 if (key < cfqg_key(st, __cfqg))
1272 node = &parent->rb_left;
1273 else {
1274 node = &parent->rb_right;
1275 left = 0;
1276 }
1277 }
1278
1279 if (left)
1280 st->left = &cfqg->rb_node;
1281
1282 rb_link_node(&cfqg->rb_node, parent, node);
1283 rb_insert_color(&cfqg->rb_node, &st->rb);
1284 }
1285
1286 /*
1287 * This has to be called only on activation of cfqg
1288 */
1289 static void
1290 cfq_update_group_weight(struct cfq_group *cfqg)
1291 {
1292 if (cfqg->new_weight) {
1293 cfqg->weight = cfqg->new_weight;
1294 cfqg->new_weight = 0;
1295 }
1296 }
1297
1298 static void
1299 cfq_update_group_leaf_weight(struct cfq_group *cfqg)
1300 {
1301 BUG_ON(!RB_EMPTY_NODE(&cfqg->rb_node));
1302
1303 if (cfqg->new_leaf_weight) {
1304 cfqg->leaf_weight = cfqg->new_leaf_weight;
1305 cfqg->new_leaf_weight = 0;
1306 }
1307 }
1308
1309 static void
1310 cfq_group_service_tree_add(struct cfq_rb_root *st, struct cfq_group *cfqg)
1311 {
1312 unsigned int vfr = 1 << CFQ_SERVICE_SHIFT; /* start with 1 */
1313 struct cfq_group *pos = cfqg;
1314 struct cfq_group *parent;
1315 bool propagate;
1316
1317 /* add to the service tree */
1318 BUG_ON(!RB_EMPTY_NODE(&cfqg->rb_node));
1319
1320 /*
1321 * Update leaf_weight. We cannot update weight at this point
1322 * because cfqg might already have been activated and is
1323 * contributing its current weight to the parent's child_weight.
1324 */
1325 cfq_update_group_leaf_weight(cfqg);
1326 __cfq_group_service_tree_add(st, cfqg);
1327
1328 /*
1329 * Activate @cfqg and calculate the portion of vfraction @cfqg is
1330 * entitled to. vfraction is calculated by walking the tree
1331 * towards the root calculating the fraction it has at each level.
1332 * The compounded ratio is how much vfraction @cfqg owns.
1333 *
1334 * Start with the proportion tasks in this cfqg has against active
1335 * children cfqgs - its leaf_weight against children_weight.
1336 */
1337 propagate = !pos->nr_active++;
1338 pos->children_weight += pos->leaf_weight;
1339 vfr = vfr * pos->leaf_weight / pos->children_weight;
1340
1341 /*
1342 * Compound ->weight walking up the tree. Both activation and
1343 * vfraction calculation are done in the same loop. Propagation
1344 * stops once an already activated node is met. vfraction
1345 * calculation should always continue to the root.
1346 */
1347 while ((parent = cfqg_parent(pos))) {
1348 if (propagate) {
1349 cfq_update_group_weight(pos);
1350 propagate = !parent->nr_active++;
1351 parent->children_weight += pos->weight;
1352 }
1353 vfr = vfr * pos->weight / parent->children_weight;
1354 pos = parent;
1355 }
1356
1357 cfqg->vfraction = max_t(unsigned, vfr, 1);
1358 }
1359
1360 static inline u64 cfq_get_cfqg_vdisktime_delay(struct cfq_data *cfqd)
1361 {
1362 if (!iops_mode(cfqd))
1363 return CFQ_SLICE_MODE_GROUP_DELAY;
1364 else
1365 return CFQ_IOPS_MODE_GROUP_DELAY;
1366 }
1367
1368 static void
1369 cfq_group_notify_queue_add(struct cfq_data *cfqd, struct cfq_group *cfqg)
1370 {
1371 struct cfq_rb_root *st = &cfqd->grp_service_tree;
1372 struct cfq_group *__cfqg;
1373 struct rb_node *n;
1374
1375 cfqg->nr_cfqq++;
1376 if (!RB_EMPTY_NODE(&cfqg->rb_node))
1377 return;
1378
1379 /*
1380 * Currently put the group at the end. Later implement something
1381 * so that groups get lesser vtime based on their weights, so that
1382 * if group does not loose all if it was not continuously backlogged.
1383 */
1384 n = rb_last(&st->rb);
1385 if (n) {
1386 __cfqg = rb_entry_cfqg(n);
1387 cfqg->vdisktime = __cfqg->vdisktime +
1388 cfq_get_cfqg_vdisktime_delay(cfqd);
1389 } else
1390 cfqg->vdisktime = st->min_vdisktime;
1391 cfq_group_service_tree_add(st, cfqg);
1392 }
1393
1394 static void
1395 cfq_group_service_tree_del(struct cfq_rb_root *st, struct cfq_group *cfqg)
1396 {
1397 struct cfq_group *pos = cfqg;
1398 bool propagate;
1399
1400 /*
1401 * Undo activation from cfq_group_service_tree_add(). Deactivate
1402 * @cfqg and propagate deactivation upwards.
1403 */
1404 propagate = !--pos->nr_active;
1405 pos->children_weight -= pos->leaf_weight;
1406
1407 while (propagate) {
1408 struct cfq_group *parent = cfqg_parent(pos);
1409
1410 /* @pos has 0 nr_active at this point */
1411 WARN_ON_ONCE(pos->children_weight);
1412 pos->vfraction = 0;
1413
1414 if (!parent)
1415 break;
1416
1417 propagate = !--parent->nr_active;
1418 parent->children_weight -= pos->weight;
1419 pos = parent;
1420 }
1421
1422 /* remove from the service tree */
1423 if (!RB_EMPTY_NODE(&cfqg->rb_node))
1424 cfq_rb_erase(&cfqg->rb_node, st);
1425 }
1426
1427 static void
1428 cfq_group_notify_queue_del(struct cfq_data *cfqd, struct cfq_group *cfqg)
1429 {
1430 struct cfq_rb_root *st = &cfqd->grp_service_tree;
1431
1432 BUG_ON(cfqg->nr_cfqq < 1);
1433 cfqg->nr_cfqq--;
1434
1435 /* If there are other cfq queues under this group, don't delete it */
1436 if (cfqg->nr_cfqq)
1437 return;
1438
1439 cfq_log_cfqg(cfqd, cfqg, "del_from_rr group");
1440 cfq_group_service_tree_del(st, cfqg);
1441 cfqg->saved_wl_slice = 0;
1442 cfqg_stats_update_dequeue(cfqg);
1443 }
1444
1445 static inline u64 cfq_cfqq_slice_usage(struct cfq_queue *cfqq,
1446 u64 *unaccounted_time)
1447 {
1448 u64 slice_used;
1449 u64 now = ktime_get_ns();
1450
1451 /*
1452 * Queue got expired before even a single request completed or
1453 * got expired immediately after first request completion.
1454 */
1455 if (!cfqq->slice_start || cfqq->slice_start == now) {
1456 /*
1457 * Also charge the seek time incurred to the group, otherwise
1458 * if there are mutiple queues in the group, each can dispatch
1459 * a single request on seeky media and cause lots of seek time
1460 * and group will never know it.
1461 */
1462 slice_used = max_t(u64, (now - cfqq->dispatch_start),
1463 jiffies_to_nsecs(1));
1464 } else {
1465 slice_used = now - cfqq->slice_start;
1466 if (slice_used > cfqq->allocated_slice) {
1467 *unaccounted_time = slice_used - cfqq->allocated_slice;
1468 slice_used = cfqq->allocated_slice;
1469 }
1470 if (cfqq->slice_start > cfqq->dispatch_start)
1471 *unaccounted_time += cfqq->slice_start -
1472 cfqq->dispatch_start;
1473 }
1474
1475 return slice_used;
1476 }
1477
1478 static void cfq_group_served(struct cfq_data *cfqd, struct cfq_group *cfqg,
1479 struct cfq_queue *cfqq)
1480 {
1481 struct cfq_rb_root *st = &cfqd->grp_service_tree;
1482 u64 used_sl, charge, unaccounted_sl = 0;
1483 int nr_sync = cfqg->nr_cfqq - cfqg_busy_async_queues(cfqd, cfqg)
1484 - cfqg->service_tree_idle.count;
1485 unsigned int vfr;
1486 u64 now = ktime_get_ns();
1487
1488 BUG_ON(nr_sync < 0);
1489 used_sl = charge = cfq_cfqq_slice_usage(cfqq, &unaccounted_sl);
1490
1491 if (iops_mode(cfqd))
1492 charge = cfqq->slice_dispatch;
1493 else if (!cfq_cfqq_sync(cfqq) && !nr_sync)
1494 charge = cfqq->allocated_slice;
1495
1496 /*
1497 * Can't update vdisktime while on service tree and cfqg->vfraction
1498 * is valid only while on it. Cache vfr, leave the service tree,
1499 * update vdisktime and go back on. The re-addition to the tree
1500 * will also update the weights as necessary.
1501 */
1502 vfr = cfqg->vfraction;
1503 cfq_group_service_tree_del(st, cfqg);
1504 cfqg->vdisktime += cfqg_scale_charge(charge, vfr);
1505 cfq_group_service_tree_add(st, cfqg);
1506
1507 /* This group is being expired. Save the context */
1508 if (cfqd->workload_expires > now) {
1509 cfqg->saved_wl_slice = cfqd->workload_expires - now;
1510 cfqg->saved_wl_type = cfqd->serving_wl_type;
1511 cfqg->saved_wl_class = cfqd->serving_wl_class;
1512 } else
1513 cfqg->saved_wl_slice = 0;
1514
1515 cfq_log_cfqg(cfqd, cfqg, "served: vt=%llu min_vt=%llu", cfqg->vdisktime,
1516 st->min_vdisktime);
1517 cfq_log_cfqq(cfqq->cfqd, cfqq,
1518 "sl_used=%llu disp=%llu charge=%llu iops=%u sect=%lu",
1519 used_sl, cfqq->slice_dispatch, charge,
1520 iops_mode(cfqd), cfqq->nr_sectors);
1521 cfqg_stats_update_timeslice_used(cfqg, used_sl, unaccounted_sl);
1522 cfqg_stats_set_start_empty_time(cfqg);
1523 }
1524
1525 /**
1526 * cfq_init_cfqg_base - initialize base part of a cfq_group
1527 * @cfqg: cfq_group to initialize
1528 *
1529 * Initialize the base part which is used whether %CONFIG_CFQ_GROUP_IOSCHED
1530 * is enabled or not.
1531 */
1532 static void cfq_init_cfqg_base(struct cfq_group *cfqg)
1533 {
1534 struct cfq_rb_root *st;
1535 int i, j;
1536
1537 for_each_cfqg_st(cfqg, i, j, st)
1538 *st = CFQ_RB_ROOT;
1539 RB_CLEAR_NODE(&cfqg->rb_node);
1540
1541 cfqg->ttime.last_end_request = ktime_get_ns();
1542 }
1543
1544 #ifdef CONFIG_CFQ_GROUP_IOSCHED
1545 static int __cfq_set_weight(struct cgroup_subsys_state *css, u64 val,
1546 bool on_dfl, bool reset_dev, bool is_leaf_weight);
1547
1548 static void cfqg_stats_exit(struct cfqg_stats *stats)
1549 {
1550 blkg_rwstat_exit(&stats->merged);
1551 blkg_rwstat_exit(&stats->service_time);
1552 blkg_rwstat_exit(&stats->wait_time);
1553 blkg_rwstat_exit(&stats->queued);
1554 blkg_stat_exit(&stats->time);
1555 #ifdef CONFIG_DEBUG_BLK_CGROUP
1556 blkg_stat_exit(&stats->unaccounted_time);
1557 blkg_stat_exit(&stats->avg_queue_size_sum);
1558 blkg_stat_exit(&stats->avg_queue_size_samples);
1559 blkg_stat_exit(&stats->dequeue);
1560 blkg_stat_exit(&stats->group_wait_time);
1561 blkg_stat_exit(&stats->idle_time);
1562 blkg_stat_exit(&stats->empty_time);
1563 #endif
1564 }
1565
1566 static int cfqg_stats_init(struct cfqg_stats *stats, gfp_t gfp)
1567 {
1568 if (blkg_rwstat_init(&stats->merged, gfp) ||
1569 blkg_rwstat_init(&stats->service_time, gfp) ||
1570 blkg_rwstat_init(&stats->wait_time, gfp) ||
1571 blkg_rwstat_init(&stats->queued, gfp) ||
1572 blkg_stat_init(&stats->time, gfp))
1573 goto err;
1574
1575 #ifdef CONFIG_DEBUG_BLK_CGROUP
1576 if (blkg_stat_init(&stats->unaccounted_time, gfp) ||
1577 blkg_stat_init(&stats->avg_queue_size_sum, gfp) ||
1578 blkg_stat_init(&stats->avg_queue_size_samples, gfp) ||
1579 blkg_stat_init(&stats->dequeue, gfp) ||
1580 blkg_stat_init(&stats->group_wait_time, gfp) ||
1581 blkg_stat_init(&stats->idle_time, gfp) ||
1582 blkg_stat_init(&stats->empty_time, gfp))
1583 goto err;
1584 #endif
1585 return 0;
1586 err:
1587 cfqg_stats_exit(stats);
1588 return -ENOMEM;
1589 }
1590
1591 static struct blkcg_policy_data *cfq_cpd_alloc(gfp_t gfp)
1592 {
1593 struct cfq_group_data *cgd;
1594
1595 cgd = kzalloc(sizeof(*cgd), gfp);
1596 if (!cgd)
1597 return NULL;
1598 return &cgd->cpd;
1599 }
1600
1601 static void cfq_cpd_init(struct blkcg_policy_data *cpd)
1602 {
1603 struct cfq_group_data *cgd = cpd_to_cfqgd(cpd);
1604 unsigned int weight = cgroup_subsys_on_dfl(io_cgrp_subsys) ?
1605 CGROUP_WEIGHT_DFL : CFQ_WEIGHT_LEGACY_DFL;
1606
1607 if (cpd_to_blkcg(cpd) == &blkcg_root)
1608 weight *= 2;
1609
1610 cgd->weight = weight;
1611 cgd->leaf_weight = weight;
1612 }
1613
1614 static void cfq_cpd_free(struct blkcg_policy_data *cpd)
1615 {
1616 kfree(cpd_to_cfqgd(cpd));
1617 }
1618
1619 static void cfq_cpd_bind(struct blkcg_policy_data *cpd)
1620 {
1621 struct blkcg *blkcg = cpd_to_blkcg(cpd);
1622 bool on_dfl = cgroup_subsys_on_dfl(io_cgrp_subsys);
1623 unsigned int weight = on_dfl ? CGROUP_WEIGHT_DFL : CFQ_WEIGHT_LEGACY_DFL;
1624
1625 if (blkcg == &blkcg_root)
1626 weight *= 2;
1627
1628 WARN_ON_ONCE(__cfq_set_weight(&blkcg->css, weight, on_dfl, true, false));
1629 WARN_ON_ONCE(__cfq_set_weight(&blkcg->css, weight, on_dfl, true, true));
1630 }
1631
1632 static struct blkg_policy_data *cfq_pd_alloc(gfp_t gfp, int node)
1633 {
1634 struct cfq_group *cfqg;
1635
1636 cfqg = kzalloc_node(sizeof(*cfqg), gfp, node);
1637 if (!cfqg)
1638 return NULL;
1639
1640 cfq_init_cfqg_base(cfqg);
1641 if (cfqg_stats_init(&cfqg->stats, gfp)) {
1642 kfree(cfqg);
1643 return NULL;
1644 }
1645
1646 return &cfqg->pd;
1647 }
1648
1649 static void cfq_pd_init(struct blkg_policy_data *pd)
1650 {
1651 struct cfq_group *cfqg = pd_to_cfqg(pd);
1652 struct cfq_group_data *cgd = blkcg_to_cfqgd(pd->blkg->blkcg);
1653
1654 cfqg->weight = cgd->weight;
1655 cfqg->leaf_weight = cgd->leaf_weight;
1656 }
1657
1658 static void cfq_pd_offline(struct blkg_policy_data *pd)
1659 {
1660 struct cfq_group *cfqg = pd_to_cfqg(pd);
1661 int i;
1662
1663 for (i = 0; i < IOPRIO_BE_NR; i++) {
1664 if (cfqg->async_cfqq[0][i])
1665 cfq_put_queue(cfqg->async_cfqq[0][i]);
1666 if (cfqg->async_cfqq[1][i])
1667 cfq_put_queue(cfqg->async_cfqq[1][i]);
1668 }
1669
1670 if (cfqg->async_idle_cfqq)
1671 cfq_put_queue(cfqg->async_idle_cfqq);
1672
1673 /*
1674 * @blkg is going offline and will be ignored by
1675 * blkg_[rw]stat_recursive_sum(). Transfer stats to the parent so
1676 * that they don't get lost. If IOs complete after this point, the
1677 * stats for them will be lost. Oh well...
1678 */
1679 cfqg_stats_xfer_dead(cfqg);
1680 }
1681
1682 static void cfq_pd_free(struct blkg_policy_data *pd)
1683 {
1684 struct cfq_group *cfqg = pd_to_cfqg(pd);
1685
1686 cfqg_stats_exit(&cfqg->stats);
1687 return kfree(cfqg);
1688 }
1689
1690 static void cfq_pd_reset_stats(struct blkg_policy_data *pd)
1691 {
1692 struct cfq_group *cfqg = pd_to_cfqg(pd);
1693
1694 cfqg_stats_reset(&cfqg->stats);
1695 }
1696
1697 static struct cfq_group *cfq_lookup_cfqg(struct cfq_data *cfqd,
1698 struct blkcg *blkcg)
1699 {
1700 struct blkcg_gq *blkg;
1701
1702 blkg = blkg_lookup(blkcg, cfqd->queue);
1703 if (likely(blkg))
1704 return blkg_to_cfqg(blkg);
1705 return NULL;
1706 }
1707
1708 static void cfq_link_cfqq_cfqg(struct cfq_queue *cfqq, struct cfq_group *cfqg)
1709 {
1710 cfqq->cfqg = cfqg;
1711 /* cfqq reference on cfqg */
1712 cfqg_get(cfqg);
1713 }
1714
1715 static u64 cfqg_prfill_weight_device(struct seq_file *sf,
1716 struct blkg_policy_data *pd, int off)
1717 {
1718 struct cfq_group *cfqg = pd_to_cfqg(pd);
1719
1720 if (!cfqg->dev_weight)
1721 return 0;
1722 return __blkg_prfill_u64(sf, pd, cfqg->dev_weight);
1723 }
1724
1725 static int cfqg_print_weight_device(struct seq_file *sf, void *v)
1726 {
1727 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1728 cfqg_prfill_weight_device, &blkcg_policy_cfq,
1729 0, false);
1730 return 0;
1731 }
1732
1733 static u64 cfqg_prfill_leaf_weight_device(struct seq_file *sf,
1734 struct blkg_policy_data *pd, int off)
1735 {
1736 struct cfq_group *cfqg = pd_to_cfqg(pd);
1737
1738 if (!cfqg->dev_leaf_weight)
1739 return 0;
1740 return __blkg_prfill_u64(sf, pd, cfqg->dev_leaf_weight);
1741 }
1742
1743 static int cfqg_print_leaf_weight_device(struct seq_file *sf, void *v)
1744 {
1745 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1746 cfqg_prfill_leaf_weight_device, &blkcg_policy_cfq,
1747 0, false);
1748 return 0;
1749 }
1750
1751 static int cfq_print_weight(struct seq_file *sf, void *v)
1752 {
1753 struct blkcg *blkcg = css_to_blkcg(seq_css(sf));
1754 struct cfq_group_data *cgd = blkcg_to_cfqgd(blkcg);
1755 unsigned int val = 0;
1756
1757 if (cgd)
1758 val = cgd->weight;
1759
1760 seq_printf(sf, "%u\n", val);
1761 return 0;
1762 }
1763
1764 static int cfq_print_leaf_weight(struct seq_file *sf, void *v)
1765 {
1766 struct blkcg *blkcg = css_to_blkcg(seq_css(sf));
1767 struct cfq_group_data *cgd = blkcg_to_cfqgd(blkcg);
1768 unsigned int val = 0;
1769
1770 if (cgd)
1771 val = cgd->leaf_weight;
1772
1773 seq_printf(sf, "%u\n", val);
1774 return 0;
1775 }
1776
1777 static ssize_t __cfqg_set_weight_device(struct kernfs_open_file *of,
1778 char *buf, size_t nbytes, loff_t off,
1779 bool on_dfl, bool is_leaf_weight)
1780 {
1781 unsigned int min = on_dfl ? CGROUP_WEIGHT_MIN : CFQ_WEIGHT_LEGACY_MIN;
1782 unsigned int max = on_dfl ? CGROUP_WEIGHT_MAX : CFQ_WEIGHT_LEGACY_MAX;
1783 struct blkcg *blkcg = css_to_blkcg(of_css(of));
1784 struct blkg_conf_ctx ctx;
1785 struct cfq_group *cfqg;
1786 struct cfq_group_data *cfqgd;
1787 int ret;
1788 u64 v;
1789
1790 ret = blkg_conf_prep(blkcg, &blkcg_policy_cfq, buf, &ctx);
1791 if (ret)
1792 return ret;
1793
1794 if (sscanf(ctx.body, "%llu", &v) == 1) {
1795 /* require "default" on dfl */
1796 ret = -ERANGE;
1797 if (!v && on_dfl)
1798 goto out_finish;
1799 } else if (!strcmp(strim(ctx.body), "default")) {
1800 v = 0;
1801 } else {
1802 ret = -EINVAL;
1803 goto out_finish;
1804 }
1805
1806 cfqg = blkg_to_cfqg(ctx.blkg);
1807 cfqgd = blkcg_to_cfqgd(blkcg);
1808
1809 ret = -ERANGE;
1810 if (!v || (v >= min && v <= max)) {
1811 if (!is_leaf_weight) {
1812 cfqg->dev_weight = v;
1813 cfqg->new_weight = v ?: cfqgd->weight;
1814 } else {
1815 cfqg->dev_leaf_weight = v;
1816 cfqg->new_leaf_weight = v ?: cfqgd->leaf_weight;
1817 }
1818 ret = 0;
1819 }
1820 out_finish:
1821 blkg_conf_finish(&ctx);
1822 return ret ?: nbytes;
1823 }
1824
1825 static ssize_t cfqg_set_weight_device(struct kernfs_open_file *of,
1826 char *buf, size_t nbytes, loff_t off)
1827 {
1828 return __cfqg_set_weight_device(of, buf, nbytes, off, false, false);
1829 }
1830
1831 static ssize_t cfqg_set_leaf_weight_device(struct kernfs_open_file *of,
1832 char *buf, size_t nbytes, loff_t off)
1833 {
1834 return __cfqg_set_weight_device(of, buf, nbytes, off, false, true);
1835 }
1836
1837 static int __cfq_set_weight(struct cgroup_subsys_state *css, u64 val,
1838 bool on_dfl, bool reset_dev, bool is_leaf_weight)
1839 {
1840 unsigned int min = on_dfl ? CGROUP_WEIGHT_MIN : CFQ_WEIGHT_LEGACY_MIN;
1841 unsigned int max = on_dfl ? CGROUP_WEIGHT_MAX : CFQ_WEIGHT_LEGACY_MAX;
1842 struct blkcg *blkcg = css_to_blkcg(css);
1843 struct blkcg_gq *blkg;
1844 struct cfq_group_data *cfqgd;
1845 int ret = 0;
1846
1847 if (val < min || val > max)
1848 return -ERANGE;
1849
1850 spin_lock_irq(&blkcg->lock);
1851 cfqgd = blkcg_to_cfqgd(blkcg);
1852 if (!cfqgd) {
1853 ret = -EINVAL;
1854 goto out;
1855 }
1856
1857 if (!is_leaf_weight)
1858 cfqgd->weight = val;
1859 else
1860 cfqgd->leaf_weight = val;
1861
1862 hlist_for_each_entry(blkg, &blkcg->blkg_list, blkcg_node) {
1863 struct cfq_group *cfqg = blkg_to_cfqg(blkg);
1864
1865 if (!cfqg)
1866 continue;
1867
1868 if (!is_leaf_weight) {
1869 if (reset_dev)
1870 cfqg->dev_weight = 0;
1871 if (!cfqg->dev_weight)
1872 cfqg->new_weight = cfqgd->weight;
1873 } else {
1874 if (reset_dev)
1875 cfqg->dev_leaf_weight = 0;
1876 if (!cfqg->dev_leaf_weight)
1877 cfqg->new_leaf_weight = cfqgd->leaf_weight;
1878 }
1879 }
1880
1881 out:
1882 spin_unlock_irq(&blkcg->lock);
1883 return ret;
1884 }
1885
1886 static int cfq_set_weight(struct cgroup_subsys_state *css, struct cftype *cft,
1887 u64 val)
1888 {
1889 return __cfq_set_weight(css, val, false, false, false);
1890 }
1891
1892 static int cfq_set_leaf_weight(struct cgroup_subsys_state *css,
1893 struct cftype *cft, u64 val)
1894 {
1895 return __cfq_set_weight(css, val, false, false, true);
1896 }
1897
1898 static int cfqg_print_stat(struct seq_file *sf, void *v)
1899 {
1900 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), blkg_prfill_stat,
1901 &blkcg_policy_cfq, seq_cft(sf)->private, false);
1902 return 0;
1903 }
1904
1905 static int cfqg_print_rwstat(struct seq_file *sf, void *v)
1906 {
1907 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), blkg_prfill_rwstat,
1908 &blkcg_policy_cfq, seq_cft(sf)->private, true);
1909 return 0;
1910 }
1911
1912 static u64 cfqg_prfill_stat_recursive(struct seq_file *sf,
1913 struct blkg_policy_data *pd, int off)
1914 {
1915 u64 sum = blkg_stat_recursive_sum(pd_to_blkg(pd),
1916 &blkcg_policy_cfq, off);
1917 return __blkg_prfill_u64(sf, pd, sum);
1918 }
1919
1920 static u64 cfqg_prfill_rwstat_recursive(struct seq_file *sf,
1921 struct blkg_policy_data *pd, int off)
1922 {
1923 struct blkg_rwstat sum = blkg_rwstat_recursive_sum(pd_to_blkg(pd),
1924 &blkcg_policy_cfq, off);
1925 return __blkg_prfill_rwstat(sf, pd, &sum);
1926 }
1927
1928 static int cfqg_print_stat_recursive(struct seq_file *sf, void *v)
1929 {
1930 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1931 cfqg_prfill_stat_recursive, &blkcg_policy_cfq,
1932 seq_cft(sf)->private, false);
1933 return 0;
1934 }
1935
1936 static int cfqg_print_rwstat_recursive(struct seq_file *sf, void *v)
1937 {
1938 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1939 cfqg_prfill_rwstat_recursive, &blkcg_policy_cfq,
1940 seq_cft(sf)->private, true);
1941 return 0;
1942 }
1943
1944 static u64 cfqg_prfill_sectors(struct seq_file *sf, struct blkg_policy_data *pd,
1945 int off)
1946 {
1947 u64 sum = blkg_rwstat_total(&pd->blkg->stat_bytes);
1948
1949 return __blkg_prfill_u64(sf, pd, sum >> 9);
1950 }
1951
1952 static int cfqg_print_stat_sectors(struct seq_file *sf, void *v)
1953 {
1954 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1955 cfqg_prfill_sectors, &blkcg_policy_cfq, 0, false);
1956 return 0;
1957 }
1958
1959 static u64 cfqg_prfill_sectors_recursive(struct seq_file *sf,
1960 struct blkg_policy_data *pd, int off)
1961 {
1962 struct blkg_rwstat tmp = blkg_rwstat_recursive_sum(pd->blkg, NULL,
1963 offsetof(struct blkcg_gq, stat_bytes));
1964 u64 sum = atomic64_read(&tmp.aux_cnt[BLKG_RWSTAT_READ]) +
1965 atomic64_read(&tmp.aux_cnt[BLKG_RWSTAT_WRITE]);
1966
1967 return __blkg_prfill_u64(sf, pd, sum >> 9);
1968 }
1969
1970 static int cfqg_print_stat_sectors_recursive(struct seq_file *sf, void *v)
1971 {
1972 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1973 cfqg_prfill_sectors_recursive, &blkcg_policy_cfq, 0,
1974 false);
1975 return 0;
1976 }
1977
1978 #ifdef CONFIG_DEBUG_BLK_CGROUP
1979 static u64 cfqg_prfill_avg_queue_size(struct seq_file *sf,
1980 struct blkg_policy_data *pd, int off)
1981 {
1982 struct cfq_group *cfqg = pd_to_cfqg(pd);
1983 u64 samples = blkg_stat_read(&cfqg->stats.avg_queue_size_samples);
1984 u64 v = 0;
1985
1986 if (samples) {
1987 v = blkg_stat_read(&cfqg->stats.avg_queue_size_sum);
1988 v = div64_u64(v, samples);
1989 }
1990 __blkg_prfill_u64(sf, pd, v);
1991 return 0;
1992 }
1993
1994 /* print avg_queue_size */
1995 static int cfqg_print_avg_queue_size(struct seq_file *sf, void *v)
1996 {
1997 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1998 cfqg_prfill_avg_queue_size, &blkcg_policy_cfq,
1999 0, false);
2000 return 0;
2001 }
2002 #endif /* CONFIG_DEBUG_BLK_CGROUP */
2003
2004 static struct cftype cfq_blkcg_legacy_files[] = {
2005 /* on root, weight is mapped to leaf_weight */
2006 {
2007 .name = "weight_device",
2008 .flags = CFTYPE_ONLY_ON_ROOT,
2009 .seq_show = cfqg_print_leaf_weight_device,
2010 .write = cfqg_set_leaf_weight_device,
2011 },
2012 {
2013 .name = "weight",
2014 .flags = CFTYPE_ONLY_ON_ROOT,
2015 .seq_show = cfq_print_leaf_weight,
2016 .write_u64 = cfq_set_leaf_weight,
2017 },
2018
2019 /* no such mapping necessary for !roots */
2020 {
2021 .name = "weight_device",
2022 .flags = CFTYPE_NOT_ON_ROOT,
2023 .seq_show = cfqg_print_weight_device,
2024 .write = cfqg_set_weight_device,
2025 },
2026 {
2027 .name = "weight",
2028 .flags = CFTYPE_NOT_ON_ROOT,
2029 .seq_show = cfq_print_weight,
2030 .write_u64 = cfq_set_weight,
2031 },
2032
2033 {
2034 .name = "leaf_weight_device",
2035 .seq_show = cfqg_print_leaf_weight_device,
2036 .write = cfqg_set_leaf_weight_device,
2037 },
2038 {
2039 .name = "leaf_weight",
2040 .seq_show = cfq_print_leaf_weight,
2041 .write_u64 = cfq_set_leaf_weight,
2042 },
2043
2044 /* statistics, covers only the tasks in the cfqg */
2045 {
2046 .name = "time",
2047 .private = offsetof(struct cfq_group, stats.time),
2048 .seq_show = cfqg_print_stat,
2049 },
2050 {
2051 .name = "sectors",
2052 .seq_show = cfqg_print_stat_sectors,
2053 },
2054 {
2055 .name = "io_service_bytes",
2056 .private = (unsigned long)&blkcg_policy_cfq,
2057 .seq_show = blkg_print_stat_bytes,
2058 },
2059 {
2060 .name = "io_serviced",
2061 .private = (unsigned long)&blkcg_policy_cfq,
2062 .seq_show = blkg_print_stat_ios,
2063 },
2064 {
2065 .name = "io_service_time",
2066 .private = offsetof(struct cfq_group, stats.service_time),
2067 .seq_show = cfqg_print_rwstat,
2068 },
2069 {
2070 .name = "io_wait_time",
2071 .private = offsetof(struct cfq_group, stats.wait_time),
2072 .seq_show = cfqg_print_rwstat,
2073 },
2074 {
2075 .name = "io_merged",
2076 .private = offsetof(struct cfq_group, stats.merged),
2077 .seq_show = cfqg_print_rwstat,
2078 },
2079 {
2080 .name = "io_queued",
2081 .private = offsetof(struct cfq_group, stats.queued),
2082 .seq_show = cfqg_print_rwstat,
2083 },
2084
2085 /* the same statictics which cover the cfqg and its descendants */
2086 {
2087 .name = "time_recursive",
2088 .private = offsetof(struct cfq_group, stats.time),
2089 .seq_show = cfqg_print_stat_recursive,
2090 },
2091 {
2092 .name = "sectors_recursive",
2093 .seq_show = cfqg_print_stat_sectors_recursive,
2094 },
2095 {
2096 .name = "io_service_bytes_recursive",
2097 .private = (unsigned long)&blkcg_policy_cfq,
2098 .seq_show = blkg_print_stat_bytes_recursive,
2099 },
2100 {
2101 .name = "io_serviced_recursive",
2102 .private = (unsigned long)&blkcg_policy_cfq,
2103 .seq_show = blkg_print_stat_ios_recursive,
2104 },
2105 {
2106 .name = "io_service_time_recursive",
2107 .private = offsetof(struct cfq_group, stats.service_time),
2108 .seq_show = cfqg_print_rwstat_recursive,
2109 },
2110 {
2111 .name = "io_wait_time_recursive",
2112 .private = offsetof(struct cfq_group, stats.wait_time),
2113 .seq_show = cfqg_print_rwstat_recursive,
2114 },
2115 {
2116 .name = "io_merged_recursive",
2117 .private = offsetof(struct cfq_group, stats.merged),
2118 .seq_show = cfqg_print_rwstat_recursive,
2119 },
2120 {
2121 .name = "io_queued_recursive",
2122 .private = offsetof(struct cfq_group, stats.queued),
2123 .seq_show = cfqg_print_rwstat_recursive,
2124 },
2125 #ifdef CONFIG_DEBUG_BLK_CGROUP
2126 {
2127 .name = "avg_queue_size",
2128 .seq_show = cfqg_print_avg_queue_size,
2129 },
2130 {
2131 .name = "group_wait_time",
2132 .private = offsetof(struct cfq_group, stats.group_wait_time),
2133 .seq_show = cfqg_print_stat,
2134 },
2135 {
2136 .name = "idle_time",
2137 .private = offsetof(struct cfq_group, stats.idle_time),
2138 .seq_show = cfqg_print_stat,
2139 },
2140 {
2141 .name = "empty_time",
2142 .private = offsetof(struct cfq_group, stats.empty_time),
2143 .seq_show = cfqg_print_stat,
2144 },
2145 {
2146 .name = "dequeue",
2147 .private = offsetof(struct cfq_group, stats.dequeue),
2148 .seq_show = cfqg_print_stat,
2149 },
2150 {
2151 .name = "unaccounted_time",
2152 .private = offsetof(struct cfq_group, stats.unaccounted_time),
2153 .seq_show = cfqg_print_stat,
2154 },
2155 #endif /* CONFIG_DEBUG_BLK_CGROUP */
2156 { } /* terminate */
2157 };
2158
2159 static int cfq_print_weight_on_dfl(struct seq_file *sf, void *v)
2160 {
2161 struct blkcg *blkcg = css_to_blkcg(seq_css(sf));
2162 struct cfq_group_data *cgd = blkcg_to_cfqgd(blkcg);
2163
2164 seq_printf(sf, "default %u\n", cgd->weight);
2165 blkcg_print_blkgs(sf, blkcg, cfqg_prfill_weight_device,
2166 &blkcg_policy_cfq, 0, false);
2167 return 0;
2168 }
2169
2170 static ssize_t cfq_set_weight_on_dfl(struct kernfs_open_file *of,
2171 char *buf, size_t nbytes, loff_t off)
2172 {
2173 char *endp;
2174 int ret;
2175 u64 v;
2176
2177 buf = strim(buf);
2178
2179 /* "WEIGHT" or "default WEIGHT" sets the default weight */
2180 v = simple_strtoull(buf, &endp, 0);
2181 if (*endp == '\0' || sscanf(buf, "default %llu", &v) == 1) {
2182 ret = __cfq_set_weight(of_css(of), v, true, false, false);
2183 return ret ?: nbytes;
2184 }
2185
2186 /* "MAJ:MIN WEIGHT" */
2187 return __cfqg_set_weight_device(of, buf, nbytes, off, true, false);
2188 }
2189
2190 static struct cftype cfq_blkcg_files[] = {
2191 {
2192 .name = "weight",
2193 .flags = CFTYPE_NOT_ON_ROOT,
2194 .seq_show = cfq_print_weight_on_dfl,
2195 .write = cfq_set_weight_on_dfl,
2196 },
2197 { } /* terminate */
2198 };
2199
2200 #else /* GROUP_IOSCHED */
2201 static struct cfq_group *cfq_lookup_cfqg(struct cfq_data *cfqd,
2202 struct blkcg *blkcg)
2203 {
2204 return cfqd->root_group;
2205 }
2206
2207 static inline void
2208 cfq_link_cfqq_cfqg(struct cfq_queue *cfqq, struct cfq_group *cfqg) {
2209 cfqq->cfqg = cfqg;
2210 }
2211
2212 #endif /* GROUP_IOSCHED */
2213
2214 /*
2215 * The cfqd->service_trees holds all pending cfq_queue's that have
2216 * requests waiting to be processed. It is sorted in the order that
2217 * we will service the queues.
2218 */
2219 static void cfq_service_tree_add(struct cfq_data *cfqd, struct cfq_queue *cfqq,
2220 bool add_front)
2221 {
2222 struct rb_node **p, *parent;
2223 struct cfq_queue *__cfqq;
2224 u64 rb_key;
2225 struct cfq_rb_root *st;
2226 int left;
2227 int new_cfqq = 1;
2228 u64 now = ktime_get_ns();
2229
2230 st = st_for(cfqq->cfqg, cfqq_class(cfqq), cfqq_type(cfqq));
2231 if (cfq_class_idle(cfqq)) {
2232 rb_key = CFQ_IDLE_DELAY;
2233 parent = rb_last(&st->rb);
2234 if (parent && parent != &cfqq->rb_node) {
2235 __cfqq = rb_entry(parent, struct cfq_queue, rb_node);
2236 rb_key += __cfqq->rb_key;
2237 } else
2238 rb_key += now;
2239 } else if (!add_front) {
2240 /*
2241 * Get our rb key offset. Subtract any residual slice
2242 * value carried from last service. A negative resid
2243 * count indicates slice overrun, and this should position
2244 * the next service time further away in the tree.
2245 */
2246 rb_key = cfq_slice_offset(cfqd, cfqq) + now;
2247 rb_key -= cfqq->slice_resid;
2248 cfqq->slice_resid = 0;
2249 } else {
2250 rb_key = -NSEC_PER_SEC;
2251 __cfqq = cfq_rb_first(st);
2252 rb_key += __cfqq ? __cfqq->rb_key : now;
2253 }
2254
2255 if (!RB_EMPTY_NODE(&cfqq->rb_node)) {
2256 new_cfqq = 0;
2257 /*
2258 * same position, nothing more to do
2259 */
2260 if (rb_key == cfqq->rb_key && cfqq->service_tree == st)
2261 return;
2262
2263 cfq_rb_erase(&cfqq->rb_node, cfqq->service_tree);
2264 cfqq->service_tree = NULL;
2265 }
2266
2267 left = 1;
2268 parent = NULL;
2269 cfqq->service_tree = st;
2270 p = &st->rb.rb_node;
2271 while (*p) {
2272 parent = *p;
2273 __cfqq = rb_entry(parent, struct cfq_queue, rb_node);
2274
2275 /*
2276 * sort by key, that represents service time.
2277 */
2278 if (rb_key < __cfqq->rb_key)
2279 p = &parent->rb_left;
2280 else {
2281 p = &parent->rb_right;
2282 left = 0;
2283 }
2284 }
2285
2286 if (left)
2287 st->left = &cfqq->rb_node;
2288
2289 cfqq->rb_key = rb_key;
2290 rb_link_node(&cfqq->rb_node, parent, p);
2291 rb_insert_color(&cfqq->rb_node, &st->rb);
2292 st->count++;
2293 if (add_front || !new_cfqq)
2294 return;
2295 cfq_group_notify_queue_add(cfqd, cfqq->cfqg);
2296 }
2297
2298 static struct cfq_queue *
2299 cfq_prio_tree_lookup(struct cfq_data *cfqd, struct rb_root *root,
2300 sector_t sector, struct rb_node **ret_parent,
2301 struct rb_node ***rb_link)
2302 {
2303 struct rb_node **p, *parent;
2304 struct cfq_queue *cfqq = NULL;
2305
2306 parent = NULL;
2307 p = &root->rb_node;
2308 while (*p) {
2309 struct rb_node **n;
2310
2311 parent = *p;
2312 cfqq = rb_entry(parent, struct cfq_queue, p_node);
2313
2314 /*
2315 * Sort strictly based on sector. Smallest to the left,
2316 * largest to the right.
2317 */
2318 if (sector > blk_rq_pos(cfqq->next_rq))
2319 n = &(*p)->rb_right;
2320 else if (sector < blk_rq_pos(cfqq->next_rq))
2321 n = &(*p)->rb_left;
2322 else
2323 break;
2324 p = n;
2325 cfqq = NULL;
2326 }
2327
2328 *ret_parent = parent;
2329 if (rb_link)
2330 *rb_link = p;
2331 return cfqq;
2332 }
2333
2334 static void cfq_prio_tree_add(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2335 {
2336 struct rb_node **p, *parent;
2337 struct cfq_queue *__cfqq;
2338
2339 if (cfqq->p_root) {
2340 rb_erase(&cfqq->p_node, cfqq->p_root);
2341 cfqq->p_root = NULL;
2342 }
2343
2344 if (cfq_class_idle(cfqq))
2345 return;
2346 if (!cfqq->next_rq)
2347 return;
2348
2349 cfqq->p_root = &cfqd->prio_trees[cfqq->org_ioprio];
2350 __cfqq = cfq_prio_tree_lookup(cfqd, cfqq->p_root,
2351 blk_rq_pos(cfqq->next_rq), &parent, &p);
2352 if (!__cfqq) {
2353 rb_link_node(&cfqq->p_node, parent, p);
2354 rb_insert_color(&cfqq->p_node, cfqq->p_root);
2355 } else
2356 cfqq->p_root = NULL;
2357 }
2358
2359 /*
2360 * Update cfqq's position in the service tree.
2361 */
2362 static void cfq_resort_rr_list(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2363 {
2364 /*
2365 * Resorting requires the cfqq to be on the RR list already.
2366 */
2367 if (cfq_cfqq_on_rr(cfqq)) {
2368 cfq_service_tree_add(cfqd, cfqq, 0);
2369 cfq_prio_tree_add(cfqd, cfqq);
2370 }
2371 }
2372
2373 /*
2374 * add to busy list of queues for service, trying to be fair in ordering
2375 * the pending list according to last request service
2376 */
2377 static void cfq_add_cfqq_rr(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2378 {
2379 cfq_log_cfqq(cfqd, cfqq, "add_to_rr");
2380 BUG_ON(cfq_cfqq_on_rr(cfqq));
2381 cfq_mark_cfqq_on_rr(cfqq);
2382 cfqd->busy_queues++;
2383 if (cfq_cfqq_sync(cfqq))
2384 cfqd->busy_sync_queues++;
2385
2386 cfq_resort_rr_list(cfqd, cfqq);
2387 }
2388
2389 /*
2390 * Called when the cfqq no longer has requests pending, remove it from
2391 * the service tree.
2392 */
2393 static void cfq_del_cfqq_rr(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2394 {
2395 cfq_log_cfqq(cfqd, cfqq, "del_from_rr");
2396 BUG_ON(!cfq_cfqq_on_rr(cfqq));
2397 cfq_clear_cfqq_on_rr(cfqq);
2398
2399 if (!RB_EMPTY_NODE(&cfqq->rb_node)) {
2400 cfq_rb_erase(&cfqq->rb_node, cfqq->service_tree);
2401 cfqq->service_tree = NULL;
2402 }
2403 if (cfqq->p_root) {
2404 rb_erase(&cfqq->p_node, cfqq->p_root);
2405 cfqq->p_root = NULL;
2406 }
2407
2408 cfq_group_notify_queue_del(cfqd, cfqq->cfqg);
2409 BUG_ON(!cfqd->busy_queues);
2410 cfqd->busy_queues--;
2411 if (cfq_cfqq_sync(cfqq))
2412 cfqd->busy_sync_queues--;
2413 }
2414
2415 /*
2416 * rb tree support functions
2417 */
2418 static void cfq_del_rq_rb(struct request *rq)
2419 {
2420 struct cfq_queue *cfqq = RQ_CFQQ(rq);
2421 const int sync = rq_is_sync(rq);
2422
2423 BUG_ON(!cfqq->queued[sync]);
2424 cfqq->queued[sync]--;
2425
2426 elv_rb_del(&cfqq->sort_list, rq);
2427
2428 if (cfq_cfqq_on_rr(cfqq) && RB_EMPTY_ROOT(&cfqq->sort_list)) {
2429 /*
2430 * Queue will be deleted from service tree when we actually
2431 * expire it later. Right now just remove it from prio tree
2432 * as it is empty.
2433 */
2434 if (cfqq->p_root) {
2435 rb_erase(&cfqq->p_node, cfqq->p_root);
2436 cfqq->p_root = NULL;
2437 }
2438 }
2439 }
2440
2441 static void cfq_add_rq_rb(struct request *rq)
2442 {
2443 struct cfq_queue *cfqq = RQ_CFQQ(rq);
2444 struct cfq_data *cfqd = cfqq->cfqd;
2445 struct request *prev;
2446
2447 cfqq->queued[rq_is_sync(rq)]++;
2448
2449 elv_rb_add(&cfqq->sort_list, rq);
2450
2451 if (!cfq_cfqq_on_rr(cfqq))
2452 cfq_add_cfqq_rr(cfqd, cfqq);
2453
2454 /*
2455 * check if this request is a better next-serve candidate
2456 */
2457 prev = cfqq->next_rq;
2458 cfqq->next_rq = cfq_choose_req(cfqd, cfqq->next_rq, rq, cfqd->last_position);
2459
2460 /*
2461 * adjust priority tree position, if ->next_rq changes
2462 */
2463 if (prev != cfqq->next_rq)
2464 cfq_prio_tree_add(cfqd, cfqq);
2465
2466 BUG_ON(!cfqq->next_rq);
2467 }
2468
2469 static void cfq_reposition_rq_rb(struct cfq_queue *cfqq, struct request *rq)
2470 {
2471 elv_rb_del(&cfqq->sort_list, rq);
2472 cfqq->queued[rq_is_sync(rq)]--;
2473 cfqg_stats_update_io_remove(RQ_CFQG(rq), rq->cmd_flags);
2474 cfq_add_rq_rb(rq);
2475 cfqg_stats_update_io_add(RQ_CFQG(rq), cfqq->cfqd->serving_group,
2476 rq->cmd_flags);
2477 }
2478
2479 static struct request *
2480 cfq_find_rq_fmerge(struct cfq_data *cfqd, struct bio *bio)
2481 {
2482 struct task_struct *tsk = current;
2483 struct cfq_io_cq *cic;
2484 struct cfq_queue *cfqq;
2485
2486 cic = cfq_cic_lookup(cfqd, tsk->io_context);
2487 if (!cic)
2488 return NULL;
2489
2490 cfqq = cic_to_cfqq(cic, op_is_sync(bio->bi_opf));
2491 if (cfqq)
2492 return elv_rb_find(&cfqq->sort_list, bio_end_sector(bio));
2493
2494 return NULL;
2495 }
2496
2497 static void cfq_activate_request(struct request_queue *q, struct request *rq)
2498 {
2499 struct cfq_data *cfqd = q->elevator->elevator_data;
2500
2501 cfqd->rq_in_driver++;
2502 cfq_log_cfqq(cfqd, RQ_CFQQ(rq), "activate rq, drv=%d",
2503 cfqd->rq_in_driver);
2504
2505 cfqd->last_position = blk_rq_pos(rq) + blk_rq_sectors(rq);
2506 }
2507
2508 static void cfq_deactivate_request(struct request_queue *q, struct request *rq)
2509 {
2510 struct cfq_data *cfqd = q->elevator->elevator_data;
2511
2512 WARN_ON(!cfqd->rq_in_driver);
2513 cfqd->rq_in_driver--;
2514 cfq_log_cfqq(cfqd, RQ_CFQQ(rq), "deactivate rq, drv=%d",
2515 cfqd->rq_in_driver);
2516 }
2517
2518 static void cfq_remove_request(struct request *rq)
2519 {
2520 struct cfq_queue *cfqq = RQ_CFQQ(rq);
2521
2522 if (cfqq->next_rq == rq)
2523 cfqq->next_rq = cfq_find_next_rq(cfqq->cfqd, cfqq, rq);
2524
2525 list_del_init(&rq->queuelist);
2526 cfq_del_rq_rb(rq);
2527
2528 cfqq->cfqd->rq_queued--;
2529 cfqg_stats_update_io_remove(RQ_CFQG(rq), rq->cmd_flags);
2530 if (rq->cmd_flags & REQ_PRIO) {
2531 WARN_ON(!cfqq->prio_pending);
2532 cfqq->prio_pending--;
2533 }
2534 }
2535
2536 static enum elv_merge cfq_merge(struct request_queue *q, struct request **req,
2537 struct bio *bio)
2538 {
2539 struct cfq_data *cfqd = q->elevator->elevator_data;
2540 struct request *__rq;
2541
2542 __rq = cfq_find_rq_fmerge(cfqd, bio);
2543 if (__rq && elv_bio_merge_ok(__rq, bio)) {
2544 *req = __rq;
2545 return ELEVATOR_FRONT_MERGE;
2546 }
2547
2548 return ELEVATOR_NO_MERGE;
2549 }
2550
2551 static void cfq_merged_request(struct request_queue *q, struct request *req,
2552 enum elv_merge type)
2553 {
2554 if (type == ELEVATOR_FRONT_MERGE) {
2555 struct cfq_queue *cfqq = RQ_CFQQ(req);
2556
2557 cfq_reposition_rq_rb(cfqq, req);
2558 }
2559 }
2560
2561 static void cfq_bio_merged(struct request_queue *q, struct request *req,
2562 struct bio *bio)
2563 {
2564 cfqg_stats_update_io_merged(RQ_CFQG(req), bio->bi_opf);
2565 }
2566
2567 static void
2568 cfq_merged_requests(struct request_queue *q, struct request *rq,
2569 struct request *next)
2570 {
2571 struct cfq_queue *cfqq = RQ_CFQQ(rq);
2572 struct cfq_data *cfqd = q->elevator->elevator_data;
2573
2574 /*
2575 * reposition in fifo if next is older than rq
2576 */
2577 if (!list_empty(&rq->queuelist) && !list_empty(&next->queuelist) &&
2578 next->fifo_time < rq->fifo_time &&
2579 cfqq == RQ_CFQQ(next)) {
2580 list_move(&rq->queuelist, &next->queuelist);
2581 rq->fifo_time = next->fifo_time;
2582 }
2583
2584 if (cfqq->next_rq == next)
2585 cfqq->next_rq = rq;
2586 cfq_remove_request(next);
2587 cfqg_stats_update_io_merged(RQ_CFQG(rq), next->cmd_flags);
2588
2589 cfqq = RQ_CFQQ(next);
2590 /*
2591 * all requests of this queue are merged to other queues, delete it
2592 * from the service tree. If it's the active_queue,
2593 * cfq_dispatch_requests() will choose to expire it or do idle
2594 */
2595 if (cfq_cfqq_on_rr(cfqq) && RB_EMPTY_ROOT(&cfqq->sort_list) &&
2596 cfqq != cfqd->active_queue)
2597 cfq_del_cfqq_rr(cfqd, cfqq);
2598 }
2599
2600 static int cfq_allow_bio_merge(struct request_queue *q, struct request *rq,
2601 struct bio *bio)
2602 {
2603 struct cfq_data *cfqd = q->elevator->elevator_data;
2604 bool is_sync = op_is_sync(bio->bi_opf);
2605 struct cfq_io_cq *cic;
2606 struct cfq_queue *cfqq;
2607
2608 /*
2609 * Disallow merge of a sync bio into an async request.
2610 */
2611 if (is_sync && !rq_is_sync(rq))
2612 return false;
2613
2614 /*
2615 * Lookup the cfqq that this bio will be queued with and allow
2616 * merge only if rq is queued there.
2617 */
2618 cic = cfq_cic_lookup(cfqd, current->io_context);
2619 if (!cic)
2620 return false;
2621
2622 cfqq = cic_to_cfqq(cic, is_sync);
2623 return cfqq == RQ_CFQQ(rq);
2624 }
2625
2626 static int cfq_allow_rq_merge(struct request_queue *q, struct request *rq,
2627 struct request *next)
2628 {
2629 return RQ_CFQQ(rq) == RQ_CFQQ(next);
2630 }
2631
2632 static inline void cfq_del_timer(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2633 {
2634 hrtimer_try_to_cancel(&cfqd->idle_slice_timer);
2635 cfqg_stats_update_idle_time(cfqq->cfqg);
2636 }
2637
2638 static void __cfq_set_active_queue(struct cfq_data *cfqd,
2639 struct cfq_queue *cfqq)
2640 {
2641 if (cfqq) {
2642 cfq_log_cfqq(cfqd, cfqq, "set_active wl_class:%d wl_type:%d",
2643 cfqd->serving_wl_class, cfqd->serving_wl_type);
2644 cfqg_stats_update_avg_queue_size(cfqq->cfqg);
2645 cfqq->slice_start = 0;
2646 cfqq->dispatch_start = ktime_get_ns();
2647 cfqq->allocated_slice = 0;
2648 cfqq->slice_end = 0;
2649 cfqq->slice_dispatch = 0;
2650 cfqq->nr_sectors = 0;
2651
2652 cfq_clear_cfqq_wait_request(cfqq);
2653 cfq_clear_cfqq_must_dispatch(cfqq);
2654 cfq_clear_cfqq_must_alloc_slice(cfqq);
2655 cfq_clear_cfqq_fifo_expire(cfqq);
2656 cfq_mark_cfqq_slice_new(cfqq);
2657
2658 cfq_del_timer(cfqd, cfqq);
2659 }
2660
2661 cfqd->active_queue = cfqq;
2662 }
2663
2664 /*
2665 * current cfqq expired its slice (or was too idle), select new one
2666 */
2667 static void
2668 __cfq_slice_expired(struct cfq_data *cfqd, struct cfq_queue *cfqq,
2669 bool timed_out)
2670 {
2671 cfq_log_cfqq(cfqd, cfqq, "slice expired t=%d", timed_out);
2672
2673 if (cfq_cfqq_wait_request(cfqq))
2674 cfq_del_timer(cfqd, cfqq);
2675
2676 cfq_clear_cfqq_wait_request(cfqq);
2677 cfq_clear_cfqq_wait_busy(cfqq);
2678
2679 /*
2680 * If this cfqq is shared between multiple processes, check to
2681 * make sure that those processes are still issuing I/Os within
2682 * the mean seek distance. If not, it may be time to break the
2683 * queues apart again.
2684 */
2685 if (cfq_cfqq_coop(cfqq) && CFQQ_SEEKY(cfqq))
2686 cfq_mark_cfqq_split_coop(cfqq);
2687
2688 /*
2689 * store what was left of this slice, if the queue idled/timed out
2690 */
2691 if (timed_out) {
2692 if (cfq_cfqq_slice_new(cfqq))
2693 cfqq->slice_resid = cfq_scaled_cfqq_slice(cfqd, cfqq);
2694 else
2695 cfqq->slice_resid = cfqq->slice_end - ktime_get_ns();
2696 cfq_log_cfqq(cfqd, cfqq, "resid=%lld", cfqq->slice_resid);
2697 }
2698
2699 cfq_group_served(cfqd, cfqq->cfqg, cfqq);
2700
2701 if (cfq_cfqq_on_rr(cfqq) && RB_EMPTY_ROOT(&cfqq->sort_list))
2702 cfq_del_cfqq_rr(cfqd, cfqq);
2703
2704 cfq_resort_rr_list(cfqd, cfqq);
2705
2706 if (cfqq == cfqd->active_queue)
2707 cfqd->active_queue = NULL;
2708
2709 if (cfqd->active_cic) {
2710 put_io_context(cfqd->active_cic->icq.ioc);
2711 cfqd->active_cic = NULL;
2712 }
2713 }
2714
2715 static inline void cfq_slice_expired(struct cfq_data *cfqd, bool timed_out)
2716 {
2717 struct cfq_queue *cfqq = cfqd->active_queue;
2718
2719 if (cfqq)
2720 __cfq_slice_expired(cfqd, cfqq, timed_out);
2721 }
2722
2723 /*
2724 * Get next queue for service. Unless we have a queue preemption,
2725 * we'll simply select the first cfqq in the service tree.
2726 */
2727 static struct cfq_queue *cfq_get_next_queue(struct cfq_data *cfqd)
2728 {
2729 struct cfq_rb_root *st = st_for(cfqd->serving_group,
2730 cfqd->serving_wl_class, cfqd->serving_wl_type);
2731
2732 if (!cfqd->rq_queued)
2733 return NULL;
2734
2735 /* There is nothing to dispatch */
2736 if (!st)
2737 return NULL;
2738 if (RB_EMPTY_ROOT(&st->rb))
2739 return NULL;
2740 return cfq_rb_first(st);
2741 }
2742
2743 static struct cfq_queue *cfq_get_next_queue_forced(struct cfq_data *cfqd)
2744 {
2745 struct cfq_group *cfqg;
2746 struct cfq_queue *cfqq;
2747 int i, j;
2748 struct cfq_rb_root *st;
2749
2750 if (!cfqd->rq_queued)
2751 return NULL;
2752
2753 cfqg = cfq_get_next_cfqg(cfqd);
2754 if (!cfqg)
2755 return NULL;
2756
2757 for_each_cfqg_st(cfqg, i, j, st) {
2758 cfqq = cfq_rb_first(st);
2759 if (cfqq)
2760 return cfqq;
2761 }
2762 return NULL;
2763 }
2764
2765 /*
2766 * Get and set a new active queue for service.
2767 */
2768 static struct cfq_queue *cfq_set_active_queue(struct cfq_data *cfqd,
2769 struct cfq_queue *cfqq)
2770 {
2771 if (!cfqq)
2772 cfqq = cfq_get_next_queue(cfqd);
2773
2774 __cfq_set_active_queue(cfqd, cfqq);
2775 return cfqq;
2776 }
2777
2778 static inline sector_t cfq_dist_from_last(struct cfq_data *cfqd,
2779 struct request *rq)
2780 {
2781 if (blk_rq_pos(rq) >= cfqd->last_position)
2782 return blk_rq_pos(rq) - cfqd->last_position;
2783 else
2784 return cfqd->last_position - blk_rq_pos(rq);
2785 }
2786
2787 static inline int cfq_rq_close(struct cfq_data *cfqd, struct cfq_queue *cfqq,
2788 struct request *rq)
2789 {
2790 return cfq_dist_from_last(cfqd, rq) <= CFQQ_CLOSE_THR;
2791 }
2792
2793 static struct cfq_queue *cfqq_close(struct cfq_data *cfqd,
2794 struct cfq_queue *cur_cfqq)
2795 {
2796 struct rb_root *root = &cfqd->prio_trees[cur_cfqq->org_ioprio];
2797 struct rb_node *parent, *node;
2798 struct cfq_queue *__cfqq;
2799 sector_t sector = cfqd->last_position;
2800
2801 if (RB_EMPTY_ROOT(root))
2802 return NULL;
2803
2804 /*
2805 * First, if we find a request starting at the end of the last
2806 * request, choose it.
2807 */
2808 __cfqq = cfq_prio_tree_lookup(cfqd, root, sector, &parent, NULL);
2809 if (__cfqq)
2810 return __cfqq;
2811
2812 /*
2813 * If the exact sector wasn't found, the parent of the NULL leaf
2814 * will contain the closest sector.
2815 */
2816 __cfqq = rb_entry(parent, struct cfq_queue, p_node);
2817 if (cfq_rq_close(cfqd, cur_cfqq, __cfqq->next_rq))
2818 return __cfqq;
2819
2820 if (blk_rq_pos(__cfqq->next_rq) < sector)
2821 node = rb_next(&__cfqq->p_node);
2822 else
2823 node = rb_prev(&__cfqq->p_node);
2824 if (!node)
2825 return NULL;
2826
2827 __cfqq = rb_entry(node, struct cfq_queue, p_node);
2828 if (cfq_rq_close(cfqd, cur_cfqq, __cfqq->next_rq))
2829 return __cfqq;
2830
2831 return NULL;
2832 }
2833
2834 /*
2835 * cfqd - obvious
2836 * cur_cfqq - passed in so that we don't decide that the current queue is
2837 * closely cooperating with itself.
2838 *
2839 * So, basically we're assuming that that cur_cfqq has dispatched at least
2840 * one request, and that cfqd->last_position reflects a position on the disk
2841 * associated with the I/O issued by cur_cfqq. I'm not sure this is a valid
2842 * assumption.
2843 */
2844 static struct cfq_queue *cfq_close_cooperator(struct cfq_data *cfqd,
2845 struct cfq_queue *cur_cfqq)
2846 {
2847 struct cfq_queue *cfqq;
2848
2849 if (cfq_class_idle(cur_cfqq))
2850 return NULL;
2851 if (!cfq_cfqq_sync(cur_cfqq))
2852 return NULL;
2853 if (CFQQ_SEEKY(cur_cfqq))
2854 return NULL;
2855
2856 /*
2857 * Don't search priority tree if it's the only queue in the group.
2858 */
2859 if (cur_cfqq->cfqg->nr_cfqq == 1)
2860 return NULL;
2861
2862 /*
2863 * We should notice if some of the queues are cooperating, eg
2864 * working closely on the same area of the disk. In that case,
2865 * we can group them together and don't waste time idling.
2866 */
2867 cfqq = cfqq_close(cfqd, cur_cfqq);
2868 if (!cfqq)
2869 return NULL;
2870
2871 /* If new queue belongs to different cfq_group, don't choose it */
2872 if (cur_cfqq->cfqg != cfqq->cfqg)
2873 return NULL;
2874
2875 /*
2876 * It only makes sense to merge sync queues.
2877 */
2878 if (!cfq_cfqq_sync(cfqq))
2879 return NULL;
2880 if (CFQQ_SEEKY(cfqq))
2881 return NULL;
2882
2883 /*
2884 * Do not merge queues of different priority classes
2885 */
2886 if (cfq_class_rt(cfqq) != cfq_class_rt(cur_cfqq))
2887 return NULL;
2888
2889 return cfqq;
2890 }
2891
2892 /*
2893 * Determine whether we should enforce idle window for this queue.
2894 */
2895
2896 static bool cfq_should_idle(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2897 {
2898 enum wl_class_t wl_class = cfqq_class(cfqq);
2899 struct cfq_rb_root *st = cfqq->service_tree;
2900
2901 BUG_ON(!st);
2902 BUG_ON(!st->count);
2903
2904 if (!cfqd->cfq_slice_idle)
2905 return false;
2906
2907 /* We never do for idle class queues. */
2908 if (wl_class == IDLE_WORKLOAD)
2909 return false;
2910
2911 /* We do for queues that were marked with idle window flag. */
2912 if (cfq_cfqq_idle_window(cfqq) &&
2913 !(blk_queue_nonrot(cfqd->queue) && cfqd->hw_tag))
2914 return true;
2915
2916 /*
2917 * Otherwise, we do only if they are the last ones
2918 * in their service tree.
2919 */
2920 if (st->count == 1 && cfq_cfqq_sync(cfqq) &&
2921 !cfq_io_thinktime_big(cfqd, &st->ttime, false))
2922 return true;
2923 cfq_log_cfqq(cfqd, cfqq, "Not idling. st->count:%d", st->count);
2924 return false;
2925 }
2926
2927 static void cfq_arm_slice_timer(struct cfq_data *cfqd)
2928 {
2929 struct cfq_queue *cfqq = cfqd->active_queue;
2930 struct cfq_rb_root *st = cfqq->service_tree;
2931 struct cfq_io_cq *cic;
2932 u64 sl, group_idle = 0;
2933 u64 now = ktime_get_ns();
2934
2935 /*
2936 * SSD device without seek penalty, disable idling. But only do so
2937 * for devices that support queuing, otherwise we still have a problem
2938 * with sync vs async workloads.
2939 */
2940 if (blk_queue_nonrot(cfqd->queue) && cfqd->hw_tag)
2941 return;
2942
2943 WARN_ON(!RB_EMPTY_ROOT(&cfqq->sort_list));
2944 WARN_ON(cfq_cfqq_slice_new(cfqq));
2945
2946 /*
2947 * idle is disabled, either manually or by past process history
2948 */
2949 if (!cfq_should_idle(cfqd, cfqq)) {
2950 /* no queue idling. Check for group idling */
2951 if (cfqd->cfq_group_idle)
2952 group_idle = cfqd->cfq_group_idle;
2953 else
2954 return;
2955 }
2956
2957 /*
2958 * still active requests from this queue, don't idle
2959 */
2960 if (cfqq->dispatched)
2961 return;
2962
2963 /*
2964 * task has exited, don't wait
2965 */
2966 cic = cfqd->active_cic;
2967 if (!cic || !atomic_read(&cic->icq.ioc->active_ref))
2968 return;
2969
2970 /*
2971 * If our average think time is larger than the remaining time
2972 * slice, then don't idle. This avoids overrunning the allotted
2973 * time slice.
2974 */
2975 if (sample_valid(cic->ttime.ttime_samples) &&
2976 (cfqq->slice_end - now < cic->ttime.ttime_mean)) {
2977 cfq_log_cfqq(cfqd, cfqq, "Not idling. think_time:%llu",
2978 cic->ttime.ttime_mean);
2979 return;
2980 }
2981
2982 /*
2983 * There are other queues in the group or this is the only group and
2984 * it has too big thinktime, don't do group idle.
2985 */
2986 if (group_idle &&
2987 (cfqq->cfqg->nr_cfqq > 1 ||
2988 cfq_io_thinktime_big(cfqd, &st->ttime, true)))
2989 return;
2990
2991 cfq_mark_cfqq_wait_request(cfqq);
2992
2993 if (group_idle)
2994 sl = cfqd->cfq_group_idle;
2995 else
2996 sl = cfqd->cfq_slice_idle;
2997
2998 hrtimer_start(&cfqd->idle_slice_timer, ns_to_ktime(sl),
2999 HRTIMER_MODE_REL);
3000 cfqg_stats_set_start_idle_time(cfqq->cfqg);
3001 cfq_log_cfqq(cfqd, cfqq, "arm_idle: %llu group_idle: %d", sl,
3002 group_idle ? 1 : 0);
3003 }
3004
3005 /*
3006 * Move request from internal lists to the request queue dispatch list.
3007 */
3008 static void cfq_dispatch_insert(struct request_queue *q, struct request *rq)
3009 {
3010 struct cfq_data *cfqd = q->elevator->elevator_data;
3011 struct cfq_queue *cfqq = RQ_CFQQ(rq);
3012
3013 cfq_log_cfqq(cfqd, cfqq, "dispatch_insert");
3014
3015 cfqq->next_rq = cfq_find_next_rq(cfqd, cfqq, rq);
3016 cfq_remove_request(rq);
3017 cfqq->dispatched++;
3018 (RQ_CFQG(rq))->dispatched++;
3019 elv_dispatch_sort(q, rq);
3020
3021 cfqd->rq_in_flight[cfq_cfqq_sync(cfqq)]++;
3022 cfqq->nr_sectors += blk_rq_sectors(rq);
3023 }
3024
3025 /*
3026 * return expired entry, or NULL to just start from scratch in rbtree
3027 */
3028 static struct request *cfq_check_fifo(struct cfq_queue *cfqq)
3029 {
3030 struct request *rq = NULL;
3031
3032 if (cfq_cfqq_fifo_expire(cfqq))
3033 return NULL;
3034
3035 cfq_mark_cfqq_fifo_expire(cfqq);
3036
3037 if (list_empty(&cfqq->fifo))
3038 return NULL;
3039
3040 rq = rq_entry_fifo(cfqq->fifo.next);
3041 if (ktime_get_ns() < rq->fifo_time)
3042 rq = NULL;
3043
3044 return rq;
3045 }
3046
3047 static inline int
3048 cfq_prio_to_maxrq(struct cfq_data *cfqd, struct cfq_queue *cfqq)
3049 {
3050 const int base_rq = cfqd->cfq_slice_async_rq;
3051
3052 WARN_ON(cfqq->ioprio >= IOPRIO_BE_NR);
3053
3054 return 2 * base_rq * (IOPRIO_BE_NR - cfqq->ioprio);
3055 }
3056
3057 /*
3058 * Must be called with the queue_lock held.
3059 */
3060 static int cfqq_process_refs(struct cfq_queue *cfqq)
3061 {
3062 int process_refs, io_refs;
3063
3064 io_refs = cfqq->allocated[READ] + cfqq->allocated[WRITE];
3065 process_refs = cfqq->ref - io_refs;
3066 BUG_ON(process_refs < 0);
3067 return process_refs;
3068 }
3069
3070 static void cfq_setup_merge(struct cfq_queue *cfqq, struct cfq_queue *new_cfqq)
3071 {
3072 int process_refs, new_process_refs;
3073 struct cfq_queue *__cfqq;
3074
3075 /*
3076 * If there are no process references on the new_cfqq, then it is
3077 * unsafe to follow the ->new_cfqq chain as other cfqq's in the
3078 * chain may have dropped their last reference (not just their
3079 * last process reference).
3080 */
3081 if (!cfqq_process_refs(new_cfqq))
3082 return;
3083
3084 /* Avoid a circular list and skip interim queue merges */
3085 while ((__cfqq = new_cfqq->new_cfqq)) {
3086 if (__cfqq == cfqq)
3087 return;
3088 new_cfqq = __cfqq;
3089 }
3090
3091 process_refs = cfqq_process_refs(cfqq);
3092 new_process_refs = cfqq_process_refs(new_cfqq);
3093 /*
3094 * If the process for the cfqq has gone away, there is no
3095 * sense in merging the queues.
3096 */
3097 if (process_refs == 0 || new_process_refs == 0)
3098 return;
3099
3100 /*
3101 * Merge in the direction of the lesser amount of work.
3102 */
3103 if (new_process_refs >= process_refs) {
3104 cfqq->new_cfqq = new_cfqq;
3105 new_cfqq->ref += process_refs;
3106 } else {
3107 new_cfqq->new_cfqq = cfqq;
3108 cfqq->ref += new_process_refs;
3109 }
3110 }
3111
3112 static enum wl_type_t cfq_choose_wl_type(struct cfq_data *cfqd,
3113 struct cfq_group *cfqg, enum wl_class_t wl_class)
3114 {
3115 struct cfq_queue *queue;
3116 int i;
3117 bool key_valid = false;
3118 u64 lowest_key = 0;
3119 enum wl_type_t cur_best = SYNC_NOIDLE_WORKLOAD;
3120
3121 for (i = 0; i <= SYNC_WORKLOAD; ++i) {
3122 /* select the one with lowest rb_key */
3123 queue = cfq_rb_first(st_for(cfqg, wl_class, i));
3124 if (queue &&
3125 (!key_valid || queue->rb_key < lowest_key)) {
3126 lowest_key = queue->rb_key;
3127 cur_best = i;
3128 key_valid = true;
3129 }
3130 }
3131
3132 return cur_best;
3133 }
3134
3135 static void
3136 choose_wl_class_and_type(struct cfq_data *cfqd, struct cfq_group *cfqg)
3137 {
3138 u64 slice;
3139 unsigned count;
3140 struct cfq_rb_root *st;
3141 u64 group_slice;
3142 enum wl_class_t original_class = cfqd->serving_wl_class;
3143 u64 now = ktime_get_ns();
3144
3145 /* Choose next priority. RT > BE > IDLE */
3146 if (cfq_group_busy_queues_wl(RT_WORKLOAD, cfqd, cfqg))
3147 cfqd->serving_wl_class = RT_WORKLOAD;
3148 else if (cfq_group_busy_queues_wl(BE_WORKLOAD, cfqd, cfqg))
3149 cfqd->serving_wl_class = BE_WORKLOAD;
3150 else {
3151 cfqd->serving_wl_class = IDLE_WORKLOAD;
3152 cfqd->workload_expires = now + jiffies_to_nsecs(1);
3153 return;
3154 }
3155
3156 if (original_class != cfqd->serving_wl_class)
3157 goto new_workload;
3158
3159 /*
3160 * For RT and BE, we have to choose also the type
3161 * (SYNC, SYNC_NOIDLE, ASYNC), and to compute a workload
3162 * expiration time
3163 */
3164 st = st_for(cfqg, cfqd->serving_wl_class, cfqd->serving_wl_type);
3165 count = st->count;
3166
3167 /*
3168 * check workload expiration, and that we still have other queues ready
3169 */
3170 if (count && !(now > cfqd->workload_expires))
3171 return;
3172
3173 new_workload:
3174 /* otherwise select new workload type */
3175 cfqd->serving_wl_type = cfq_choose_wl_type(cfqd, cfqg,
3176 cfqd->serving_wl_class);
3177 st = st_for(cfqg, cfqd->serving_wl_class, cfqd->serving_wl_type);
3178 count = st->count;
3179
3180 /*
3181 * the workload slice is computed as a fraction of target latency
3182 * proportional to the number of queues in that workload, over
3183 * all the queues in the same priority class
3184 */
3185 group_slice = cfq_group_slice(cfqd, cfqg);
3186
3187 slice = div_u64(group_slice * count,
3188 max_t(unsigned, cfqg->busy_queues_avg[cfqd->serving_wl_class],
3189 cfq_group_busy_queues_wl(cfqd->serving_wl_class, cfqd,
3190 cfqg)));
3191
3192 if (cfqd->serving_wl_type == ASYNC_WORKLOAD) {
3193 u64 tmp;
3194
3195 /*
3196 * Async queues are currently system wide. Just taking
3197 * proportion of queues with-in same group will lead to higher
3198 * async ratio system wide as generally root group is going
3199 * to have higher weight. A more accurate thing would be to
3200 * calculate system wide asnc/sync ratio.
3201 */
3202 tmp = cfqd->cfq_target_latency *
3203 cfqg_busy_async_queues(cfqd, cfqg);
3204 tmp = div_u64(tmp, cfqd->busy_queues);
3205 slice = min_t(u64, slice, tmp);
3206
3207 /* async workload slice is scaled down according to
3208 * the sync/async slice ratio. */
3209 slice = div64_u64(slice*cfqd->cfq_slice[0], cfqd->cfq_slice[1]);
3210 } else
3211 /* sync workload slice is at least 2 * cfq_slice_idle */
3212 slice = max(slice, 2 * cfqd->cfq_slice_idle);
3213
3214 slice = max_t(u64, slice, CFQ_MIN_TT);
3215 cfq_log(cfqd, "workload slice:%llu", slice);
3216 cfqd->workload_expires = now + slice;
3217 }
3218
3219 static struct cfq_group *cfq_get_next_cfqg(struct cfq_data *cfqd)
3220 {
3221 struct cfq_rb_root *st = &cfqd->grp_service_tree;
3222 struct cfq_group *cfqg;
3223
3224 if (RB_EMPTY_ROOT(&st->rb))
3225 return NULL;
3226 cfqg = cfq_rb_first_group(st);
3227 update_min_vdisktime(st);
3228 return cfqg;
3229 }
3230
3231 static void cfq_choose_cfqg(struct cfq_data *cfqd)
3232 {
3233 struct cfq_group *cfqg = cfq_get_next_cfqg(cfqd);
3234 u64 now = ktime_get_ns();
3235
3236 cfqd->serving_group = cfqg;
3237
3238 /* Restore the workload type data */
3239 if (cfqg->saved_wl_slice) {
3240 cfqd->workload_expires = now + cfqg->saved_wl_slice;
3241 cfqd->serving_wl_type = cfqg->saved_wl_type;
3242 cfqd->serving_wl_class = cfqg->saved_wl_class;
3243 } else
3244 cfqd->workload_expires = now - 1;
3245
3246 choose_wl_class_and_type(cfqd, cfqg);
3247 }
3248
3249 /*
3250 * Select a queue for service. If we have a current active queue,
3251 * check whether to continue servicing it, or retrieve and set a new one.
3252 */
3253 static struct cfq_queue *cfq_select_queue(struct cfq_data *cfqd)
3254 {
3255 struct cfq_queue *cfqq, *new_cfqq = NULL;
3256 u64 now = ktime_get_ns();
3257
3258 cfqq = cfqd->active_queue;
3259 if (!cfqq)
3260 goto new_queue;
3261
3262 if (!cfqd->rq_queued)
3263 return NULL;
3264
3265 /*
3266 * We were waiting for group to get backlogged. Expire the queue
3267 */
3268 if (cfq_cfqq_wait_busy(cfqq) && !RB_EMPTY_ROOT(&cfqq->sort_list))
3269 goto expire;
3270
3271 /*
3272 * The active queue has run out of time, expire it and select new.
3273 */
3274 if (cfq_slice_used(cfqq) && !cfq_cfqq_must_dispatch(cfqq)) {
3275 /*
3276 * If slice had not expired at the completion of last request
3277 * we might not have turned on wait_busy flag. Don't expire
3278 * the queue yet. Allow the group to get backlogged.
3279 *
3280 * The very fact that we have used the slice, that means we
3281 * have been idling all along on this queue and it should be
3282 * ok to wait for this request to complete.
3283 */
3284 if (cfqq->cfqg->nr_cfqq == 1 && RB_EMPTY_ROOT(&cfqq->sort_list)
3285 && cfqq->dispatched && cfq_should_idle(cfqd, cfqq)) {
3286 cfqq = NULL;
3287 goto keep_queue;
3288 } else
3289 goto check_group_idle;
3290 }
3291
3292 /*
3293 * The active queue has requests and isn't expired, allow it to
3294 * dispatch.
3295 */
3296 if (!RB_EMPTY_ROOT(&cfqq->sort_list))
3297 goto keep_queue;
3298
3299 /*
3300 * If another queue has a request waiting within our mean seek
3301 * distance, let it run. The expire code will check for close
3302 * cooperators and put the close queue at the front of the service
3303 * tree. If possible, merge the expiring queue with the new cfqq.
3304 */
3305 new_cfqq = cfq_close_cooperator(cfqd, cfqq);
3306 if (new_cfqq) {
3307 if (!cfqq->new_cfqq)
3308 cfq_setup_merge(cfqq, new_cfqq);
3309 goto expire;
3310 }
3311
3312 /*
3313 * No requests pending. If the active queue still has requests in
3314 * flight or is idling for a new request, allow either of these
3315 * conditions to happen (or time out) before selecting a new queue.
3316 */
3317 if (hrtimer_active(&cfqd->idle_slice_timer)) {
3318 cfqq = NULL;
3319 goto keep_queue;
3320 }
3321
3322 /*
3323 * This is a deep seek queue, but the device is much faster than
3324 * the queue can deliver, don't idle
3325 **/
3326 if (CFQQ_SEEKY(cfqq) && cfq_cfqq_idle_window(cfqq) &&
3327 (cfq_cfqq_slice_new(cfqq) ||
3328 (cfqq->slice_end - now > now - cfqq->slice_start))) {
3329 cfq_clear_cfqq_deep(cfqq);
3330 cfq_clear_cfqq_idle_window(cfqq);
3331 }
3332
3333 if (cfqq->dispatched && cfq_should_idle(cfqd, cfqq)) {
3334 cfqq = NULL;
3335 goto keep_queue;
3336 }
3337
3338 /*
3339 * If group idle is enabled and there are requests dispatched from
3340 * this group, wait for requests to complete.
3341 */
3342 check_group_idle:
3343 if (cfqd->cfq_group_idle && cfqq->cfqg->nr_cfqq == 1 &&
3344 cfqq->cfqg->dispatched &&
3345 !cfq_io_thinktime_big(cfqd, &cfqq->cfqg->ttime, true)) {
3346 cfqq = NULL;
3347 goto keep_queue;
3348 }
3349
3350 expire:
3351 cfq_slice_expired(cfqd, 0);
3352 new_queue:
3353 /*
3354 * Current queue expired. Check if we have to switch to a new
3355 * service tree
3356 */
3357 if (!new_cfqq)
3358 cfq_choose_cfqg(cfqd);
3359
3360 cfqq = cfq_set_active_queue(cfqd, new_cfqq);
3361 keep_queue:
3362 return cfqq;
3363 }
3364
3365 static int __cfq_forced_dispatch_cfqq(struct cfq_queue *cfqq)
3366 {
3367 int dispatched = 0;
3368
3369 while (cfqq->next_rq) {
3370 cfq_dispatch_insert(cfqq->cfqd->queue, cfqq->next_rq);
3371 dispatched++;
3372 }
3373
3374 BUG_ON(!list_empty(&cfqq->fifo));
3375
3376 /* By default cfqq is not expired if it is empty. Do it explicitly */
3377 __cfq_slice_expired(cfqq->cfqd, cfqq, 0);
3378 return dispatched;
3379 }
3380
3381 /*
3382 * Drain our current requests. Used for barriers and when switching
3383 * io schedulers on-the-fly.
3384 */
3385 static int cfq_forced_dispatch(struct cfq_data *cfqd)
3386 {
3387 struct cfq_queue *cfqq;
3388 int dispatched = 0;
3389
3390 /* Expire the timeslice of the current active queue first */
3391 cfq_slice_expired(cfqd, 0);
3392 while ((cfqq = cfq_get_next_queue_forced(cfqd)) != NULL) {
3393 __cfq_set_active_queue(cfqd, cfqq);
3394 dispatched += __cfq_forced_dispatch_cfqq(cfqq);
3395 }
3396
3397 BUG_ON(cfqd->busy_queues);
3398
3399 cfq_log(cfqd, "forced_dispatch=%d", dispatched);
3400 return dispatched;
3401 }
3402
3403 static inline bool cfq_slice_used_soon(struct cfq_data *cfqd,
3404 struct cfq_queue *cfqq)
3405 {
3406 u64 now = ktime_get_ns();
3407
3408 /* the queue hasn't finished any request, can't estimate */
3409 if (cfq_cfqq_slice_new(cfqq))
3410 return true;
3411 if (now + cfqd->cfq_slice_idle * cfqq->dispatched > cfqq->slice_end)
3412 return true;
3413
3414 return false;
3415 }
3416
3417 static bool cfq_may_dispatch(struct cfq_data *cfqd, struct cfq_queue *cfqq)
3418 {
3419 unsigned int max_dispatch;
3420
3421 if (cfq_cfqq_must_dispatch(cfqq))
3422 return true;
3423
3424 /*
3425 * Drain async requests before we start sync IO
3426 */
3427 if (cfq_should_idle(cfqd, cfqq) && cfqd->rq_in_flight[BLK_RW_ASYNC])
3428 return false;
3429
3430 /*
3431 * If this is an async queue and we have sync IO in flight, let it wait
3432 */
3433 if (cfqd->rq_in_flight[BLK_RW_SYNC] && !cfq_cfqq_sync(cfqq))
3434 return false;
3435
3436 max_dispatch = max_t(unsigned int, cfqd->cfq_quantum / 2, 1);
3437 if (cfq_class_idle(cfqq))
3438 max_dispatch = 1;
3439
3440 /*
3441 * Does this cfqq already have too much IO in flight?
3442 */
3443 if (cfqq->dispatched >= max_dispatch) {
3444 bool promote_sync = false;
3445 /*
3446 * idle queue must always only have a single IO in flight
3447 */
3448 if (cfq_class_idle(cfqq))
3449 return false;
3450
3451 /*
3452 * If there is only one sync queue
3453 * we can ignore async queue here and give the sync
3454 * queue no dispatch limit. The reason is a sync queue can
3455 * preempt async queue, limiting the sync queue doesn't make
3456 * sense. This is useful for aiostress test.
3457 */
3458 if (cfq_cfqq_sync(cfqq) && cfqd->busy_sync_queues == 1)
3459 promote_sync = true;
3460
3461 /*
3462 * We have other queues, don't allow more IO from this one
3463 */
3464 if (cfqd->busy_queues > 1 && cfq_slice_used_soon(cfqd, cfqq) &&
3465 !promote_sync)
3466 return false;
3467
3468 /*
3469 * Sole queue user, no limit
3470 */
3471 if (cfqd->busy_queues == 1 || promote_sync)
3472 max_dispatch = -1;
3473 else
3474 /*
3475 * Normally we start throttling cfqq when cfq_quantum/2
3476 * requests have been dispatched. But we can drive
3477 * deeper queue depths at the beginning of slice
3478 * subjected to upper limit of cfq_quantum.
3479 * */
3480 max_dispatch = cfqd->cfq_quantum;
3481 }
3482
3483 /*
3484 * Async queues must wait a bit before being allowed dispatch.
3485 * We also ramp up the dispatch depth gradually for async IO,
3486 * based on the last sync IO we serviced
3487 */
3488 if (!cfq_cfqq_sync(cfqq) && cfqd->cfq_latency) {
3489 u64 last_sync = ktime_get_ns() - cfqd->last_delayed_sync;
3490 unsigned int depth;
3491
3492 depth = div64_u64(last_sync, cfqd->cfq_slice[1]);
3493 if (!depth && !cfqq->dispatched)
3494 depth = 1;
3495 if (depth < max_dispatch)
3496 max_dispatch = depth;
3497 }
3498
3499 /*
3500 * If we're below the current max, allow a dispatch
3501 */
3502 return cfqq->dispatched < max_dispatch;
3503 }
3504
3505 /*
3506 * Dispatch a request from cfqq, moving them to the request queue
3507 * dispatch list.
3508 */
3509 static bool cfq_dispatch_request(struct cfq_data *cfqd, struct cfq_queue *cfqq)
3510 {
3511 struct request *rq;
3512
3513 BUG_ON(RB_EMPTY_ROOT(&cfqq->sort_list));
3514
3515 rq = cfq_check_fifo(cfqq);
3516 if (rq)
3517 cfq_mark_cfqq_must_dispatch(cfqq);
3518
3519 if (!cfq_may_dispatch(cfqd, cfqq))
3520 return false;
3521
3522 /*
3523 * follow expired path, else get first next available
3524 */
3525 if (!rq)
3526 rq = cfqq->next_rq;
3527 else
3528 cfq_log_cfqq(cfqq->cfqd, cfqq, "fifo=%p", rq);
3529
3530 /*
3531 * insert request into driver dispatch list
3532 */
3533 cfq_dispatch_insert(cfqd->queue, rq);
3534
3535 if (!cfqd->active_cic) {
3536 struct cfq_io_cq *cic = RQ_CIC(rq);
3537
3538 atomic_long_inc(&cic->icq.ioc->refcount);
3539 cfqd->active_cic = cic;
3540 }
3541
3542 return true;
3543 }
3544
3545 /*
3546 * Find the cfqq that we need to service and move a request from that to the
3547 * dispatch list
3548 */
3549 static int cfq_dispatch_requests(struct request_queue *q, int force)
3550 {
3551 struct cfq_data *cfqd = q->elevator->elevator_data;
3552 struct cfq_queue *cfqq;
3553
3554 if (!cfqd->busy_queues)
3555 return 0;
3556
3557 if (unlikely(force))
3558 return cfq_forced_dispatch(cfqd);
3559
3560 cfqq = cfq_select_queue(cfqd);
3561 if (!cfqq)
3562 return 0;
3563
3564 /*
3565 * Dispatch a request from this cfqq, if it is allowed
3566 */
3567 if (!cfq_dispatch_request(cfqd, cfqq))
3568 return 0;
3569
3570 cfqq->slice_dispatch++;
3571 cfq_clear_cfqq_must_dispatch(cfqq);
3572
3573 /*
3574 * expire an async queue immediately if it has used up its slice. idle
3575 * queue always expire after 1 dispatch round.
3576 */
3577 if (cfqd->busy_queues > 1 && ((!cfq_cfqq_sync(cfqq) &&
3578 cfqq->slice_dispatch >= cfq_prio_to_maxrq(cfqd, cfqq)) ||
3579 cfq_class_idle(cfqq))) {
3580 cfqq->slice_end = ktime_get_ns() + 1;
3581 cfq_slice_expired(cfqd, 0);
3582 }
3583
3584 cfq_log_cfqq(cfqd, cfqq, "dispatched a request");
3585 return 1;
3586 }
3587
3588 /*
3589 * task holds one reference to the queue, dropped when task exits. each rq
3590 * in-flight on this queue also holds a reference, dropped when rq is freed.
3591 *
3592 * Each cfq queue took a reference on the parent group. Drop it now.
3593 * queue lock must be held here.
3594 */
3595 static void cfq_put_queue(struct cfq_queue *cfqq)
3596 {
3597 struct cfq_data *cfqd = cfqq->cfqd;
3598 struct cfq_group *cfqg;
3599
3600 BUG_ON(cfqq->ref <= 0);
3601
3602 cfqq->ref--;
3603 if (cfqq->ref)
3604 return;
3605
3606 cfq_log_cfqq(cfqd, cfqq, "put_queue");
3607 BUG_ON(rb_first(&cfqq->sort_list));
3608 BUG_ON(cfqq->allocated[READ] + cfqq->allocated[WRITE]);
3609 cfqg = cfqq->cfqg;
3610
3611 if (unlikely(cfqd->active_queue == cfqq)) {
3612 __cfq_slice_expired(cfqd, cfqq, 0);
3613 cfq_schedule_dispatch(cfqd);
3614 }
3615
3616 BUG_ON(cfq_cfqq_on_rr(cfqq));
3617 kmem_cache_free(cfq_pool, cfqq);
3618 cfqg_put(cfqg);
3619 }
3620
3621 static void cfq_put_cooperator(struct cfq_queue *cfqq)
3622 {
3623 struct cfq_queue *__cfqq, *next;
3624
3625 /*
3626 * If this queue was scheduled to merge with another queue, be
3627 * sure to drop the reference taken on that queue (and others in
3628 * the merge chain). See cfq_setup_merge and cfq_merge_cfqqs.
3629 */
3630 __cfqq = cfqq->new_cfqq;
3631 while (__cfqq) {
3632 if (__cfqq == cfqq) {
3633 WARN(1, "cfqq->new_cfqq loop detected\n");
3634 break;
3635 }
3636 next = __cfqq->new_cfqq;
3637 cfq_put_queue(__cfqq);
3638 __cfqq = next;
3639 }
3640 }
3641
3642 static void cfq_exit_cfqq(struct cfq_data *cfqd, struct cfq_queue *cfqq)
3643 {
3644 if (unlikely(cfqq == cfqd->active_queue)) {
3645 __cfq_slice_expired(cfqd, cfqq, 0);
3646 cfq_schedule_dispatch(cfqd);
3647 }
3648
3649 cfq_put_cooperator(cfqq);
3650
3651 cfq_put_queue(cfqq);
3652 }
3653
3654 static void cfq_init_icq(struct io_cq *icq)
3655 {
3656 struct cfq_io_cq *cic = icq_to_cic(icq);
3657
3658 cic->ttime.last_end_request = ktime_get_ns();
3659 }
3660
3661 static void cfq_exit_icq(struct io_cq *icq)
3662 {
3663 struct cfq_io_cq *cic = icq_to_cic(icq);
3664 struct cfq_data *cfqd = cic_to_cfqd(cic);
3665
3666 if (cic_to_cfqq(cic, false)) {
3667 cfq_exit_cfqq(cfqd, cic_to_cfqq(cic, false));
3668 cic_set_cfqq(cic, NULL, false);
3669 }
3670
3671 if (cic_to_cfqq(cic, true)) {
3672 cfq_exit_cfqq(cfqd, cic_to_cfqq(cic, true));
3673 cic_set_cfqq(cic, NULL, true);
3674 }
3675 }
3676
3677 static void cfq_init_prio_data(struct cfq_queue *cfqq, struct cfq_io_cq *cic)
3678 {
3679 struct task_struct *tsk = current;
3680 int ioprio_class;
3681
3682 if (!cfq_cfqq_prio_changed(cfqq))
3683 return;
3684
3685 ioprio_class = IOPRIO_PRIO_CLASS(cic->ioprio);
3686 switch (ioprio_class) {
3687 default:
3688 printk(KERN_ERR "cfq: bad prio %x\n", ioprio_class);
3689 case IOPRIO_CLASS_NONE:
3690 /*
3691 * no prio set, inherit CPU scheduling settings
3692 */
3693 cfqq->ioprio = task_nice_ioprio(tsk);
3694 cfqq->ioprio_class = task_nice_ioclass(tsk);
3695 break;
3696 case IOPRIO_CLASS_RT:
3697 cfqq->ioprio = IOPRIO_PRIO_DATA(cic->ioprio);
3698 cfqq->ioprio_class = IOPRIO_CLASS_RT;
3699 break;
3700 case IOPRIO_CLASS_BE:
3701 cfqq->ioprio = IOPRIO_PRIO_DATA(cic->ioprio);
3702 cfqq->ioprio_class = IOPRIO_CLASS_BE;
3703 break;
3704 case IOPRIO_CLASS_IDLE:
3705 cfqq->ioprio_class = IOPRIO_CLASS_IDLE;
3706 cfqq->ioprio = 7;
3707 cfq_clear_cfqq_idle_window(cfqq);
3708 break;
3709 }
3710
3711 /*
3712 * keep track of original prio settings in case we have to temporarily
3713 * elevate the priority of this queue
3714 */
3715 cfqq->org_ioprio = cfqq->ioprio;
3716 cfqq->org_ioprio_class = cfqq->ioprio_class;
3717 cfq_clear_cfqq_prio_changed(cfqq);
3718 }
3719
3720 static void check_ioprio_changed(struct cfq_io_cq *cic, struct bio *bio)
3721 {
3722 int ioprio = cic->icq.ioc->ioprio;
3723 struct cfq_data *cfqd = cic_to_cfqd(cic);
3724 struct cfq_queue *cfqq;
3725
3726 /*
3727 * Check whether ioprio has changed. The condition may trigger
3728 * spuriously on a newly created cic but there's no harm.
3729 */
3730 if (unlikely(!cfqd) || likely(cic->ioprio == ioprio))
3731 return;
3732
3733 cfqq = cic_to_cfqq(cic, false);
3734 if (cfqq) {
3735 cfq_put_queue(cfqq);
3736 cfqq = cfq_get_queue(cfqd, BLK_RW_ASYNC, cic, bio);
3737 cic_set_cfqq(cic, cfqq, false);
3738 }
3739
3740 cfqq = cic_to_cfqq(cic, true);
3741 if (cfqq)
3742 cfq_mark_cfqq_prio_changed(cfqq);
3743
3744 cic->ioprio = ioprio;
3745 }
3746
3747 static void cfq_init_cfqq(struct cfq_data *cfqd, struct cfq_queue *cfqq,
3748 pid_t pid, bool is_sync)
3749 {
3750 RB_CLEAR_NODE(&cfqq->rb_node);
3751 RB_CLEAR_NODE(&cfqq->p_node);
3752 INIT_LIST_HEAD(&cfqq->fifo);
3753
3754 cfqq->ref = 0;
3755 cfqq->cfqd = cfqd;
3756
3757 cfq_mark_cfqq_prio_changed(cfqq);
3758
3759 if (is_sync) {
3760 if (!cfq_class_idle(cfqq))
3761 cfq_mark_cfqq_idle_window(cfqq);
3762 cfq_mark_cfqq_sync(cfqq);
3763 }
3764 cfqq->pid = pid;
3765 }
3766
3767 #ifdef CONFIG_CFQ_GROUP_IOSCHED
3768 static void check_blkcg_changed(struct cfq_io_cq *cic, struct bio *bio)
3769 {
3770 struct cfq_data *cfqd = cic_to_cfqd(cic);
3771 struct cfq_queue *cfqq;
3772 uint64_t serial_nr;
3773
3774 rcu_read_lock();
3775 serial_nr = bio_blkcg(bio)->css.serial_nr;
3776 rcu_read_unlock();
3777
3778 /*
3779 * Check whether blkcg has changed. The condition may trigger
3780 * spuriously on a newly created cic but there's no harm.
3781 */
3782 if (unlikely(!cfqd) || likely(cic->blkcg_serial_nr == serial_nr))
3783 return;
3784
3785 /*
3786 * Drop reference to queues. New queues will be assigned in new
3787 * group upon arrival of fresh requests.
3788 */
3789 cfqq = cic_to_cfqq(cic, false);
3790 if (cfqq) {
3791 cfq_log_cfqq(cfqd, cfqq, "changed cgroup");
3792 cic_set_cfqq(cic, NULL, false);
3793 cfq_put_queue(cfqq);
3794 }
3795
3796 cfqq = cic_to_cfqq(cic, true);
3797 if (cfqq) {
3798 cfq_log_cfqq(cfqd, cfqq, "changed cgroup");
3799 cic_set_cfqq(cic, NULL, true);
3800 cfq_put_queue(cfqq);
3801 }
3802
3803 cic->blkcg_serial_nr = serial_nr;
3804 }
3805 #else
3806 static inline void check_blkcg_changed(struct cfq_io_cq *cic, struct bio *bio)
3807 {
3808 }
3809 #endif /* CONFIG_CFQ_GROUP_IOSCHED */
3810
3811 static struct cfq_queue **
3812 cfq_async_queue_prio(struct cfq_group *cfqg, int ioprio_class, int ioprio)
3813 {
3814 switch (ioprio_class) {
3815 case IOPRIO_CLASS_RT:
3816 return &cfqg->async_cfqq[0][ioprio];
3817 case IOPRIO_CLASS_NONE:
3818 ioprio = IOPRIO_NORM;
3819 /* fall through */
3820 case IOPRIO_CLASS_BE:
3821 return &cfqg->async_cfqq[1][ioprio];
3822 case IOPRIO_CLASS_IDLE:
3823 return &cfqg->async_idle_cfqq;
3824 default:
3825 BUG();
3826 }
3827 }
3828
3829 static struct cfq_queue *
3830 cfq_get_queue(struct cfq_data *cfqd, bool is_sync, struct cfq_io_cq *cic,
3831 struct bio *bio)
3832 {
3833 int ioprio_class = IOPRIO_PRIO_CLASS(cic->ioprio);
3834 int ioprio = IOPRIO_PRIO_DATA(cic->ioprio);
3835 struct cfq_queue **async_cfqq = NULL;
3836 struct cfq_queue *cfqq;
3837 struct cfq_group *cfqg;
3838
3839 rcu_read_lock();
3840 cfqg = cfq_lookup_cfqg(cfqd, bio_blkcg(bio));
3841 if (!cfqg) {
3842 cfqq = &cfqd->oom_cfqq;
3843 goto out;
3844 }
3845
3846 if (!is_sync) {
3847 if (!ioprio_valid(cic->ioprio)) {
3848 struct task_struct *tsk = current;
3849 ioprio = task_nice_ioprio(tsk);
3850 ioprio_class = task_nice_ioclass(tsk);
3851 }
3852 async_cfqq = cfq_async_queue_prio(cfqg, ioprio_class, ioprio);
3853 cfqq = *async_cfqq;
3854 if (cfqq)
3855 goto out;
3856 }
3857
3858 cfqq = kmem_cache_alloc_node(cfq_pool,
3859 GFP_NOWAIT | __GFP_ZERO | __GFP_NOWARN,
3860 cfqd->queue->node);
3861 if (!cfqq) {
3862 cfqq = &cfqd->oom_cfqq;
3863 goto out;
3864 }
3865
3866 /* cfq_init_cfqq() assumes cfqq->ioprio_class is initialized. */
3867 cfqq->ioprio_class = IOPRIO_CLASS_NONE;
3868 cfq_init_cfqq(cfqd, cfqq, current->pid, is_sync);
3869 cfq_init_prio_data(cfqq, cic);
3870 cfq_link_cfqq_cfqg(cfqq, cfqg);
3871 cfq_log_cfqq(cfqd, cfqq, "alloced");
3872
3873 if (async_cfqq) {
3874 /* a new async queue is created, pin and remember */
3875 cfqq->ref++;
3876 *async_cfqq = cfqq;
3877 }
3878 out:
3879 cfqq->ref++;
3880 rcu_read_unlock();
3881 return cfqq;
3882 }
3883
3884 static void
3885 __cfq_update_io_thinktime(struct cfq_ttime *ttime, u64 slice_idle)
3886 {
3887 u64 elapsed = ktime_get_ns() - ttime->last_end_request;
3888 elapsed = min(elapsed, 2UL * slice_idle);
3889
3890 ttime->ttime_samples = (7*ttime->ttime_samples + 256) / 8;
3891 ttime->ttime_total = div_u64(7*ttime->ttime_total + 256*elapsed, 8);
3892 ttime->ttime_mean = div64_ul(ttime->ttime_total + 128,
3893 ttime->ttime_samples);
3894 }
3895
3896 static void
3897 cfq_update_io_thinktime(struct cfq_data *cfqd, struct cfq_queue *cfqq,
3898 struct cfq_io_cq *cic)
3899 {
3900 if (cfq_cfqq_sync(cfqq)) {
3901 __cfq_update_io_thinktime(&cic->ttime, cfqd->cfq_slice_idle);
3902 __cfq_update_io_thinktime(&cfqq->service_tree->ttime,
3903 cfqd->cfq_slice_idle);
3904 }
3905 #ifdef CONFIG_CFQ_GROUP_IOSCHED
3906 __cfq_update_io_thinktime(&cfqq->cfqg->ttime, cfqd->cfq_group_idle);
3907 #endif
3908 }
3909
3910 static void
3911 cfq_update_io_seektime(struct cfq_data *cfqd, struct cfq_queue *cfqq,
3912 struct request *rq)
3913 {
3914 sector_t sdist = 0;
3915 sector_t n_sec = blk_rq_sectors(rq);
3916 if (cfqq->last_request_pos) {
3917 if (cfqq->last_request_pos < blk_rq_pos(rq))
3918 sdist = blk_rq_pos(rq) - cfqq->last_request_pos;
3919 else
3920 sdist = cfqq->last_request_pos - blk_rq_pos(rq);
3921 }
3922
3923 cfqq->seek_history <<= 1;
3924 if (blk_queue_nonrot(cfqd->queue))
3925 cfqq->seek_history |= (n_sec < CFQQ_SECT_THR_NONROT);
3926 else
3927 cfqq->seek_history |= (sdist > CFQQ_SEEK_THR);
3928 }
3929
3930 static inline bool req_noidle(struct request *req)
3931 {
3932 return req_op(req) == REQ_OP_WRITE &&
3933 (req->cmd_flags & (REQ_SYNC | REQ_IDLE)) == REQ_SYNC;
3934 }
3935
3936 /*
3937 * Disable idle window if the process thinks too long or seeks so much that
3938 * it doesn't matter
3939 */
3940 static void
3941 cfq_update_idle_window(struct cfq_data *cfqd, struct cfq_queue *cfqq,
3942 struct cfq_io_cq *cic)
3943 {
3944 int old_idle, enable_idle;
3945
3946 /*
3947 * Don't idle for async or idle io prio class
3948 */
3949 if (!cfq_cfqq_sync(cfqq) || cfq_class_idle(cfqq))
3950 return;
3951
3952 enable_idle = old_idle = cfq_cfqq_idle_window(cfqq);
3953
3954 if (cfqq->queued[0] + cfqq->queued[1] >= 4)
3955 cfq_mark_cfqq_deep(cfqq);
3956
3957 if (cfqq->next_rq && req_noidle(cfqq->next_rq))
3958 enable_idle = 0;
3959 else if (!atomic_read(&cic->icq.ioc->active_ref) ||
3960 !cfqd->cfq_slice_idle ||
3961 (!cfq_cfqq_deep(cfqq) && CFQQ_SEEKY(cfqq)))
3962 enable_idle = 0;
3963 else if (sample_valid(cic->ttime.ttime_samples)) {
3964 if (cic->ttime.ttime_mean > cfqd->cfq_slice_idle)
3965 enable_idle = 0;
3966 else
3967 enable_idle = 1;
3968 }
3969
3970 if (old_idle != enable_idle) {
3971 cfq_log_cfqq(cfqd, cfqq, "idle=%d", enable_idle);
3972 if (enable_idle)
3973 cfq_mark_cfqq_idle_window(cfqq);
3974 else
3975 cfq_clear_cfqq_idle_window(cfqq);
3976 }
3977 }
3978
3979 /*
3980 * Check if new_cfqq should preempt the currently active queue. Return 0 for
3981 * no or if we aren't sure, a 1 will cause a preempt.
3982 */
3983 static bool
3984 cfq_should_preempt(struct cfq_data *cfqd, struct cfq_queue *new_cfqq,
3985 struct request *rq)
3986 {
3987 struct cfq_queue *cfqq;
3988
3989 cfqq = cfqd->active_queue;
3990 if (!cfqq)
3991 return false;
3992
3993 if (cfq_class_idle(new_cfqq))
3994 return false;
3995
3996 if (cfq_class_idle(cfqq))
3997 return true;
3998
3999 /*
4000 * Don't allow a non-RT request to preempt an ongoing RT cfqq timeslice.
4001 */
4002 if (cfq_class_rt(cfqq) && !cfq_class_rt(new_cfqq))
4003 return false;
4004
4005 /*
4006 * if the new request is sync, but the currently running queue is
4007 * not, let the sync request have priority.
4008 */
4009 if (rq_is_sync(rq) && !cfq_cfqq_sync(cfqq) && !cfq_cfqq_must_dispatch(cfqq))
4010 return true;
4011
4012 /*
4013 * Treat ancestors of current cgroup the same way as current cgroup.
4014 * For anybody else we disallow preemption to guarantee service
4015 * fairness among cgroups.
4016 */
4017 if (!cfqg_is_descendant(cfqq->cfqg, new_cfqq->cfqg))
4018 return false;
4019
4020 if (cfq_slice_used(cfqq))
4021 return true;
4022
4023 /*
4024 * Allow an RT request to pre-empt an ongoing non-RT cfqq timeslice.
4025 */
4026 if (cfq_class_rt(new_cfqq) && !cfq_class_rt(cfqq))
4027 return true;
4028
4029 WARN_ON_ONCE(cfqq->ioprio_class != new_cfqq->ioprio_class);
4030 /* Allow preemption only if we are idling on sync-noidle tree */
4031 if (cfqd->serving_wl_type == SYNC_NOIDLE_WORKLOAD &&
4032 cfqq_type(new_cfqq) == SYNC_NOIDLE_WORKLOAD &&
4033 RB_EMPTY_ROOT(&cfqq->sort_list))
4034 return true;
4035
4036 /*
4037 * So both queues are sync. Let the new request get disk time if
4038 * it's a metadata request and the current queue is doing regular IO.
4039 */
4040 if ((rq->cmd_flags & REQ_PRIO) && !cfqq->prio_pending)
4041 return true;
4042
4043 /* An idle queue should not be idle now for some reason */
4044 if (RB_EMPTY_ROOT(&cfqq->sort_list) && !cfq_should_idle(cfqd, cfqq))
4045 return true;
4046
4047 if (!cfqd->active_cic || !cfq_cfqq_wait_request(cfqq))
4048 return false;
4049
4050 /*
4051 * if this request is as-good as one we would expect from the
4052 * current cfqq, let it preempt
4053 */
4054 if (cfq_rq_close(cfqd, cfqq, rq))
4055 return true;
4056
4057 return false;
4058 }
4059
4060 /*
4061 * cfqq preempts the active queue. if we allowed preempt with no slice left,
4062 * let it have half of its nominal slice.
4063 */
4064 static void cfq_preempt_queue(struct cfq_data *cfqd, struct cfq_queue *cfqq)
4065 {
4066 enum wl_type_t old_type = cfqq_type(cfqd->active_queue);
4067
4068 cfq_log_cfqq(cfqd, cfqq, "preempt");
4069 cfq_slice_expired(cfqd, 1);
4070
4071 /*
4072 * workload type is changed, don't save slice, otherwise preempt
4073 * doesn't happen
4074 */
4075 if (old_type != cfqq_type(cfqq))
4076 cfqq->cfqg->saved_wl_slice = 0;
4077
4078 /*
4079 * Put the new queue at the front of the of the current list,
4080 * so we know that it will be selected next.
4081 */
4082 BUG_ON(!cfq_cfqq_on_rr(cfqq));
4083
4084 cfq_service_tree_add(cfqd, cfqq, 1);
4085
4086 cfqq->slice_end = 0;
4087 cfq_mark_cfqq_slice_new(cfqq);
4088 }
4089
4090 /*
4091 * Called when a new fs request (rq) is added (to cfqq). Check if there's
4092 * something we should do about it
4093 */
4094 static void
4095 cfq_rq_enqueued(struct cfq_data *cfqd, struct cfq_queue *cfqq,
4096 struct request *rq)
4097 {
4098 struct cfq_io_cq *cic = RQ_CIC(rq);
4099
4100 cfqd->rq_queued++;
4101 if (rq->cmd_flags & REQ_PRIO)
4102 cfqq->prio_pending++;
4103
4104 cfq_update_io_thinktime(cfqd, cfqq, cic);
4105 cfq_update_io_seektime(cfqd, cfqq, rq);
4106 cfq_update_idle_window(cfqd, cfqq, cic);
4107
4108 cfqq->last_request_pos = blk_rq_pos(rq) + blk_rq_sectors(rq);
4109
4110 if (cfqq == cfqd->active_queue) {
4111 /*
4112 * Remember that we saw a request from this process, but
4113 * don't start queuing just yet. Otherwise we risk seeing lots
4114 * of tiny requests, because we disrupt the normal plugging
4115 * and merging. If the request is already larger than a single
4116 * page, let it rip immediately. For that case we assume that
4117 * merging is already done. Ditto for a busy system that
4118 * has other work pending, don't risk delaying until the
4119 * idle timer unplug to continue working.
4120 */
4121 if (cfq_cfqq_wait_request(cfqq)) {
4122 if (blk_rq_bytes(rq) > PAGE_SIZE ||
4123 cfqd->busy_queues > 1) {
4124 cfq_del_timer(cfqd, cfqq);
4125 cfq_clear_cfqq_wait_request(cfqq);
4126 __blk_run_queue(cfqd->queue);
4127 } else {
4128 cfqg_stats_update_idle_time(cfqq->cfqg);
4129 cfq_mark_cfqq_must_dispatch(cfqq);
4130 }
4131 }
4132 } else if (cfq_should_preempt(cfqd, cfqq, rq)) {
4133 /*
4134 * not the active queue - expire current slice if it is
4135 * idle and has expired it's mean thinktime or this new queue
4136 * has some old slice time left and is of higher priority or
4137 * this new queue is RT and the current one is BE
4138 */
4139 cfq_preempt_queue(cfqd, cfqq);
4140 __blk_run_queue(cfqd->queue);
4141 }
4142 }
4143
4144 static void cfq_insert_request(struct request_queue *q, struct request *rq)
4145 {
4146 struct cfq_data *cfqd = q->elevator->elevator_data;
4147 struct cfq_queue *cfqq = RQ_CFQQ(rq);
4148
4149 cfq_log_cfqq(cfqd, cfqq, "insert_request");
4150 cfq_init_prio_data(cfqq, RQ_CIC(rq));
4151
4152 rq->fifo_time = ktime_get_ns() + cfqd->cfq_fifo_expire[rq_is_sync(rq)];
4153 list_add_tail(&rq->queuelist, &cfqq->fifo);
4154 cfq_add_rq_rb(rq);
4155 cfqg_stats_update_io_add(RQ_CFQG(rq), cfqd->serving_group,
4156 rq->cmd_flags);
4157 cfq_rq_enqueued(cfqd, cfqq, rq);
4158 }
4159
4160 /*
4161 * Update hw_tag based on peak queue depth over 50 samples under
4162 * sufficient load.
4163 */
4164 static void cfq_update_hw_tag(struct cfq_data *cfqd)
4165 {
4166 struct cfq_queue *cfqq = cfqd->active_queue;
4167
4168 if (cfqd->rq_in_driver > cfqd->hw_tag_est_depth)
4169 cfqd->hw_tag_est_depth = cfqd->rq_in_driver;
4170
4171 if (cfqd->hw_tag == 1)
4172 return;
4173
4174 if (cfqd->rq_queued <= CFQ_HW_QUEUE_MIN &&
4175 cfqd->rq_in_driver <= CFQ_HW_QUEUE_MIN)
4176 return;
4177
4178 /*
4179 * If active queue hasn't enough requests and can idle, cfq might not
4180 * dispatch sufficient requests to hardware. Don't zero hw_tag in this
4181 * case
4182 */
4183 if (cfqq && cfq_cfqq_idle_window(cfqq) &&
4184 cfqq->dispatched + cfqq->queued[0] + cfqq->queued[1] <
4185 CFQ_HW_QUEUE_MIN && cfqd->rq_in_driver < CFQ_HW_QUEUE_MIN)
4186 return;
4187
4188 if (cfqd->hw_tag_samples++ < 50)
4189 return;
4190
4191 if (cfqd->hw_tag_est_depth >= CFQ_HW_QUEUE_MIN)
4192 cfqd->hw_tag = 1;
4193 else
4194 cfqd->hw_tag = 0;
4195 }
4196
4197 static bool cfq_should_wait_busy(struct cfq_data *cfqd, struct cfq_queue *cfqq)
4198 {
4199 struct cfq_io_cq *cic = cfqd->active_cic;
4200 u64 now = ktime_get_ns();
4201
4202 /* If the queue already has requests, don't wait */
4203 if (!RB_EMPTY_ROOT(&cfqq->sort_list))
4204 return false;
4205
4206 /* If there are other queues in the group, don't wait */
4207 if (cfqq->cfqg->nr_cfqq > 1)
4208 return false;
4209
4210 /* the only queue in the group, but think time is big */
4211 if (cfq_io_thinktime_big(cfqd, &cfqq->cfqg->ttime, true))
4212 return false;
4213
4214 if (cfq_slice_used(cfqq))
4215 return true;
4216
4217 /* if slice left is less than think time, wait busy */
4218 if (cic && sample_valid(cic->ttime.ttime_samples)
4219 && (cfqq->slice_end - now < cic->ttime.ttime_mean))
4220 return true;
4221
4222 /*
4223 * If think times is less than a jiffy than ttime_mean=0 and above
4224 * will not be true. It might happen that slice has not expired yet
4225 * but will expire soon (4-5 ns) during select_queue(). To cover the
4226 * case where think time is less than a jiffy, mark the queue wait
4227 * busy if only 1 jiffy is left in the slice.
4228 */
4229 if (cfqq->slice_end - now <= jiffies_to_nsecs(1))
4230 return true;
4231
4232 return false;
4233 }
4234
4235 static void cfq_completed_request(struct request_queue *q, struct request *rq)
4236 {
4237 struct cfq_queue *cfqq = RQ_CFQQ(rq);
4238 struct cfq_data *cfqd = cfqq->cfqd;
4239 const int sync = rq_is_sync(rq);
4240 u64 now = ktime_get_ns();
4241
4242 cfq_log_cfqq(cfqd, cfqq, "complete rqnoidle %d", req_noidle(rq));
4243
4244 cfq_update_hw_tag(cfqd);
4245
4246 WARN_ON(!cfqd->rq_in_driver);
4247 WARN_ON(!cfqq->dispatched);
4248 cfqd->rq_in_driver--;
4249 cfqq->dispatched--;
4250 (RQ_CFQG(rq))->dispatched--;
4251 cfqg_stats_update_completion(cfqq->cfqg, rq_start_time_ns(rq),
4252 rq_io_start_time_ns(rq), rq->cmd_flags);
4253
4254 cfqd->rq_in_flight[cfq_cfqq_sync(cfqq)]--;
4255
4256 if (sync) {
4257 struct cfq_rb_root *st;
4258
4259 RQ_CIC(rq)->ttime.last_end_request = now;
4260
4261 if (cfq_cfqq_on_rr(cfqq))
4262 st = cfqq->service_tree;
4263 else
4264 st = st_for(cfqq->cfqg, cfqq_class(cfqq),
4265 cfqq_type(cfqq));
4266
4267 st->ttime.last_end_request = now;
4268 /*
4269 * We have to do this check in jiffies since start_time is in
4270 * jiffies and it is not trivial to convert to ns. If
4271 * cfq_fifo_expire[1] ever comes close to 1 jiffie, this test
4272 * will become problematic but so far we are fine (the default
4273 * is 128 ms).
4274 */
4275 if (!time_after(rq->start_time +
4276 nsecs_to_jiffies(cfqd->cfq_fifo_expire[1]),
4277 jiffies))
4278 cfqd->last_delayed_sync = now;
4279 }
4280
4281 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4282 cfqq->cfqg->ttime.last_end_request = now;
4283 #endif
4284
4285 /*
4286 * If this is the active queue, check if it needs to be expired,
4287 * or if we want to idle in case it has no pending requests.
4288 */
4289 if (cfqd->active_queue == cfqq) {
4290 const bool cfqq_empty = RB_EMPTY_ROOT(&cfqq->sort_list);
4291
4292 if (cfq_cfqq_slice_new(cfqq)) {
4293 cfq_set_prio_slice(cfqd, cfqq);
4294 cfq_clear_cfqq_slice_new(cfqq);
4295 }
4296
4297 /*
4298 * Should we wait for next request to come in before we expire
4299 * the queue.
4300 */
4301 if (cfq_should_wait_busy(cfqd, cfqq)) {
4302 u64 extend_sl = cfqd->cfq_slice_idle;
4303 if (!cfqd->cfq_slice_idle)
4304 extend_sl = cfqd->cfq_group_idle;
4305 cfqq->slice_end = now + extend_sl;
4306 cfq_mark_cfqq_wait_busy(cfqq);
4307 cfq_log_cfqq(cfqd, cfqq, "will busy wait");
4308 }
4309
4310 /*
4311 * Idling is not enabled on:
4312 * - expired queues
4313 * - idle-priority queues
4314 * - async queues
4315 * - queues with still some requests queued
4316 * - when there is a close cooperator
4317 */
4318 if (cfq_slice_used(cfqq) || cfq_class_idle(cfqq))
4319 cfq_slice_expired(cfqd, 1);
4320 else if (sync && cfqq_empty &&
4321 !cfq_close_cooperator(cfqd, cfqq)) {
4322 cfq_arm_slice_timer(cfqd);
4323 }
4324 }
4325
4326 if (!cfqd->rq_in_driver)
4327 cfq_schedule_dispatch(cfqd);
4328 }
4329
4330 static void cfqq_boost_on_prio(struct cfq_queue *cfqq, unsigned int op)
4331 {
4332 /*
4333 * If REQ_PRIO is set, boost class and prio level, if it's below
4334 * BE/NORM. If prio is not set, restore the potentially boosted
4335 * class/prio level.
4336 */
4337 if (!(op & REQ_PRIO)) {
4338 cfqq->ioprio_class = cfqq->org_ioprio_class;
4339 cfqq->ioprio = cfqq->org_ioprio;
4340 } else {
4341 if (cfq_class_idle(cfqq))
4342 cfqq->ioprio_class = IOPRIO_CLASS_BE;
4343 if (cfqq->ioprio > IOPRIO_NORM)
4344 cfqq->ioprio = IOPRIO_NORM;
4345 }
4346 }
4347
4348 static inline int __cfq_may_queue(struct cfq_queue *cfqq)
4349 {
4350 if (cfq_cfqq_wait_request(cfqq) && !cfq_cfqq_must_alloc_slice(cfqq)) {
4351 cfq_mark_cfqq_must_alloc_slice(cfqq);
4352 return ELV_MQUEUE_MUST;
4353 }
4354
4355 return ELV_MQUEUE_MAY;
4356 }
4357
4358 static int cfq_may_queue(struct request_queue *q, unsigned int op)
4359 {
4360 struct cfq_data *cfqd = q->elevator->elevator_data;
4361 struct task_struct *tsk = current;
4362 struct cfq_io_cq *cic;
4363 struct cfq_queue *cfqq;
4364
4365 /*
4366 * don't force setup of a queue from here, as a call to may_queue
4367 * does not necessarily imply that a request actually will be queued.
4368 * so just lookup a possibly existing queue, or return 'may queue'
4369 * if that fails
4370 */
4371 cic = cfq_cic_lookup(cfqd, tsk->io_context);
4372 if (!cic)
4373 return ELV_MQUEUE_MAY;
4374
4375 cfqq = cic_to_cfqq(cic, op_is_sync(op));
4376 if (cfqq) {
4377 cfq_init_prio_data(cfqq, cic);
4378 cfqq_boost_on_prio(cfqq, op);
4379
4380 return __cfq_may_queue(cfqq);
4381 }
4382
4383 return ELV_MQUEUE_MAY;
4384 }
4385
4386 /*
4387 * queue lock held here
4388 */
4389 static void cfq_put_request(struct request *rq)
4390 {
4391 struct cfq_queue *cfqq = RQ_CFQQ(rq);
4392
4393 if (cfqq) {
4394 const int rw = rq_data_dir(rq);
4395
4396 BUG_ON(!cfqq->allocated[rw]);
4397 cfqq->allocated[rw]--;
4398
4399 /* Put down rq reference on cfqg */
4400 cfqg_put(RQ_CFQG(rq));
4401 rq->elv.priv[0] = NULL;
4402 rq->elv.priv[1] = NULL;
4403
4404 cfq_put_queue(cfqq);
4405 }
4406 }
4407
4408 static struct cfq_queue *
4409 cfq_merge_cfqqs(struct cfq_data *cfqd, struct cfq_io_cq *cic,
4410 struct cfq_queue *cfqq)
4411 {
4412 cfq_log_cfqq(cfqd, cfqq, "merging with queue %p", cfqq->new_cfqq);
4413 cic_set_cfqq(cic, cfqq->new_cfqq, 1);
4414 cfq_mark_cfqq_coop(cfqq->new_cfqq);
4415 cfq_put_queue(cfqq);
4416 return cic_to_cfqq(cic, 1);
4417 }
4418
4419 /*
4420 * Returns NULL if a new cfqq should be allocated, or the old cfqq if this
4421 * was the last process referring to said cfqq.
4422 */
4423 static struct cfq_queue *
4424 split_cfqq(struct cfq_io_cq *cic, struct cfq_queue *cfqq)
4425 {
4426 if (cfqq_process_refs(cfqq) == 1) {
4427 cfqq->pid = current->pid;
4428 cfq_clear_cfqq_coop(cfqq);
4429 cfq_clear_cfqq_split_coop(cfqq);
4430 return cfqq;
4431 }
4432
4433 cic_set_cfqq(cic, NULL, 1);
4434
4435 cfq_put_cooperator(cfqq);
4436
4437 cfq_put_queue(cfqq);
4438 return NULL;
4439 }
4440 /*
4441 * Allocate cfq data structures associated with this request.
4442 */
4443 static int
4444 cfq_set_request(struct request_queue *q, struct request *rq, struct bio *bio,
4445 gfp_t gfp_mask)
4446 {
4447 struct cfq_data *cfqd = q->elevator->elevator_data;
4448 struct cfq_io_cq *cic = icq_to_cic(rq->elv.icq);
4449 const int rw = rq_data_dir(rq);
4450 const bool is_sync = rq_is_sync(rq);
4451 struct cfq_queue *cfqq;
4452
4453 spin_lock_irq(q->queue_lock);
4454
4455 check_ioprio_changed(cic, bio);
4456 check_blkcg_changed(cic, bio);
4457 new_queue:
4458 cfqq = cic_to_cfqq(cic, is_sync);
4459 if (!cfqq || cfqq == &cfqd->oom_cfqq) {
4460 if (cfqq)
4461 cfq_put_queue(cfqq);
4462 cfqq = cfq_get_queue(cfqd, is_sync, cic, bio);
4463 cic_set_cfqq(cic, cfqq, is_sync);
4464 } else {
4465 /*
4466 * If the queue was seeky for too long, break it apart.
4467 */
4468 if (cfq_cfqq_coop(cfqq) && cfq_cfqq_split_coop(cfqq)) {
4469 cfq_log_cfqq(cfqd, cfqq, "breaking apart cfqq");
4470 cfqq = split_cfqq(cic, cfqq);
4471 if (!cfqq)
4472 goto new_queue;
4473 }
4474
4475 /*
4476 * Check to see if this queue is scheduled to merge with
4477 * another, closely cooperating queue. The merging of
4478 * queues happens here as it must be done in process context.
4479 * The reference on new_cfqq was taken in merge_cfqqs.
4480 */
4481 if (cfqq->new_cfqq)
4482 cfqq = cfq_merge_cfqqs(cfqd, cic, cfqq);
4483 }
4484
4485 cfqq->allocated[rw]++;
4486
4487 cfqq->ref++;
4488 cfqg_get(cfqq->cfqg);
4489 rq->elv.priv[0] = cfqq;
4490 rq->elv.priv[1] = cfqq->cfqg;
4491 spin_unlock_irq(q->queue_lock);
4492
4493 return 0;
4494 }
4495
4496 static void cfq_kick_queue(struct work_struct *work)
4497 {
4498 struct cfq_data *cfqd =
4499 container_of(work, struct cfq_data, unplug_work);
4500 struct request_queue *q = cfqd->queue;
4501
4502 spin_lock_irq(q->queue_lock);
4503 __blk_run_queue(cfqd->queue);
4504 spin_unlock_irq(q->queue_lock);
4505 }
4506
4507 /*
4508 * Timer running if the active_queue is currently idling inside its time slice
4509 */
4510 static enum hrtimer_restart cfq_idle_slice_timer(struct hrtimer *timer)
4511 {
4512 struct cfq_data *cfqd = container_of(timer, struct cfq_data,
4513 idle_slice_timer);
4514 struct cfq_queue *cfqq;
4515 unsigned long flags;
4516 int timed_out = 1;
4517
4518 cfq_log(cfqd, "idle timer fired");
4519
4520 spin_lock_irqsave(cfqd->queue->queue_lock, flags);
4521
4522 cfqq = cfqd->active_queue;
4523 if (cfqq) {
4524 timed_out = 0;
4525
4526 /*
4527 * We saw a request before the queue expired, let it through
4528 */
4529 if (cfq_cfqq_must_dispatch(cfqq))
4530 goto out_kick;
4531
4532 /*
4533 * expired
4534 */
4535 if (cfq_slice_used(cfqq))
4536 goto expire;
4537
4538 /*
4539 * only expire and reinvoke request handler, if there are
4540 * other queues with pending requests
4541 */
4542 if (!cfqd->busy_queues)
4543 goto out_cont;
4544
4545 /*
4546 * not expired and it has a request pending, let it dispatch
4547 */
4548 if (!RB_EMPTY_ROOT(&cfqq->sort_list))
4549 goto out_kick;
4550
4551 /*
4552 * Queue depth flag is reset only when the idle didn't succeed
4553 */
4554 cfq_clear_cfqq_deep(cfqq);
4555 }
4556 expire:
4557 cfq_slice_expired(cfqd, timed_out);
4558 out_kick:
4559 cfq_schedule_dispatch(cfqd);
4560 out_cont:
4561 spin_unlock_irqrestore(cfqd->queue->queue_lock, flags);
4562 return HRTIMER_NORESTART;
4563 }
4564
4565 static void cfq_shutdown_timer_wq(struct cfq_data *cfqd)
4566 {
4567 hrtimer_cancel(&cfqd->idle_slice_timer);
4568 cancel_work_sync(&cfqd->unplug_work);
4569 }
4570
4571 static void cfq_exit_queue(struct elevator_queue *e)
4572 {
4573 struct cfq_data *cfqd = e->elevator_data;
4574 struct request_queue *q = cfqd->queue;
4575
4576 cfq_shutdown_timer_wq(cfqd);
4577
4578 spin_lock_irq(q->queue_lock);
4579
4580 if (cfqd->active_queue)
4581 __cfq_slice_expired(cfqd, cfqd->active_queue, 0);
4582
4583 spin_unlock_irq(q->queue_lock);
4584
4585 cfq_shutdown_timer_wq(cfqd);
4586
4587 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4588 blkcg_deactivate_policy(q, &blkcg_policy_cfq);
4589 #else
4590 kfree(cfqd->root_group);
4591 #endif
4592 kfree(cfqd);
4593 }
4594
4595 static int cfq_init_queue(struct request_queue *q, struct elevator_type *e)
4596 {
4597 struct cfq_data *cfqd;
4598 struct blkcg_gq *blkg __maybe_unused;
4599 int i, ret;
4600 struct elevator_queue *eq;
4601
4602 eq = elevator_alloc(q, e);
4603 if (!eq)
4604 return -ENOMEM;
4605
4606 cfqd = kzalloc_node(sizeof(*cfqd), GFP_KERNEL, q->node);
4607 if (!cfqd) {
4608 kobject_put(&eq->kobj);
4609 return -ENOMEM;
4610 }
4611 eq->elevator_data = cfqd;
4612
4613 cfqd->queue = q;
4614 spin_lock_irq(q->queue_lock);
4615 q->elevator = eq;
4616 spin_unlock_irq(q->queue_lock);
4617
4618 /* Init root service tree */
4619 cfqd->grp_service_tree = CFQ_RB_ROOT;
4620
4621 /* Init root group and prefer root group over other groups by default */
4622 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4623 ret = blkcg_activate_policy(q, &blkcg_policy_cfq);
4624 if (ret)
4625 goto out_free;
4626
4627 cfqd->root_group = blkg_to_cfqg(q->root_blkg);
4628 #else
4629 ret = -ENOMEM;
4630 cfqd->root_group = kzalloc_node(sizeof(*cfqd->root_group),
4631 GFP_KERNEL, cfqd->queue->node);
4632 if (!cfqd->root_group)
4633 goto out_free;
4634
4635 cfq_init_cfqg_base(cfqd->root_group);
4636 cfqd->root_group->weight = 2 * CFQ_WEIGHT_LEGACY_DFL;
4637 cfqd->root_group->leaf_weight = 2 * CFQ_WEIGHT_LEGACY_DFL;
4638 #endif
4639
4640 /*
4641 * Not strictly needed (since RB_ROOT just clears the node and we
4642 * zeroed cfqd on alloc), but better be safe in case someone decides
4643 * to add magic to the rb code
4644 */
4645 for (i = 0; i < CFQ_PRIO_LISTS; i++)
4646 cfqd->prio_trees[i] = RB_ROOT;
4647
4648 /*
4649 * Our fallback cfqq if cfq_get_queue() runs into OOM issues.
4650 * Grab a permanent reference to it, so that the normal code flow
4651 * will not attempt to free it. oom_cfqq is linked to root_group
4652 * but shouldn't hold a reference as it'll never be unlinked. Lose
4653 * the reference from linking right away.
4654 */
4655 cfq_init_cfqq(cfqd, &cfqd->oom_cfqq, 1, 0);
4656 cfqd->oom_cfqq.ref++;
4657
4658 spin_lock_irq(q->queue_lock);
4659 cfq_link_cfqq_cfqg(&cfqd->oom_cfqq, cfqd->root_group);
4660 cfqg_put(cfqd->root_group);
4661 spin_unlock_irq(q->queue_lock);
4662
4663 hrtimer_init(&cfqd->idle_slice_timer, CLOCK_MONOTONIC,
4664 HRTIMER_MODE_REL);
4665 cfqd->idle_slice_timer.function = cfq_idle_slice_timer;
4666
4667 INIT_WORK(&cfqd->unplug_work, cfq_kick_queue);
4668
4669 cfqd->cfq_quantum = cfq_quantum;
4670 cfqd->cfq_fifo_expire[0] = cfq_fifo_expire[0];
4671 cfqd->cfq_fifo_expire[1] = cfq_fifo_expire[1];
4672 cfqd->cfq_back_max = cfq_back_max;
4673 cfqd->cfq_back_penalty = cfq_back_penalty;
4674 cfqd->cfq_slice[0] = cfq_slice_async;
4675 cfqd->cfq_slice[1] = cfq_slice_sync;
4676 cfqd->cfq_target_latency = cfq_target_latency;
4677 cfqd->cfq_slice_async_rq = cfq_slice_async_rq;
4678 cfqd->cfq_slice_idle = cfq_slice_idle;
4679 cfqd->cfq_group_idle = cfq_group_idle;
4680 cfqd->cfq_latency = 1;
4681 cfqd->hw_tag = -1;
4682 /*
4683 * we optimistically start assuming sync ops weren't delayed in last
4684 * second, in order to have larger depth for async operations.
4685 */
4686 cfqd->last_delayed_sync = ktime_get_ns() - NSEC_PER_SEC;
4687 return 0;
4688
4689 out_free:
4690 kfree(cfqd);
4691 kobject_put(&eq->kobj);
4692 return ret;
4693 }
4694
4695 static void cfq_registered_queue(struct request_queue *q)
4696 {
4697 struct elevator_queue *e = q->elevator;
4698 struct cfq_data *cfqd = e->elevator_data;
4699
4700 /*
4701 * Default to IOPS mode with no idling for SSDs
4702 */
4703 if (blk_queue_nonrot(q))
4704 cfqd->cfq_slice_idle = 0;
4705 wbt_disable_default(q);
4706 }
4707
4708 /*
4709 * sysfs parts below -->
4710 */
4711 static ssize_t
4712 cfq_var_show(unsigned int var, char *page)
4713 {
4714 return sprintf(page, "%u\n", var);
4715 }
4716
4717 static ssize_t
4718 cfq_var_store(unsigned int *var, const char *page, size_t count)
4719 {
4720 char *p = (char *) page;
4721
4722 *var = simple_strtoul(p, &p, 10);
4723 return count;
4724 }
4725
4726 #define SHOW_FUNCTION(__FUNC, __VAR, __CONV) \
4727 static ssize_t __FUNC(struct elevator_queue *e, char *page) \
4728 { \
4729 struct cfq_data *cfqd = e->elevator_data; \
4730 u64 __data = __VAR; \
4731 if (__CONV) \
4732 __data = div_u64(__data, NSEC_PER_MSEC); \
4733 return cfq_var_show(__data, (page)); \
4734 }
4735 SHOW_FUNCTION(cfq_quantum_show, cfqd->cfq_quantum, 0);
4736 SHOW_FUNCTION(cfq_fifo_expire_sync_show, cfqd->cfq_fifo_expire[1], 1);
4737 SHOW_FUNCTION(cfq_fifo_expire_async_show, cfqd->cfq_fifo_expire[0], 1);
4738 SHOW_FUNCTION(cfq_back_seek_max_show, cfqd->cfq_back_max, 0);
4739 SHOW_FUNCTION(cfq_back_seek_penalty_show, cfqd->cfq_back_penalty, 0);
4740 SHOW_FUNCTION(cfq_slice_idle_show, cfqd->cfq_slice_idle, 1);
4741 SHOW_FUNCTION(cfq_group_idle_show, cfqd->cfq_group_idle, 1);
4742 SHOW_FUNCTION(cfq_slice_sync_show, cfqd->cfq_slice[1], 1);
4743 SHOW_FUNCTION(cfq_slice_async_show, cfqd->cfq_slice[0], 1);
4744 SHOW_FUNCTION(cfq_slice_async_rq_show, cfqd->cfq_slice_async_rq, 0);
4745 SHOW_FUNCTION(cfq_low_latency_show, cfqd->cfq_latency, 0);
4746 SHOW_FUNCTION(cfq_target_latency_show, cfqd->cfq_target_latency, 1);
4747 #undef SHOW_FUNCTION
4748
4749 #define USEC_SHOW_FUNCTION(__FUNC, __VAR) \
4750 static ssize_t __FUNC(struct elevator_queue *e, char *page) \
4751 { \
4752 struct cfq_data *cfqd = e->elevator_data; \
4753 u64 __data = __VAR; \
4754 __data = div_u64(__data, NSEC_PER_USEC); \
4755 return cfq_var_show(__data, (page)); \
4756 }
4757 USEC_SHOW_FUNCTION(cfq_slice_idle_us_show, cfqd->cfq_slice_idle);
4758 USEC_SHOW_FUNCTION(cfq_group_idle_us_show, cfqd->cfq_group_idle);
4759 USEC_SHOW_FUNCTION(cfq_slice_sync_us_show, cfqd->cfq_slice[1]);
4760 USEC_SHOW_FUNCTION(cfq_slice_async_us_show, cfqd->cfq_slice[0]);
4761 USEC_SHOW_FUNCTION(cfq_target_latency_us_show, cfqd->cfq_target_latency);
4762 #undef USEC_SHOW_FUNCTION
4763
4764 #define STORE_FUNCTION(__FUNC, __PTR, MIN, MAX, __CONV) \
4765 static ssize_t __FUNC(struct elevator_queue *e, const char *page, size_t count) \
4766 { \
4767 struct cfq_data *cfqd = e->elevator_data; \
4768 unsigned int __data; \
4769 int ret = cfq_var_store(&__data, (page), count); \
4770 if (__data < (MIN)) \
4771 __data = (MIN); \
4772 else if (__data > (MAX)) \
4773 __data = (MAX); \
4774 if (__CONV) \
4775 *(__PTR) = (u64)__data * NSEC_PER_MSEC; \
4776 else \
4777 *(__PTR) = __data; \
4778 return ret; \
4779 }
4780 STORE_FUNCTION(cfq_quantum_store, &cfqd->cfq_quantum, 1, UINT_MAX, 0);
4781 STORE_FUNCTION(cfq_fifo_expire_sync_store, &cfqd->cfq_fifo_expire[1], 1,
4782 UINT_MAX, 1);
4783 STORE_FUNCTION(cfq_fifo_expire_async_store, &cfqd->cfq_fifo_expire[0], 1,
4784 UINT_MAX, 1);
4785 STORE_FUNCTION(cfq_back_seek_max_store, &cfqd->cfq_back_max, 0, UINT_MAX, 0);
4786 STORE_FUNCTION(cfq_back_seek_penalty_store, &cfqd->cfq_back_penalty, 1,
4787 UINT_MAX, 0);
4788 STORE_FUNCTION(cfq_slice_idle_store, &cfqd->cfq_slice_idle, 0, UINT_MAX, 1);
4789 STORE_FUNCTION(cfq_group_idle_store, &cfqd->cfq_group_idle, 0, UINT_MAX, 1);
4790 STORE_FUNCTION(cfq_slice_sync_store, &cfqd->cfq_slice[1], 1, UINT_MAX, 1);
4791 STORE_FUNCTION(cfq_slice_async_store, &cfqd->cfq_slice[0], 1, UINT_MAX, 1);
4792 STORE_FUNCTION(cfq_slice_async_rq_store, &cfqd->cfq_slice_async_rq, 1,
4793 UINT_MAX, 0);
4794 STORE_FUNCTION(cfq_low_latency_store, &cfqd->cfq_latency, 0, 1, 0);
4795 STORE_FUNCTION(cfq_target_latency_store, &cfqd->cfq_target_latency, 1, UINT_MAX, 1);
4796 #undef STORE_FUNCTION
4797
4798 #define USEC_STORE_FUNCTION(__FUNC, __PTR, MIN, MAX) \
4799 static ssize_t __FUNC(struct elevator_queue *e, const char *page, size_t count) \
4800 { \
4801 struct cfq_data *cfqd = e->elevator_data; \
4802 unsigned int __data; \
4803 int ret = cfq_var_store(&__data, (page), count); \
4804 if (__data < (MIN)) \
4805 __data = (MIN); \
4806 else if (__data > (MAX)) \
4807 __data = (MAX); \
4808 *(__PTR) = (u64)__data * NSEC_PER_USEC; \
4809 return ret; \
4810 }
4811 USEC_STORE_FUNCTION(cfq_slice_idle_us_store, &cfqd->cfq_slice_idle, 0, UINT_MAX);
4812 USEC_STORE_FUNCTION(cfq_group_idle_us_store, &cfqd->cfq_group_idle, 0, UINT_MAX);
4813 USEC_STORE_FUNCTION(cfq_slice_sync_us_store, &cfqd->cfq_slice[1], 1, UINT_MAX);
4814 USEC_STORE_FUNCTION(cfq_slice_async_us_store, &cfqd->cfq_slice[0], 1, UINT_MAX);
4815 USEC_STORE_FUNCTION(cfq_target_latency_us_store, &cfqd->cfq_target_latency, 1, UINT_MAX);
4816 #undef USEC_STORE_FUNCTION
4817
4818 #define CFQ_ATTR(name) \
4819 __ATTR(name, S_IRUGO|S_IWUSR, cfq_##name##_show, cfq_##name##_store)
4820
4821 static struct elv_fs_entry cfq_attrs[] = {
4822 CFQ_ATTR(quantum),
4823 CFQ_ATTR(fifo_expire_sync),
4824 CFQ_ATTR(fifo_expire_async),
4825 CFQ_ATTR(back_seek_max),
4826 CFQ_ATTR(back_seek_penalty),
4827 CFQ_ATTR(slice_sync),
4828 CFQ_ATTR(slice_sync_us),
4829 CFQ_ATTR(slice_async),
4830 CFQ_ATTR(slice_async_us),
4831 CFQ_ATTR(slice_async_rq),
4832 CFQ_ATTR(slice_idle),
4833 CFQ_ATTR(slice_idle_us),
4834 CFQ_ATTR(group_idle),
4835 CFQ_ATTR(group_idle_us),
4836 CFQ_ATTR(low_latency),
4837 CFQ_ATTR(target_latency),
4838 CFQ_ATTR(target_latency_us),
4839 __ATTR_NULL
4840 };
4841
4842 static struct elevator_type iosched_cfq = {
4843 .ops.sq = {
4844 .elevator_merge_fn = cfq_merge,
4845 .elevator_merged_fn = cfq_merged_request,
4846 .elevator_merge_req_fn = cfq_merged_requests,
4847 .elevator_allow_bio_merge_fn = cfq_allow_bio_merge,
4848 .elevator_allow_rq_merge_fn = cfq_allow_rq_merge,
4849 .elevator_bio_merged_fn = cfq_bio_merged,
4850 .elevator_dispatch_fn = cfq_dispatch_requests,
4851 .elevator_add_req_fn = cfq_insert_request,
4852 .elevator_activate_req_fn = cfq_activate_request,
4853 .elevator_deactivate_req_fn = cfq_deactivate_request,
4854 .elevator_completed_req_fn = cfq_completed_request,
4855 .elevator_former_req_fn = elv_rb_former_request,
4856 .elevator_latter_req_fn = elv_rb_latter_request,
4857 .elevator_init_icq_fn = cfq_init_icq,
4858 .elevator_exit_icq_fn = cfq_exit_icq,
4859 .elevator_set_req_fn = cfq_set_request,
4860 .elevator_put_req_fn = cfq_put_request,
4861 .elevator_may_queue_fn = cfq_may_queue,
4862 .elevator_init_fn = cfq_init_queue,
4863 .elevator_exit_fn = cfq_exit_queue,
4864 .elevator_registered_fn = cfq_registered_queue,
4865 },
4866 .icq_size = sizeof(struct cfq_io_cq),
4867 .icq_align = __alignof__(struct cfq_io_cq),
4868 .elevator_attrs = cfq_attrs,
4869 .elevator_name = "cfq",
4870 .elevator_owner = THIS_MODULE,
4871 };
4872
4873 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4874 static struct blkcg_policy blkcg_policy_cfq = {
4875 .dfl_cftypes = cfq_blkcg_files,
4876 .legacy_cftypes = cfq_blkcg_legacy_files,
4877
4878 .cpd_alloc_fn = cfq_cpd_alloc,
4879 .cpd_init_fn = cfq_cpd_init,
4880 .cpd_free_fn = cfq_cpd_free,
4881 .cpd_bind_fn = cfq_cpd_bind,
4882
4883 .pd_alloc_fn = cfq_pd_alloc,
4884 .pd_init_fn = cfq_pd_init,
4885 .pd_offline_fn = cfq_pd_offline,
4886 .pd_free_fn = cfq_pd_free,
4887 .pd_reset_stats_fn = cfq_pd_reset_stats,
4888 };
4889 #endif
4890
4891 static int __init cfq_init(void)
4892 {
4893 int ret;
4894
4895 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4896 ret = blkcg_policy_register(&blkcg_policy_cfq);
4897 if (ret)
4898 return ret;
4899 #else
4900 cfq_group_idle = 0;
4901 #endif
4902
4903 ret = -ENOMEM;
4904 cfq_pool = KMEM_CACHE(cfq_queue, 0);
4905 if (!cfq_pool)
4906 goto err_pol_unreg;
4907
4908 ret = elv_register(&iosched_cfq);
4909 if (ret)
4910 goto err_free_pool;
4911
4912 return 0;
4913
4914 err_free_pool:
4915 kmem_cache_destroy(cfq_pool);
4916 err_pol_unreg:
4917 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4918 blkcg_policy_unregister(&blkcg_policy_cfq);
4919 #endif
4920 return ret;
4921 }
4922
4923 static void __exit cfq_exit(void)
4924 {
4925 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4926 blkcg_policy_unregister(&blkcg_policy_cfq);
4927 #endif
4928 elv_unregister(&iosched_cfq);
4929 kmem_cache_destroy(cfq_pool);
4930 }
4931
4932 module_init(cfq_init);
4933 module_exit(cfq_exit);
4934
4935 MODULE_AUTHOR("Jens Axboe");
4936 MODULE_LICENSE("GPL");
4937 MODULE_DESCRIPTION("Completely Fair Queueing IO scheduler");