2 * CFQ, or complete fairness queueing, disk scheduler.
4 * Based on ideas from a previously unfinished io
5 * scheduler (round robin per-process disk scheduling) and Andrea Arcangeli.
7 * Copyright (C) 2003 Jens Axboe <axboe@kernel.dk>
9 #include <linux/module.h>
10 #include <linux/slab.h>
11 #include <linux/blkdev.h>
12 #include <linux/elevator.h>
13 #include <linux/ktime.h>
14 #include <linux/rbtree.h>
15 #include <linux/ioprio.h>
16 #include <linux/blktrace_api.h>
17 #include <linux/blk-cgroup.h>
23 /* max queue in one round of service */
24 static const int cfq_quantum = 8;
25 static const u64 cfq_fifo_expire[2] = { NSEC_PER_SEC / 4, NSEC_PER_SEC / 8 };
26 /* maximum backwards seek, in KiB */
27 static const int cfq_back_max = 16 * 1024;
28 /* penalty of a backwards seek */
29 static const int cfq_back_penalty = 2;
30 static const u64 cfq_slice_sync = NSEC_PER_SEC / 10;
31 static u64 cfq_slice_async = NSEC_PER_SEC / 25;
32 static const int cfq_slice_async_rq = 2;
33 static u64 cfq_slice_idle = NSEC_PER_SEC / 125;
34 static u64 cfq_group_idle = NSEC_PER_SEC / 125;
35 static const u64 cfq_target_latency = (u64)NSEC_PER_SEC * 3/10; /* 300 ms */
36 static const int cfq_hist_divisor = 4;
39 * offset from end of queue service tree for idle class
41 #define CFQ_IDLE_DELAY (NSEC_PER_SEC / 5)
42 /* offset from end of group service tree under time slice mode */
43 #define CFQ_SLICE_MODE_GROUP_DELAY (NSEC_PER_SEC / 5)
44 /* offset from end of group service under IOPS mode */
45 #define CFQ_IOPS_MODE_GROUP_DELAY (HZ / 5)
48 * below this threshold, we consider thinktime immediate
50 #define CFQ_MIN_TT (2 * NSEC_PER_SEC / HZ)
52 #define CFQ_SLICE_SCALE (5)
53 #define CFQ_HW_QUEUE_MIN (5)
54 #define CFQ_SERVICE_SHIFT 12
56 #define CFQQ_SEEK_THR (sector_t)(8 * 100)
57 #define CFQQ_CLOSE_THR (sector_t)(8 * 1024)
58 #define CFQQ_SECT_THR_NONROT (sector_t)(2 * 32)
59 #define CFQQ_SEEKY(cfqq) (hweight32(cfqq->seek_history) > 32/8)
61 #define RQ_CIC(rq) icq_to_cic((rq)->elv.icq)
62 #define RQ_CFQQ(rq) (struct cfq_queue *) ((rq)->elv.priv[0])
63 #define RQ_CFQG(rq) (struct cfq_group *) ((rq)->elv.priv[1])
65 static struct kmem_cache *cfq_pool;
67 #define CFQ_PRIO_LISTS IOPRIO_BE_NR
68 #define cfq_class_idle(cfqq) ((cfqq)->ioprio_class == IOPRIO_CLASS_IDLE)
69 #define cfq_class_rt(cfqq) ((cfqq)->ioprio_class == IOPRIO_CLASS_RT)
71 #define sample_valid(samples) ((samples) > 80)
72 #define rb_entry_cfqg(node) rb_entry((node), struct cfq_group, rb_node)
74 /* blkio-related constants */
75 #define CFQ_WEIGHT_LEGACY_MIN 10
76 #define CFQ_WEIGHT_LEGACY_DFL 500
77 #define CFQ_WEIGHT_LEGACY_MAX 1000
84 unsigned long ttime_samples;
88 * Most of our rbtree usage is for sorting with min extraction, so
89 * if we cache the leftmost node we don't have to walk down the tree
90 * to find it. Idea borrowed from Ingo Molnars CFS scheduler. We should
91 * move this into the elevator for the rq sorting as well.
98 struct cfq_ttime ttime;
100 #define CFQ_RB_ROOT (struct cfq_rb_root) { .rb = RB_ROOT, \
101 .ttime = {.last_end_request = ktime_get_ns(),},}
104 * Per process-grouping structure
107 /* reference count */
109 /* various state flags, see below */
111 /* parent cfq_data */
112 struct cfq_data *cfqd;
113 /* service_tree member */
114 struct rb_node rb_node;
115 /* service_tree key */
117 /* prio tree member */
118 struct rb_node p_node;
119 /* prio tree root we belong to, if any */
120 struct rb_root *p_root;
121 /* sorted list of pending requests */
122 struct rb_root sort_list;
123 /* if fifo isn't expired, next request to serve */
124 struct request *next_rq;
125 /* requests queued in sort_list */
127 /* currently allocated requests */
129 /* fifo list of requests in sort_list */
130 struct list_head fifo;
132 /* time when queue got scheduled in to dispatch first request. */
136 /* time when first request from queue completed and slice started. */
141 /* pending priority requests */
143 /* number of requests that are on the dispatch list or inside driver */
146 /* io prio of this group */
147 unsigned short ioprio, org_ioprio;
148 unsigned short ioprio_class;
153 sector_t last_request_pos;
155 struct cfq_rb_root *service_tree;
156 struct cfq_queue *new_cfqq;
157 struct cfq_group *cfqg;
158 /* Number of sectors dispatched from queue in single dispatch round */
159 unsigned long nr_sectors;
163 * First index in the service_trees.
164 * IDLE is handled separately, so it has negative index
174 * Second index in the service_trees.
178 SYNC_NOIDLE_WORKLOAD = 1,
183 #ifdef CONFIG_CFQ_GROUP_IOSCHED
184 /* number of ios merged */
185 struct blkg_rwstat merged;
186 /* total time spent on device in ns, may not be accurate w/ queueing */
187 struct blkg_rwstat service_time;
188 /* total time spent waiting in scheduler queue in ns */
189 struct blkg_rwstat wait_time;
190 /* number of IOs queued up */
191 struct blkg_rwstat queued;
192 /* total disk time and nr sectors dispatched by this group */
193 struct blkg_stat time;
194 #ifdef CONFIG_DEBUG_BLK_CGROUP
195 /* time not charged to this cgroup */
196 struct blkg_stat unaccounted_time;
197 /* sum of number of ios queued across all samples */
198 struct blkg_stat avg_queue_size_sum;
199 /* count of samples taken for average */
200 struct blkg_stat avg_queue_size_samples;
201 /* how many times this group has been removed from service tree */
202 struct blkg_stat dequeue;
203 /* total time spent waiting for it to be assigned a timeslice. */
204 struct blkg_stat group_wait_time;
205 /* time spent idling for this blkcg_gq */
206 struct blkg_stat idle_time;
207 /* total time with empty current active q with other requests queued */
208 struct blkg_stat empty_time;
209 /* fields after this shouldn't be cleared on stat reset */
210 uint64_t start_group_wait_time;
211 uint64_t start_idle_time;
212 uint64_t start_empty_time;
214 #endif /* CONFIG_DEBUG_BLK_CGROUP */
215 #endif /* CONFIG_CFQ_GROUP_IOSCHED */
218 /* Per-cgroup data */
219 struct cfq_group_data {
220 /* must be the first member */
221 struct blkcg_policy_data cpd;
224 unsigned int leaf_weight;
227 /* This is per cgroup per device grouping structure */
229 /* must be the first member */
230 struct blkg_policy_data pd;
232 /* group service_tree member */
233 struct rb_node rb_node;
235 /* group service_tree key */
239 * The number of active cfqgs and sum of their weights under this
240 * cfqg. This covers this cfqg's leaf_weight and all children's
241 * weights, but does not cover weights of further descendants.
243 * If a cfqg is on the service tree, it's active. An active cfqg
244 * also activates its parent and contributes to the children_weight
248 unsigned int children_weight;
251 * vfraction is the fraction of vdisktime that the tasks in this
252 * cfqg are entitled to. This is determined by compounding the
253 * ratios walking up from this cfqg to the root.
255 * It is in fixed point w/ CFQ_SERVICE_SHIFT and the sum of all
256 * vfractions on a service tree is approximately 1. The sum may
257 * deviate a bit due to rounding errors and fluctuations caused by
258 * cfqgs entering and leaving the service tree.
260 unsigned int vfraction;
263 * There are two weights - (internal) weight is the weight of this
264 * cfqg against the sibling cfqgs. leaf_weight is the wight of
265 * this cfqg against the child cfqgs. For the root cfqg, both
266 * weights are kept in sync for backward compatibility.
269 unsigned int new_weight;
270 unsigned int dev_weight;
272 unsigned int leaf_weight;
273 unsigned int new_leaf_weight;
274 unsigned int dev_leaf_weight;
276 /* number of cfqq currently on this group */
280 * Per group busy queues average. Useful for workload slice calc. We
281 * create the array for each prio class but at run time it is used
282 * only for RT and BE class and slot for IDLE class remains unused.
283 * This is primarily done to avoid confusion and a gcc warning.
285 unsigned int busy_queues_avg[CFQ_PRIO_NR];
287 * rr lists of queues with requests. We maintain service trees for
288 * RT and BE classes. These trees are subdivided in subclasses
289 * of SYNC, SYNC_NOIDLE and ASYNC based on workload type. For IDLE
290 * class there is no subclassification and all the cfq queues go on
291 * a single tree service_tree_idle.
292 * Counts are embedded in the cfq_rb_root
294 struct cfq_rb_root service_trees[2][3];
295 struct cfq_rb_root service_tree_idle;
298 enum wl_type_t saved_wl_type;
299 enum wl_class_t saved_wl_class;
301 /* number of requests that are on the dispatch list or inside driver */
303 struct cfq_ttime ttime;
304 struct cfqg_stats stats; /* stats for this cfqg */
306 /* async queue for each priority case */
307 struct cfq_queue *async_cfqq[2][IOPRIO_BE_NR];
308 struct cfq_queue *async_idle_cfqq;
313 struct io_cq icq; /* must be the first member */
314 struct cfq_queue *cfqq[2];
315 struct cfq_ttime ttime;
316 int ioprio; /* the current ioprio */
317 #ifdef CONFIG_CFQ_GROUP_IOSCHED
318 uint64_t blkcg_serial_nr; /* the current blkcg serial */
323 * Per block device queue structure
326 struct request_queue *queue;
327 /* Root service tree for cfq_groups */
328 struct cfq_rb_root grp_service_tree;
329 struct cfq_group *root_group;
332 * The priority currently being served
334 enum wl_class_t serving_wl_class;
335 enum wl_type_t serving_wl_type;
336 u64 workload_expires;
337 struct cfq_group *serving_group;
340 * Each priority tree is sorted by next_request position. These
341 * trees are used when determining if two or more queues are
342 * interleaving requests (see cfq_close_cooperator).
344 struct rb_root prio_trees[CFQ_PRIO_LISTS];
346 unsigned int busy_queues;
347 unsigned int busy_sync_queues;
353 * queue-depth detection
359 * -1 => indeterminate, (cfq will behave as if NCQ is present, to allow better detection)
360 * 1 => NCQ is present (hw_tag_est_depth is the estimated max depth)
363 int hw_tag_est_depth;
364 unsigned int hw_tag_samples;
367 * idle window management
369 struct hrtimer idle_slice_timer;
370 struct work_struct unplug_work;
372 struct cfq_queue *active_queue;
373 struct cfq_io_cq *active_cic;
375 sector_t last_position;
378 * tunables, see top of file
380 unsigned int cfq_quantum;
381 unsigned int cfq_back_penalty;
382 unsigned int cfq_back_max;
383 unsigned int cfq_slice_async_rq;
384 unsigned int cfq_latency;
385 u64 cfq_fifo_expire[2];
389 u64 cfq_target_latency;
392 * Fallback dummy cfqq for extreme OOM conditions
394 struct cfq_queue oom_cfqq;
396 u64 last_delayed_sync;
399 static struct cfq_group *cfq_get_next_cfqg(struct cfq_data *cfqd);
400 static void cfq_put_queue(struct cfq_queue *cfqq);
402 static struct cfq_rb_root *st_for(struct cfq_group *cfqg,
403 enum wl_class_t class,
409 if (class == IDLE_WORKLOAD)
410 return &cfqg->service_tree_idle;
412 return &cfqg->service_trees[class][type];
415 enum cfqq_state_flags {
416 CFQ_CFQQ_FLAG_on_rr = 0, /* on round-robin busy list */
417 CFQ_CFQQ_FLAG_wait_request, /* waiting for a request */
418 CFQ_CFQQ_FLAG_must_dispatch, /* must be allowed a dispatch */
419 CFQ_CFQQ_FLAG_must_alloc_slice, /* per-slice must_alloc flag */
420 CFQ_CFQQ_FLAG_fifo_expire, /* FIFO checked in this slice */
421 CFQ_CFQQ_FLAG_idle_window, /* slice idling enabled */
422 CFQ_CFQQ_FLAG_prio_changed, /* task priority has changed */
423 CFQ_CFQQ_FLAG_slice_new, /* no requests dispatched in slice */
424 CFQ_CFQQ_FLAG_sync, /* synchronous queue */
425 CFQ_CFQQ_FLAG_coop, /* cfqq is shared */
426 CFQ_CFQQ_FLAG_split_coop, /* shared cfqq will be splitted */
427 CFQ_CFQQ_FLAG_deep, /* sync cfqq experienced large depth */
428 CFQ_CFQQ_FLAG_wait_busy, /* Waiting for next request */
431 #define CFQ_CFQQ_FNS(name) \
432 static inline void cfq_mark_cfqq_##name(struct cfq_queue *cfqq) \
434 (cfqq)->flags |= (1 << CFQ_CFQQ_FLAG_##name); \
436 static inline void cfq_clear_cfqq_##name(struct cfq_queue *cfqq) \
438 (cfqq)->flags &= ~(1 << CFQ_CFQQ_FLAG_##name); \
440 static inline int cfq_cfqq_##name(const struct cfq_queue *cfqq) \
442 return ((cfqq)->flags & (1 << CFQ_CFQQ_FLAG_##name)) != 0; \
446 CFQ_CFQQ_FNS(wait_request);
447 CFQ_CFQQ_FNS(must_dispatch);
448 CFQ_CFQQ_FNS(must_alloc_slice);
449 CFQ_CFQQ_FNS(fifo_expire);
450 CFQ_CFQQ_FNS(idle_window);
451 CFQ_CFQQ_FNS(prio_changed);
452 CFQ_CFQQ_FNS(slice_new);
455 CFQ_CFQQ_FNS(split_coop);
457 CFQ_CFQQ_FNS(wait_busy);
460 #if defined(CONFIG_CFQ_GROUP_IOSCHED) && defined(CONFIG_DEBUG_BLK_CGROUP)
462 /* cfqg stats flags */
463 enum cfqg_stats_flags {
464 CFQG_stats_waiting = 0,
469 #define CFQG_FLAG_FNS(name) \
470 static inline void cfqg_stats_mark_##name(struct cfqg_stats *stats) \
472 stats->flags |= (1 << CFQG_stats_##name); \
474 static inline void cfqg_stats_clear_##name(struct cfqg_stats *stats) \
476 stats->flags &= ~(1 << CFQG_stats_##name); \
478 static inline int cfqg_stats_##name(struct cfqg_stats *stats) \
480 return (stats->flags & (1 << CFQG_stats_##name)) != 0; \
483 CFQG_FLAG_FNS(waiting)
484 CFQG_FLAG_FNS(idling)
488 /* This should be called with the queue_lock held. */
489 static void cfqg_stats_update_group_wait_time(struct cfqg_stats *stats)
491 unsigned long long now;
493 if (!cfqg_stats_waiting(stats))
497 if (time_after64(now, stats->start_group_wait_time))
498 blkg_stat_add(&stats->group_wait_time,
499 now - stats->start_group_wait_time);
500 cfqg_stats_clear_waiting(stats);
503 /* This should be called with the queue_lock held. */
504 static void cfqg_stats_set_start_group_wait_time(struct cfq_group *cfqg,
505 struct cfq_group *curr_cfqg)
507 struct cfqg_stats *stats = &cfqg->stats;
509 if (cfqg_stats_waiting(stats))
511 if (cfqg == curr_cfqg)
513 stats->start_group_wait_time = sched_clock();
514 cfqg_stats_mark_waiting(stats);
517 /* This should be called with the queue_lock held. */
518 static void cfqg_stats_end_empty_time(struct cfqg_stats *stats)
520 unsigned long long now;
522 if (!cfqg_stats_empty(stats))
526 if (time_after64(now, stats->start_empty_time))
527 blkg_stat_add(&stats->empty_time,
528 now - stats->start_empty_time);
529 cfqg_stats_clear_empty(stats);
532 static void cfqg_stats_update_dequeue(struct cfq_group *cfqg)
534 blkg_stat_add(&cfqg->stats.dequeue, 1);
537 static void cfqg_stats_set_start_empty_time(struct cfq_group *cfqg)
539 struct cfqg_stats *stats = &cfqg->stats;
541 if (blkg_rwstat_total(&stats->queued))
545 * group is already marked empty. This can happen if cfqq got new
546 * request in parent group and moved to this group while being added
547 * to service tree. Just ignore the event and move on.
549 if (cfqg_stats_empty(stats))
552 stats->start_empty_time = sched_clock();
553 cfqg_stats_mark_empty(stats);
556 static void cfqg_stats_update_idle_time(struct cfq_group *cfqg)
558 struct cfqg_stats *stats = &cfqg->stats;
560 if (cfqg_stats_idling(stats)) {
561 unsigned long long now = sched_clock();
563 if (time_after64(now, stats->start_idle_time))
564 blkg_stat_add(&stats->idle_time,
565 now - stats->start_idle_time);
566 cfqg_stats_clear_idling(stats);
570 static void cfqg_stats_set_start_idle_time(struct cfq_group *cfqg)
572 struct cfqg_stats *stats = &cfqg->stats;
574 BUG_ON(cfqg_stats_idling(stats));
576 stats->start_idle_time = sched_clock();
577 cfqg_stats_mark_idling(stats);
580 static void cfqg_stats_update_avg_queue_size(struct cfq_group *cfqg)
582 struct cfqg_stats *stats = &cfqg->stats;
584 blkg_stat_add(&stats->avg_queue_size_sum,
585 blkg_rwstat_total(&stats->queued));
586 blkg_stat_add(&stats->avg_queue_size_samples, 1);
587 cfqg_stats_update_group_wait_time(stats);
590 #else /* CONFIG_CFQ_GROUP_IOSCHED && CONFIG_DEBUG_BLK_CGROUP */
592 static inline void cfqg_stats_set_start_group_wait_time(struct cfq_group *cfqg, struct cfq_group *curr_cfqg) { }
593 static inline void cfqg_stats_end_empty_time(struct cfqg_stats *stats) { }
594 static inline void cfqg_stats_update_dequeue(struct cfq_group *cfqg) { }
595 static inline void cfqg_stats_set_start_empty_time(struct cfq_group *cfqg) { }
596 static inline void cfqg_stats_update_idle_time(struct cfq_group *cfqg) { }
597 static inline void cfqg_stats_set_start_idle_time(struct cfq_group *cfqg) { }
598 static inline void cfqg_stats_update_avg_queue_size(struct cfq_group *cfqg) { }
600 #endif /* CONFIG_CFQ_GROUP_IOSCHED && CONFIG_DEBUG_BLK_CGROUP */
602 #ifdef CONFIG_CFQ_GROUP_IOSCHED
604 static inline struct cfq_group *pd_to_cfqg(struct blkg_policy_data *pd)
606 return pd ? container_of(pd, struct cfq_group, pd) : NULL;
609 static struct cfq_group_data
610 *cpd_to_cfqgd(struct blkcg_policy_data *cpd)
612 return cpd ? container_of(cpd, struct cfq_group_data, cpd) : NULL;
615 static inline struct blkcg_gq *cfqg_to_blkg(struct cfq_group *cfqg)
617 return pd_to_blkg(&cfqg->pd);
620 static struct blkcg_policy blkcg_policy_cfq;
622 static inline struct cfq_group *blkg_to_cfqg(struct blkcg_gq *blkg)
624 return pd_to_cfqg(blkg_to_pd(blkg, &blkcg_policy_cfq));
627 static struct cfq_group_data *blkcg_to_cfqgd(struct blkcg *blkcg)
629 return cpd_to_cfqgd(blkcg_to_cpd(blkcg, &blkcg_policy_cfq));
632 static inline struct cfq_group *cfqg_parent(struct cfq_group *cfqg)
634 struct blkcg_gq *pblkg = cfqg_to_blkg(cfqg)->parent;
636 return pblkg ? blkg_to_cfqg(pblkg) : NULL;
639 static inline bool cfqg_is_descendant(struct cfq_group *cfqg,
640 struct cfq_group *ancestor)
642 return cgroup_is_descendant(cfqg_to_blkg(cfqg)->blkcg->css.cgroup,
643 cfqg_to_blkg(ancestor)->blkcg->css.cgroup);
646 static inline void cfqg_get(struct cfq_group *cfqg)
648 return blkg_get(cfqg_to_blkg(cfqg));
651 static inline void cfqg_put(struct cfq_group *cfqg)
653 return blkg_put(cfqg_to_blkg(cfqg));
656 #define cfq_log_cfqq(cfqd, cfqq, fmt, args...) do { \
659 blkg_path(cfqg_to_blkg((cfqq)->cfqg), __pbuf, sizeof(__pbuf)); \
660 blk_add_trace_msg((cfqd)->queue, "cfq%d%c%c %s " fmt, (cfqq)->pid, \
661 cfq_cfqq_sync((cfqq)) ? 'S' : 'A', \
662 cfqq_type((cfqq)) == SYNC_NOIDLE_WORKLOAD ? 'N' : ' ',\
666 #define cfq_log_cfqg(cfqd, cfqg, fmt, args...) do { \
669 blkg_path(cfqg_to_blkg(cfqg), __pbuf, sizeof(__pbuf)); \
670 blk_add_trace_msg((cfqd)->queue, "%s " fmt, __pbuf, ##args); \
673 static inline void cfqg_stats_update_io_add(struct cfq_group *cfqg,
674 struct cfq_group *curr_cfqg, int rw)
676 blkg_rwstat_add(&cfqg->stats.queued, rw, 1);
677 cfqg_stats_end_empty_time(&cfqg->stats);
678 cfqg_stats_set_start_group_wait_time(cfqg, curr_cfqg);
681 static inline void cfqg_stats_update_timeslice_used(struct cfq_group *cfqg,
682 uint64_t time, unsigned long unaccounted_time)
684 blkg_stat_add(&cfqg->stats.time, time);
685 #ifdef CONFIG_DEBUG_BLK_CGROUP
686 blkg_stat_add(&cfqg->stats.unaccounted_time, unaccounted_time);
690 static inline void cfqg_stats_update_io_remove(struct cfq_group *cfqg, int rw)
692 blkg_rwstat_add(&cfqg->stats.queued, rw, -1);
695 static inline void cfqg_stats_update_io_merged(struct cfq_group *cfqg, int rw)
697 blkg_rwstat_add(&cfqg->stats.merged, rw, 1);
700 static inline void cfqg_stats_update_completion(struct cfq_group *cfqg,
701 uint64_t start_time, uint64_t io_start_time, int rw)
703 struct cfqg_stats *stats = &cfqg->stats;
704 unsigned long long now = sched_clock();
706 if (time_after64(now, io_start_time))
707 blkg_rwstat_add(&stats->service_time, rw, now - io_start_time);
708 if (time_after64(io_start_time, start_time))
709 blkg_rwstat_add(&stats->wait_time, rw,
710 io_start_time - start_time);
714 static void cfqg_stats_reset(struct cfqg_stats *stats)
716 /* queued stats shouldn't be cleared */
717 blkg_rwstat_reset(&stats->merged);
718 blkg_rwstat_reset(&stats->service_time);
719 blkg_rwstat_reset(&stats->wait_time);
720 blkg_stat_reset(&stats->time);
721 #ifdef CONFIG_DEBUG_BLK_CGROUP
722 blkg_stat_reset(&stats->unaccounted_time);
723 blkg_stat_reset(&stats->avg_queue_size_sum);
724 blkg_stat_reset(&stats->avg_queue_size_samples);
725 blkg_stat_reset(&stats->dequeue);
726 blkg_stat_reset(&stats->group_wait_time);
727 blkg_stat_reset(&stats->idle_time);
728 blkg_stat_reset(&stats->empty_time);
733 static void cfqg_stats_add_aux(struct cfqg_stats *to, struct cfqg_stats *from)
735 /* queued stats shouldn't be cleared */
736 blkg_rwstat_add_aux(&to->merged, &from->merged);
737 blkg_rwstat_add_aux(&to->service_time, &from->service_time);
738 blkg_rwstat_add_aux(&to->wait_time, &from->wait_time);
739 blkg_stat_add_aux(&from->time, &from->time);
740 #ifdef CONFIG_DEBUG_BLK_CGROUP
741 blkg_stat_add_aux(&to->unaccounted_time, &from->unaccounted_time);
742 blkg_stat_add_aux(&to->avg_queue_size_sum, &from->avg_queue_size_sum);
743 blkg_stat_add_aux(&to->avg_queue_size_samples, &from->avg_queue_size_samples);
744 blkg_stat_add_aux(&to->dequeue, &from->dequeue);
745 blkg_stat_add_aux(&to->group_wait_time, &from->group_wait_time);
746 blkg_stat_add_aux(&to->idle_time, &from->idle_time);
747 blkg_stat_add_aux(&to->empty_time, &from->empty_time);
752 * Transfer @cfqg's stats to its parent's aux counts so that the ancestors'
753 * recursive stats can still account for the amount used by this cfqg after
756 static void cfqg_stats_xfer_dead(struct cfq_group *cfqg)
758 struct cfq_group *parent = cfqg_parent(cfqg);
760 lockdep_assert_held(cfqg_to_blkg(cfqg)->q->queue_lock);
762 if (unlikely(!parent))
765 cfqg_stats_add_aux(&parent->stats, &cfqg->stats);
766 cfqg_stats_reset(&cfqg->stats);
769 #else /* CONFIG_CFQ_GROUP_IOSCHED */
771 static inline struct cfq_group *cfqg_parent(struct cfq_group *cfqg) { return NULL; }
772 static inline bool cfqg_is_descendant(struct cfq_group *cfqg,
773 struct cfq_group *ancestor)
777 static inline void cfqg_get(struct cfq_group *cfqg) { }
778 static inline void cfqg_put(struct cfq_group *cfqg) { }
780 #define cfq_log_cfqq(cfqd, cfqq, fmt, args...) \
781 blk_add_trace_msg((cfqd)->queue, "cfq%d%c%c " fmt, (cfqq)->pid, \
782 cfq_cfqq_sync((cfqq)) ? 'S' : 'A', \
783 cfqq_type((cfqq)) == SYNC_NOIDLE_WORKLOAD ? 'N' : ' ',\
785 #define cfq_log_cfqg(cfqd, cfqg, fmt, args...) do {} while (0)
787 static inline void cfqg_stats_update_io_add(struct cfq_group *cfqg,
788 struct cfq_group *curr_cfqg, int rw) { }
789 static inline void cfqg_stats_update_timeslice_used(struct cfq_group *cfqg,
790 uint64_t time, unsigned long unaccounted_time) { }
791 static inline void cfqg_stats_update_io_remove(struct cfq_group *cfqg, int rw) { }
792 static inline void cfqg_stats_update_io_merged(struct cfq_group *cfqg, int rw) { }
793 static inline void cfqg_stats_update_completion(struct cfq_group *cfqg,
794 uint64_t start_time, uint64_t io_start_time, int rw) { }
796 #endif /* CONFIG_CFQ_GROUP_IOSCHED */
798 #define cfq_log(cfqd, fmt, args...) \
799 blk_add_trace_msg((cfqd)->queue, "cfq " fmt, ##args)
801 /* Traverses through cfq group service trees */
802 #define for_each_cfqg_st(cfqg, i, j, st) \
803 for (i = 0; i <= IDLE_WORKLOAD; i++) \
804 for (j = 0, st = i < IDLE_WORKLOAD ? &cfqg->service_trees[i][j]\
805 : &cfqg->service_tree_idle; \
806 (i < IDLE_WORKLOAD && j <= SYNC_WORKLOAD) || \
807 (i == IDLE_WORKLOAD && j == 0); \
808 j++, st = i < IDLE_WORKLOAD ? \
809 &cfqg->service_trees[i][j]: NULL) \
811 static inline bool cfq_io_thinktime_big(struct cfq_data *cfqd,
812 struct cfq_ttime *ttime, bool group_idle)
815 if (!sample_valid(ttime->ttime_samples))
818 slice = cfqd->cfq_group_idle;
820 slice = cfqd->cfq_slice_idle;
821 return ttime->ttime_mean > slice;
824 static inline bool iops_mode(struct cfq_data *cfqd)
827 * If we are not idling on queues and it is a NCQ drive, parallel
828 * execution of requests is on and measuring time is not possible
829 * in most of the cases until and unless we drive shallower queue
830 * depths and that becomes a performance bottleneck. In such cases
831 * switch to start providing fairness in terms of number of IOs.
833 if (!cfqd->cfq_slice_idle && cfqd->hw_tag)
839 static inline enum wl_class_t cfqq_class(struct cfq_queue *cfqq)
841 if (cfq_class_idle(cfqq))
842 return IDLE_WORKLOAD;
843 if (cfq_class_rt(cfqq))
849 static enum wl_type_t cfqq_type(struct cfq_queue *cfqq)
851 if (!cfq_cfqq_sync(cfqq))
852 return ASYNC_WORKLOAD;
853 if (!cfq_cfqq_idle_window(cfqq))
854 return SYNC_NOIDLE_WORKLOAD;
855 return SYNC_WORKLOAD;
858 static inline int cfq_group_busy_queues_wl(enum wl_class_t wl_class,
859 struct cfq_data *cfqd,
860 struct cfq_group *cfqg)
862 if (wl_class == IDLE_WORKLOAD)
863 return cfqg->service_tree_idle.count;
865 return cfqg->service_trees[wl_class][ASYNC_WORKLOAD].count +
866 cfqg->service_trees[wl_class][SYNC_NOIDLE_WORKLOAD].count +
867 cfqg->service_trees[wl_class][SYNC_WORKLOAD].count;
870 static inline int cfqg_busy_async_queues(struct cfq_data *cfqd,
871 struct cfq_group *cfqg)
873 return cfqg->service_trees[RT_WORKLOAD][ASYNC_WORKLOAD].count +
874 cfqg->service_trees[BE_WORKLOAD][ASYNC_WORKLOAD].count;
877 static void cfq_dispatch_insert(struct request_queue *, struct request *);
878 static struct cfq_queue *cfq_get_queue(struct cfq_data *cfqd, bool is_sync,
879 struct cfq_io_cq *cic, struct bio *bio);
881 static inline struct cfq_io_cq *icq_to_cic(struct io_cq *icq)
883 /* cic->icq is the first member, %NULL will convert to %NULL */
884 return container_of(icq, struct cfq_io_cq, icq);
887 static inline struct cfq_io_cq *cfq_cic_lookup(struct cfq_data *cfqd,
888 struct io_context *ioc)
891 return icq_to_cic(ioc_lookup_icq(ioc, cfqd->queue));
895 static inline struct cfq_queue *cic_to_cfqq(struct cfq_io_cq *cic, bool is_sync)
897 return cic->cfqq[is_sync];
900 static inline void cic_set_cfqq(struct cfq_io_cq *cic, struct cfq_queue *cfqq,
903 cic->cfqq[is_sync] = cfqq;
906 static inline struct cfq_data *cic_to_cfqd(struct cfq_io_cq *cic)
908 return cic->icq.q->elevator->elevator_data;
912 * We regard a request as SYNC, if it's either a read or has the SYNC bit
913 * set (in which case it could also be direct WRITE).
915 static inline bool cfq_bio_sync(struct bio *bio)
917 return bio_data_dir(bio) == READ || (bio->bi_rw & REQ_SYNC);
921 * scheduler run of queue, if there are requests pending and no one in the
922 * driver that will restart queueing
924 static inline void cfq_schedule_dispatch(struct cfq_data *cfqd)
926 if (cfqd->busy_queues) {
927 cfq_log(cfqd, "schedule dispatch");
928 kblockd_schedule_work(&cfqd->unplug_work);
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.
937 static inline u64 cfq_prio_slice(struct cfq_data *cfqd, bool sync,
940 u64 base_slice = cfqd->cfq_slice[sync];
941 u64 slice = div_u64(base_slice, CFQ_SLICE_SCALE);
943 WARN_ON(prio >= IOPRIO_BE_NR);
945 return base_slice + (slice * (4 - prio));
949 cfq_prio_to_slice(struct cfq_data *cfqd, struct cfq_queue *cfqq)
951 return cfq_prio_slice(cfqd, cfq_cfqq_sync(cfqq), cfqq->ioprio);
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
959 * Scale @charge according to @vfraction, which is in range (0, 1]. The
960 * scaling is inversely proportional.
962 * scaled = charge / vfraction
964 * The result is also in fixed point w/ CFQ_SERVICE_SHIFT.
966 static inline u64 cfqg_scale_charge(u64 charge,
967 unsigned int vfraction)
969 u64 c = charge << CFQ_SERVICE_SHIFT; /* make it fixed point */
971 /* charge / vfraction */
972 c <<= CFQ_SERVICE_SHIFT;
973 return div_u64(c, vfraction);
976 static inline u64 max_vdisktime(u64 min_vdisktime, u64 vdisktime)
978 s64 delta = (s64)(vdisktime - min_vdisktime);
980 min_vdisktime = vdisktime;
982 return min_vdisktime;
985 static void update_min_vdisktime(struct cfq_rb_root *st)
987 struct cfq_group *cfqg;
990 cfqg = rb_entry_cfqg(st->left);
991 st->min_vdisktime = max_vdisktime(st->min_vdisktime,
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
1002 static inline unsigned cfq_group_get_avg_queues(struct cfq_data *cfqd,
1003 struct cfq_group *cfqg, bool rt)
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);
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) /
1014 return cfqg->busy_queues_avg[rt];
1018 cfq_group_slice(struct cfq_data *cfqd, struct cfq_group *cfqg)
1020 return cfqd->cfq_target_latency * cfqg->vfraction >> CFQ_SERVICE_SHIFT;
1024 cfq_scaled_cfqq_slice(struct cfq_data *cfqd, struct cfq_queue *cfqq)
1026 u64 slice = cfq_prio_to_slice(cfqd, cfqq);
1027 if (cfqd->cfq_latency) {
1029 * interested queues (we consider only the ones with the same
1030 * priority class in the cfq group)
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);
1038 if (expect_latency > group_slice) {
1039 u64 base_low_slice = 2 * cfqd->cfq_slice_idle;
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);
1056 cfq_set_prio_slice(struct cfq_data *cfqd, struct cfq_queue *cfqq)
1058 u64 slice = cfq_scaled_cfqq_slice(cfqd, cfqq);
1059 u64 now = ktime_get_ns();
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);
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.
1072 static inline bool cfq_slice_used(struct cfq_queue *cfqq)
1074 if (cfq_cfqq_slice_new(cfqq))
1076 if (ktime_get_ns() < cfqq->slice_end)
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.
1087 static struct request *
1088 cfq_choose_req(struct cfq_data *cfqd, struct request *rq1, struct request *rq2, sector_t last)
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? */
1096 if (rq1 == NULL || rq1 == rq2)
1101 if (rq_is_sync(rq1) != rq_is_sync(rq2))
1102 return rq_is_sync(rq1) ? rq1 : rq2;
1104 if ((rq1->cmd_flags ^ rq2->cmd_flags) & REQ_PRIO)
1105 return rq1->cmd_flags & REQ_PRIO ? rq1 : rq2;
1107 s1 = blk_rq_pos(rq1);
1108 s2 = blk_rq_pos(rq2);
1111 * by definition, 1KiB is 2 sectors
1113 back_max = cfqd->cfq_back_max * 2;
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.
1122 else if (s1 + back_max >= last)
1123 d1 = (last - s1) * cfqd->cfq_back_penalty;
1125 wrap |= CFQ_RQ1_WRAP;
1129 else if (s2 + back_max >= last)
1130 d2 = (last - s2) * cfqd->cfq_back_penalty;
1132 wrap |= CFQ_RQ2_WRAP;
1134 /* Found required data */
1137 * By doing switch() on the bit mask "wrap" we avoid having to
1138 * check two variables for all permutations: --> faster!
1141 case 0: /* common case for CFQ: rq1 and rq2 not wrapped */
1157 case (CFQ_RQ1_WRAP|CFQ_RQ2_WRAP): /* both rqs wrapped */
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.
1173 * The below is leftmost cache rbtree addon
1175 static struct cfq_queue *cfq_rb_first(struct cfq_rb_root *root)
1177 /* Service tree is empty */
1182 root->left = rb_first(&root->rb);
1185 return rb_entry(root->left, struct cfq_queue, rb_node);
1190 static struct cfq_group *cfq_rb_first_group(struct cfq_rb_root *root)
1193 root->left = rb_first(&root->rb);
1196 return rb_entry_cfqg(root->left);
1201 static void rb_erase_init(struct rb_node *n, struct rb_root *root)
1207 static void cfq_rb_erase(struct rb_node *n, struct cfq_rb_root *root)
1209 if (root->left == n)
1211 rb_erase_init(n, &root->rb);
1216 * would be nice to take fifo expire time into account as well
1218 static struct request *
1219 cfq_find_next_rq(struct cfq_data *cfqd, struct cfq_queue *cfqq,
1220 struct request *last)
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;
1226 BUG_ON(RB_EMPTY_NODE(&last->rb_node));
1229 prev = rb_entry_rq(rbprev);
1232 next = rb_entry_rq(rbnext);
1234 rbnext = rb_first(&cfqq->sort_list);
1235 if (rbnext && rbnext != &last->rb_node)
1236 next = rb_entry_rq(rbnext);
1239 return cfq_choose_req(cfqd, next, prev, blk_rq_pos(last));
1242 static u64 cfq_slice_offset(struct cfq_data *cfqd,
1243 struct cfq_queue *cfqq)
1246 * just an approximation, should be ok.
1248 return (cfqq->cfqg->nr_cfqq - 1) * (cfq_prio_slice(cfqd, 1, 0) -
1249 cfq_prio_slice(cfqd, cfq_cfqq_sync(cfqq), cfqq->ioprio));
1253 cfqg_key(struct cfq_rb_root *st, struct cfq_group *cfqg)
1255 return cfqg->vdisktime - st->min_vdisktime;
1259 __cfq_group_service_tree_add(struct cfq_rb_root *st, struct cfq_group *cfqg)
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);
1267 while (*node != NULL) {
1269 __cfqg = rb_entry_cfqg(parent);
1271 if (key < cfqg_key(st, __cfqg))
1272 node = &parent->rb_left;
1274 node = &parent->rb_right;
1280 st->left = &cfqg->rb_node;
1282 rb_link_node(&cfqg->rb_node, parent, node);
1283 rb_insert_color(&cfqg->rb_node, &st->rb);
1287 * This has to be called only on activation of cfqg
1290 cfq_update_group_weight(struct cfq_group *cfqg)
1292 if (cfqg->new_weight) {
1293 cfqg->weight = cfqg->new_weight;
1294 cfqg->new_weight = 0;
1299 cfq_update_group_leaf_weight(struct cfq_group *cfqg)
1301 BUG_ON(!RB_EMPTY_NODE(&cfqg->rb_node));
1303 if (cfqg->new_leaf_weight) {
1304 cfqg->leaf_weight = cfqg->new_leaf_weight;
1305 cfqg->new_leaf_weight = 0;
1310 cfq_group_service_tree_add(struct cfq_rb_root *st, struct cfq_group *cfqg)
1312 unsigned int vfr = 1 << CFQ_SERVICE_SHIFT; /* start with 1 */
1313 struct cfq_group *pos = cfqg;
1314 struct cfq_group *parent;
1317 /* add to the service tree */
1318 BUG_ON(!RB_EMPTY_NODE(&cfqg->rb_node));
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.
1325 cfq_update_group_leaf_weight(cfqg);
1326 __cfq_group_service_tree_add(st, cfqg);
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.
1334 * Start with the proportion tasks in this cfqg has against active
1335 * children cfqgs - its leaf_weight against children_weight.
1337 propagate = !pos->nr_active++;
1338 pos->children_weight += pos->leaf_weight;
1339 vfr = vfr * pos->leaf_weight / pos->children_weight;
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.
1347 while ((parent = cfqg_parent(pos))) {
1349 cfq_update_group_weight(pos);
1350 propagate = !parent->nr_active++;
1351 parent->children_weight += pos->weight;
1353 vfr = vfr * pos->weight / parent->children_weight;
1357 cfqg->vfraction = max_t(unsigned, vfr, 1);
1360 static inline u64 cfq_get_cfqg_vdisktime_delay(struct cfq_data *cfqd)
1362 if (!iops_mode(cfqd))
1363 return CFQ_SLICE_MODE_GROUP_DELAY;
1365 return CFQ_IOPS_MODE_GROUP_DELAY;
1369 cfq_group_notify_queue_add(struct cfq_data *cfqd, struct cfq_group *cfqg)
1371 struct cfq_rb_root *st = &cfqd->grp_service_tree;
1372 struct cfq_group *__cfqg;
1376 if (!RB_EMPTY_NODE(&cfqg->rb_node))
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.
1384 n = rb_last(&st->rb);
1386 __cfqg = rb_entry_cfqg(n);
1387 cfqg->vdisktime = __cfqg->vdisktime +
1388 cfq_get_cfqg_vdisktime_delay(cfqd);
1390 cfqg->vdisktime = st->min_vdisktime;
1391 cfq_group_service_tree_add(st, cfqg);
1395 cfq_group_service_tree_del(struct cfq_rb_root *st, struct cfq_group *cfqg)
1397 struct cfq_group *pos = cfqg;
1401 * Undo activation from cfq_group_service_tree_add(). Deactivate
1402 * @cfqg and propagate deactivation upwards.
1404 propagate = !--pos->nr_active;
1405 pos->children_weight -= pos->leaf_weight;
1408 struct cfq_group *parent = cfqg_parent(pos);
1410 /* @pos has 0 nr_active at this point */
1411 WARN_ON_ONCE(pos->children_weight);
1417 propagate = !--parent->nr_active;
1418 parent->children_weight -= pos->weight;
1422 /* remove from the service tree */
1423 if (!RB_EMPTY_NODE(&cfqg->rb_node))
1424 cfq_rb_erase(&cfqg->rb_node, st);
1428 cfq_group_notify_queue_del(struct cfq_data *cfqd, struct cfq_group *cfqg)
1430 struct cfq_rb_root *st = &cfqd->grp_service_tree;
1432 BUG_ON(cfqg->nr_cfqq < 1);
1435 /* If there are other cfq queues under this group, don't delete it */
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);
1445 static inline u64 cfq_cfqq_slice_usage(struct cfq_queue *cfqq,
1446 u64 *unaccounted_time)
1449 u64 now = ktime_get_ns();
1452 * Queue got expired before even a single request completed or
1453 * got expired immediately after first request completion.
1455 if (!cfqq->slice_start || cfqq->slice_start == now) {
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.
1462 slice_used = max_t(u64, (now - cfqq->dispatch_start),
1463 jiffies_to_nsecs(1));
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;
1470 if (cfqq->slice_start > cfqq->dispatch_start)
1471 *unaccounted_time += cfqq->slice_start -
1472 cfqq->dispatch_start;
1478 static void cfq_group_served(struct cfq_data *cfqd, struct cfq_group *cfqg,
1479 struct cfq_queue *cfqq)
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;
1486 u64 now = ktime_get_ns();
1488 BUG_ON(nr_sync < 0);
1489 used_sl = charge = cfq_cfqq_slice_usage(cfqq, &unaccounted_sl);
1491 if (iops_mode(cfqd))
1492 charge = cfqq->slice_dispatch;
1493 else if (!cfq_cfqq_sync(cfqq) && !nr_sync)
1494 charge = cfqq->allocated_slice;
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.
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);
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;
1513 cfqg->saved_wl_slice = 0;
1515 cfq_log_cfqg(cfqd, cfqg, "served: vt=%llu min_vt=%llu", cfqg->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);
1526 * cfq_init_cfqg_base - initialize base part of a cfq_group
1527 * @cfqg: cfq_group to initialize
1529 * Initialize the base part which is used whether %CONFIG_CFQ_GROUP_IOSCHED
1530 * is enabled or not.
1532 static void cfq_init_cfqg_base(struct cfq_group *cfqg)
1534 struct cfq_rb_root *st;
1537 for_each_cfqg_st(cfqg, i, j, st)
1539 RB_CLEAR_NODE(&cfqg->rb_node);
1541 cfqg->ttime.last_end_request = ktime_get_ns();
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);
1548 static void cfqg_stats_exit(struct cfqg_stats *stats)
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);
1566 static int cfqg_stats_init(struct cfqg_stats *stats, gfp_t gfp)
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))
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))
1587 cfqg_stats_exit(stats);
1591 static struct blkcg_policy_data *cfq_cpd_alloc(gfp_t gfp)
1593 struct cfq_group_data *cgd;
1595 cgd = kzalloc(sizeof(*cgd), gfp);
1601 static void cfq_cpd_init(struct blkcg_policy_data *cpd)
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;
1607 if (cpd_to_blkcg(cpd) == &blkcg_root)
1610 cgd->weight = weight;
1611 cgd->leaf_weight = weight;
1614 static void cfq_cpd_free(struct blkcg_policy_data *cpd)
1616 kfree(cpd_to_cfqgd(cpd));
1619 static void cfq_cpd_bind(struct blkcg_policy_data *cpd)
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;
1625 if (blkcg == &blkcg_root)
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));
1632 static struct blkg_policy_data *cfq_pd_alloc(gfp_t gfp, int node)
1634 struct cfq_group *cfqg;
1636 cfqg = kzalloc_node(sizeof(*cfqg), gfp, node);
1640 cfq_init_cfqg_base(cfqg);
1641 if (cfqg_stats_init(&cfqg->stats, gfp)) {
1649 static void cfq_pd_init(struct blkg_policy_data *pd)
1651 struct cfq_group *cfqg = pd_to_cfqg(pd);
1652 struct cfq_group_data *cgd = blkcg_to_cfqgd(pd->blkg->blkcg);
1654 cfqg->weight = cgd->weight;
1655 cfqg->leaf_weight = cgd->leaf_weight;
1658 static void cfq_pd_offline(struct blkg_policy_data *pd)
1660 struct cfq_group *cfqg = pd_to_cfqg(pd);
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]);
1670 if (cfqg->async_idle_cfqq)
1671 cfq_put_queue(cfqg->async_idle_cfqq);
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...
1679 cfqg_stats_xfer_dead(cfqg);
1682 static void cfq_pd_free(struct blkg_policy_data *pd)
1684 struct cfq_group *cfqg = pd_to_cfqg(pd);
1686 cfqg_stats_exit(&cfqg->stats);
1690 static void cfq_pd_reset_stats(struct blkg_policy_data *pd)
1692 struct cfq_group *cfqg = pd_to_cfqg(pd);
1694 cfqg_stats_reset(&cfqg->stats);
1697 static struct cfq_group *cfq_lookup_cfqg(struct cfq_data *cfqd,
1698 struct blkcg *blkcg)
1700 struct blkcg_gq *blkg;
1702 blkg = blkg_lookup(blkcg, cfqd->queue);
1704 return blkg_to_cfqg(blkg);
1708 static void cfq_link_cfqq_cfqg(struct cfq_queue *cfqq, struct cfq_group *cfqg)
1711 /* cfqq reference on cfqg */
1715 static u64 cfqg_prfill_weight_device(struct seq_file *sf,
1716 struct blkg_policy_data *pd, int off)
1718 struct cfq_group *cfqg = pd_to_cfqg(pd);
1720 if (!cfqg->dev_weight)
1722 return __blkg_prfill_u64(sf, pd, cfqg->dev_weight);
1725 static int cfqg_print_weight_device(struct seq_file *sf, void *v)
1727 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1728 cfqg_prfill_weight_device, &blkcg_policy_cfq,
1733 static u64 cfqg_prfill_leaf_weight_device(struct seq_file *sf,
1734 struct blkg_policy_data *pd, int off)
1736 struct cfq_group *cfqg = pd_to_cfqg(pd);
1738 if (!cfqg->dev_leaf_weight)
1740 return __blkg_prfill_u64(sf, pd, cfqg->dev_leaf_weight);
1743 static int cfqg_print_leaf_weight_device(struct seq_file *sf, void *v)
1745 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1746 cfqg_prfill_leaf_weight_device, &blkcg_policy_cfq,
1751 static int cfq_print_weight(struct seq_file *sf, void *v)
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;
1760 seq_printf(sf, "%u\n", val);
1764 static int cfq_print_leaf_weight(struct seq_file *sf, void *v)
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;
1771 val = cgd->leaf_weight;
1773 seq_printf(sf, "%u\n", val);
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)
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;
1790 ret = blkg_conf_prep(blkcg, &blkcg_policy_cfq, buf, &ctx);
1794 if (sscanf(ctx.body, "%llu", &v) == 1) {
1795 /* require "default" on dfl */
1799 } else if (!strcmp(strim(ctx.body), "default")) {
1806 cfqg = blkg_to_cfqg(ctx.blkg);
1807 cfqgd = blkcg_to_cfqgd(blkcg);
1810 if (!v || (v >= min && v <= max)) {
1811 if (!is_leaf_weight) {
1812 cfqg->dev_weight = v;
1813 cfqg->new_weight = v ?: cfqgd->weight;
1815 cfqg->dev_leaf_weight = v;
1816 cfqg->new_leaf_weight = v ?: cfqgd->leaf_weight;
1821 blkg_conf_finish(&ctx);
1822 return ret ?: nbytes;
1825 static ssize_t cfqg_set_weight_device(struct kernfs_open_file *of,
1826 char *buf, size_t nbytes, loff_t off)
1828 return __cfqg_set_weight_device(of, buf, nbytes, off, false, false);
1831 static ssize_t cfqg_set_leaf_weight_device(struct kernfs_open_file *of,
1832 char *buf, size_t nbytes, loff_t off)
1834 return __cfqg_set_weight_device(of, buf, nbytes, off, false, true);
1837 static int __cfq_set_weight(struct cgroup_subsys_state *css, u64 val,
1838 bool on_dfl, bool reset_dev, bool is_leaf_weight)
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;
1847 if (val < min || val > max)
1850 spin_lock_irq(&blkcg->lock);
1851 cfqgd = blkcg_to_cfqgd(blkcg);
1857 if (!is_leaf_weight)
1858 cfqgd->weight = val;
1860 cfqgd->leaf_weight = val;
1862 hlist_for_each_entry(blkg, &blkcg->blkg_list, blkcg_node) {
1863 struct cfq_group *cfqg = blkg_to_cfqg(blkg);
1868 if (!is_leaf_weight) {
1870 cfqg->dev_weight = 0;
1871 if (!cfqg->dev_weight)
1872 cfqg->new_weight = cfqgd->weight;
1875 cfqg->dev_leaf_weight = 0;
1876 if (!cfqg->dev_leaf_weight)
1877 cfqg->new_leaf_weight = cfqgd->leaf_weight;
1882 spin_unlock_irq(&blkcg->lock);
1886 static int cfq_set_weight(struct cgroup_subsys_state *css, struct cftype *cft,
1889 return __cfq_set_weight(css, val, false, false, false);
1892 static int cfq_set_leaf_weight(struct cgroup_subsys_state *css,
1893 struct cftype *cft, u64 val)
1895 return __cfq_set_weight(css, val, false, false, true);
1898 static int cfqg_print_stat(struct seq_file *sf, void *v)
1900 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), blkg_prfill_stat,
1901 &blkcg_policy_cfq, seq_cft(sf)->private, false);
1905 static int cfqg_print_rwstat(struct seq_file *sf, void *v)
1907 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), blkg_prfill_rwstat,
1908 &blkcg_policy_cfq, seq_cft(sf)->private, true);
1912 static u64 cfqg_prfill_stat_recursive(struct seq_file *sf,
1913 struct blkg_policy_data *pd, int off)
1915 u64 sum = blkg_stat_recursive_sum(pd_to_blkg(pd),
1916 &blkcg_policy_cfq, off);
1917 return __blkg_prfill_u64(sf, pd, sum);
1920 static u64 cfqg_prfill_rwstat_recursive(struct seq_file *sf,
1921 struct blkg_policy_data *pd, int off)
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);
1928 static int cfqg_print_stat_recursive(struct seq_file *sf, void *v)
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);
1936 static int cfqg_print_rwstat_recursive(struct seq_file *sf, void *v)
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);
1944 static u64 cfqg_prfill_sectors(struct seq_file *sf, struct blkg_policy_data *pd,
1947 u64 sum = blkg_rwstat_total(&pd->blkg->stat_bytes);
1949 return __blkg_prfill_u64(sf, pd, sum >> 9);
1952 static int cfqg_print_stat_sectors(struct seq_file *sf, void *v)
1954 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1955 cfqg_prfill_sectors, &blkcg_policy_cfq, 0, false);
1959 static u64 cfqg_prfill_sectors_recursive(struct seq_file *sf,
1960 struct blkg_policy_data *pd, int off)
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]);
1967 return __blkg_prfill_u64(sf, pd, sum >> 9);
1970 static int cfqg_print_stat_sectors_recursive(struct seq_file *sf, void *v)
1972 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1973 cfqg_prfill_sectors_recursive, &blkcg_policy_cfq, 0,
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)
1982 struct cfq_group *cfqg = pd_to_cfqg(pd);
1983 u64 samples = blkg_stat_read(&cfqg->stats.avg_queue_size_samples);
1987 v = blkg_stat_read(&cfqg->stats.avg_queue_size_sum);
1988 v = div64_u64(v, samples);
1990 __blkg_prfill_u64(sf, pd, v);
1994 /* print avg_queue_size */
1995 static int cfqg_print_avg_queue_size(struct seq_file *sf, void *v)
1997 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1998 cfqg_prfill_avg_queue_size, &blkcg_policy_cfq,
2002 #endif /* CONFIG_DEBUG_BLK_CGROUP */
2004 static struct cftype cfq_blkcg_legacy_files[] = {
2005 /* on root, weight is mapped to leaf_weight */
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,
2014 .flags = CFTYPE_ONLY_ON_ROOT,
2015 .seq_show = cfq_print_leaf_weight,
2016 .write_u64 = cfq_set_leaf_weight,
2019 /* no such mapping necessary for !roots */
2021 .name = "weight_device",
2022 .flags = CFTYPE_NOT_ON_ROOT,
2023 .seq_show = cfqg_print_weight_device,
2024 .write = cfqg_set_weight_device,
2028 .flags = CFTYPE_NOT_ON_ROOT,
2029 .seq_show = cfq_print_weight,
2030 .write_u64 = cfq_set_weight,
2034 .name = "leaf_weight_device",
2035 .seq_show = cfqg_print_leaf_weight_device,
2036 .write = cfqg_set_leaf_weight_device,
2039 .name = "leaf_weight",
2040 .seq_show = cfq_print_leaf_weight,
2041 .write_u64 = cfq_set_leaf_weight,
2044 /* statistics, covers only the tasks in the cfqg */
2047 .private = offsetof(struct cfq_group, stats.time),
2048 .seq_show = cfqg_print_stat,
2052 .seq_show = cfqg_print_stat_sectors,
2055 .name = "io_service_bytes",
2056 .private = (unsigned long)&blkcg_policy_cfq,
2057 .seq_show = blkg_print_stat_bytes,
2060 .name = "io_serviced",
2061 .private = (unsigned long)&blkcg_policy_cfq,
2062 .seq_show = blkg_print_stat_ios,
2065 .name = "io_service_time",
2066 .private = offsetof(struct cfq_group, stats.service_time),
2067 .seq_show = cfqg_print_rwstat,
2070 .name = "io_wait_time",
2071 .private = offsetof(struct cfq_group, stats.wait_time),
2072 .seq_show = cfqg_print_rwstat,
2075 .name = "io_merged",
2076 .private = offsetof(struct cfq_group, stats.merged),
2077 .seq_show = cfqg_print_rwstat,
2080 .name = "io_queued",
2081 .private = offsetof(struct cfq_group, stats.queued),
2082 .seq_show = cfqg_print_rwstat,
2085 /* the same statictics which cover the cfqg and its descendants */
2087 .name = "time_recursive",
2088 .private = offsetof(struct cfq_group, stats.time),
2089 .seq_show = cfqg_print_stat_recursive,
2092 .name = "sectors_recursive",
2093 .seq_show = cfqg_print_stat_sectors_recursive,
2096 .name = "io_service_bytes_recursive",
2097 .private = (unsigned long)&blkcg_policy_cfq,
2098 .seq_show = blkg_print_stat_bytes_recursive,
2101 .name = "io_serviced_recursive",
2102 .private = (unsigned long)&blkcg_policy_cfq,
2103 .seq_show = blkg_print_stat_ios_recursive,
2106 .name = "io_service_time_recursive",
2107 .private = offsetof(struct cfq_group, stats.service_time),
2108 .seq_show = cfqg_print_rwstat_recursive,
2111 .name = "io_wait_time_recursive",
2112 .private = offsetof(struct cfq_group, stats.wait_time),
2113 .seq_show = cfqg_print_rwstat_recursive,
2116 .name = "io_merged_recursive",
2117 .private = offsetof(struct cfq_group, stats.merged),
2118 .seq_show = cfqg_print_rwstat_recursive,
2121 .name = "io_queued_recursive",
2122 .private = offsetof(struct cfq_group, stats.queued),
2123 .seq_show = cfqg_print_rwstat_recursive,
2125 #ifdef CONFIG_DEBUG_BLK_CGROUP
2127 .name = "avg_queue_size",
2128 .seq_show = cfqg_print_avg_queue_size,
2131 .name = "group_wait_time",
2132 .private = offsetof(struct cfq_group, stats.group_wait_time),
2133 .seq_show = cfqg_print_stat,
2136 .name = "idle_time",
2137 .private = offsetof(struct cfq_group, stats.idle_time),
2138 .seq_show = cfqg_print_stat,
2141 .name = "empty_time",
2142 .private = offsetof(struct cfq_group, stats.empty_time),
2143 .seq_show = cfqg_print_stat,
2147 .private = offsetof(struct cfq_group, stats.dequeue),
2148 .seq_show = cfqg_print_stat,
2151 .name = "unaccounted_time",
2152 .private = offsetof(struct cfq_group, stats.unaccounted_time),
2153 .seq_show = cfqg_print_stat,
2155 #endif /* CONFIG_DEBUG_BLK_CGROUP */
2159 static int cfq_print_weight_on_dfl(struct seq_file *sf, void *v)
2161 struct blkcg *blkcg = css_to_blkcg(seq_css(sf));
2162 struct cfq_group_data *cgd = blkcg_to_cfqgd(blkcg);
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);
2170 static ssize_t cfq_set_weight_on_dfl(struct kernfs_open_file *of,
2171 char *buf, size_t nbytes, loff_t off)
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;
2186 /* "MAJ:MIN WEIGHT" */
2187 return __cfqg_set_weight_device(of, buf, nbytes, off, true, false);
2190 static struct cftype cfq_blkcg_files[] = {
2193 .flags = CFTYPE_NOT_ON_ROOT,
2194 .seq_show = cfq_print_weight_on_dfl,
2195 .write = cfq_set_weight_on_dfl,
2200 #else /* GROUP_IOSCHED */
2201 static struct cfq_group *cfq_lookup_cfqg(struct cfq_data *cfqd,
2202 struct blkcg *blkcg)
2204 return cfqd->root_group;
2208 cfq_link_cfqq_cfqg(struct cfq_queue *cfqq, struct cfq_group *cfqg) {
2212 #endif /* GROUP_IOSCHED */
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.
2219 static void cfq_service_tree_add(struct cfq_data *cfqd, struct cfq_queue *cfqq,
2222 struct rb_node **p, *parent;
2223 struct cfq_queue *__cfqq;
2225 struct cfq_rb_root *st;
2228 u64 now = ktime_get_ns();
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;
2239 } else if (!add_front) {
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.
2246 rb_key = cfq_slice_offset(cfqd, cfqq) + now;
2247 rb_key -= cfqq->slice_resid;
2248 cfqq->slice_resid = 0;
2250 rb_key = -NSEC_PER_SEC;
2251 __cfqq = cfq_rb_first(st);
2252 rb_key += __cfqq ? __cfqq->rb_key : now;
2255 if (!RB_EMPTY_NODE(&cfqq->rb_node)) {
2258 * same position, nothing more to do
2260 if (rb_key == cfqq->rb_key && cfqq->service_tree == st)
2263 cfq_rb_erase(&cfqq->rb_node, cfqq->service_tree);
2264 cfqq->service_tree = NULL;
2269 cfqq->service_tree = st;
2270 p = &st->rb.rb_node;
2273 __cfqq = rb_entry(parent, struct cfq_queue, rb_node);
2276 * sort by key, that represents service time.
2278 if (rb_key < __cfqq->rb_key)
2279 p = &parent->rb_left;
2281 p = &parent->rb_right;
2287 st->left = &cfqq->rb_node;
2289 cfqq->rb_key = rb_key;
2290 rb_link_node(&cfqq->rb_node, parent, p);
2291 rb_insert_color(&cfqq->rb_node, &st->rb);
2293 if (add_front || !new_cfqq)
2295 cfq_group_notify_queue_add(cfqd, cfqq->cfqg);
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)
2303 struct rb_node **p, *parent;
2304 struct cfq_queue *cfqq = NULL;
2312 cfqq = rb_entry(parent, struct cfq_queue, p_node);
2315 * Sort strictly based on sector. Smallest to the left,
2316 * largest to the right.
2318 if (sector > blk_rq_pos(cfqq->next_rq))
2319 n = &(*p)->rb_right;
2320 else if (sector < blk_rq_pos(cfqq->next_rq))
2328 *ret_parent = parent;
2334 static void cfq_prio_tree_add(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2336 struct rb_node **p, *parent;
2337 struct cfq_queue *__cfqq;
2340 rb_erase(&cfqq->p_node, cfqq->p_root);
2341 cfqq->p_root = NULL;
2344 if (cfq_class_idle(cfqq))
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);
2353 rb_link_node(&cfqq->p_node, parent, p);
2354 rb_insert_color(&cfqq->p_node, cfqq->p_root);
2356 cfqq->p_root = NULL;
2360 * Update cfqq's position in the service tree.
2362 static void cfq_resort_rr_list(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2365 * Resorting requires the cfqq to be on the RR list already.
2367 if (cfq_cfqq_on_rr(cfqq)) {
2368 cfq_service_tree_add(cfqd, cfqq, 0);
2369 cfq_prio_tree_add(cfqd, cfqq);
2374 * add to busy list of queues for service, trying to be fair in ordering
2375 * the pending list according to last request service
2377 static void cfq_add_cfqq_rr(struct cfq_data *cfqd, struct cfq_queue *cfqq)
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++;
2386 cfq_resort_rr_list(cfqd, cfqq);
2390 * Called when the cfqq no longer has requests pending, remove it from
2393 static void cfq_del_cfqq_rr(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2395 cfq_log_cfqq(cfqd, cfqq, "del_from_rr");
2396 BUG_ON(!cfq_cfqq_on_rr(cfqq));
2397 cfq_clear_cfqq_on_rr(cfqq);
2399 if (!RB_EMPTY_NODE(&cfqq->rb_node)) {
2400 cfq_rb_erase(&cfqq->rb_node, cfqq->service_tree);
2401 cfqq->service_tree = NULL;
2404 rb_erase(&cfqq->p_node, cfqq->p_root);
2405 cfqq->p_root = NULL;
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--;
2416 * rb tree support functions
2418 static void cfq_del_rq_rb(struct request *rq)
2420 struct cfq_queue *cfqq = RQ_CFQQ(rq);
2421 const int sync = rq_is_sync(rq);
2423 BUG_ON(!cfqq->queued[sync]);
2424 cfqq->queued[sync]--;
2426 elv_rb_del(&cfqq->sort_list, rq);
2428 if (cfq_cfqq_on_rr(cfqq) && RB_EMPTY_ROOT(&cfqq->sort_list)) {
2430 * Queue will be deleted from service tree when we actually
2431 * expire it later. Right now just remove it from prio tree
2435 rb_erase(&cfqq->p_node, cfqq->p_root);
2436 cfqq->p_root = NULL;
2441 static void cfq_add_rq_rb(struct request *rq)
2443 struct cfq_queue *cfqq = RQ_CFQQ(rq);
2444 struct cfq_data *cfqd = cfqq->cfqd;
2445 struct request *prev;
2447 cfqq->queued[rq_is_sync(rq)]++;
2449 elv_rb_add(&cfqq->sort_list, rq);
2451 if (!cfq_cfqq_on_rr(cfqq))
2452 cfq_add_cfqq_rr(cfqd, cfqq);
2455 * check if this request is a better next-serve candidate
2457 prev = cfqq->next_rq;
2458 cfqq->next_rq = cfq_choose_req(cfqd, cfqq->next_rq, rq, cfqd->last_position);
2461 * adjust priority tree position, if ->next_rq changes
2463 if (prev != cfqq->next_rq)
2464 cfq_prio_tree_add(cfqd, cfqq);
2466 BUG_ON(!cfqq->next_rq);
2469 static void cfq_reposition_rq_rb(struct cfq_queue *cfqq, struct request *rq)
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);
2475 cfqg_stats_update_io_add(RQ_CFQG(rq), cfqq->cfqd->serving_group,
2479 static struct request *
2480 cfq_find_rq_fmerge(struct cfq_data *cfqd, struct bio *bio)
2482 struct task_struct *tsk = current;
2483 struct cfq_io_cq *cic;
2484 struct cfq_queue *cfqq;
2486 cic = cfq_cic_lookup(cfqd, tsk->io_context);
2490 cfqq = cic_to_cfqq(cic, cfq_bio_sync(bio));
2492 return elv_rb_find(&cfqq->sort_list, bio_end_sector(bio));
2497 static void cfq_activate_request(struct request_queue *q, struct request *rq)
2499 struct cfq_data *cfqd = q->elevator->elevator_data;
2501 cfqd->rq_in_driver++;
2502 cfq_log_cfqq(cfqd, RQ_CFQQ(rq), "activate rq, drv=%d",
2503 cfqd->rq_in_driver);
2505 cfqd->last_position = blk_rq_pos(rq) + blk_rq_sectors(rq);
2508 static void cfq_deactivate_request(struct request_queue *q, struct request *rq)
2510 struct cfq_data *cfqd = q->elevator->elevator_data;
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);
2518 static void cfq_remove_request(struct request *rq)
2520 struct cfq_queue *cfqq = RQ_CFQQ(rq);
2522 if (cfqq->next_rq == rq)
2523 cfqq->next_rq = cfq_find_next_rq(cfqq->cfqd, cfqq, rq);
2525 list_del_init(&rq->queuelist);
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--;
2536 static int cfq_merge(struct request_queue *q, struct request **req,
2539 struct cfq_data *cfqd = q->elevator->elevator_data;
2540 struct request *__rq;
2542 __rq = cfq_find_rq_fmerge(cfqd, bio);
2543 if (__rq && elv_rq_merge_ok(__rq, bio)) {
2545 return ELEVATOR_FRONT_MERGE;
2548 return ELEVATOR_NO_MERGE;
2551 static void cfq_merged_request(struct request_queue *q, struct request *req,
2554 if (type == ELEVATOR_FRONT_MERGE) {
2555 struct cfq_queue *cfqq = RQ_CFQQ(req);
2557 cfq_reposition_rq_rb(cfqq, req);
2561 static void cfq_bio_merged(struct request_queue *q, struct request *req,
2564 cfqg_stats_update_io_merged(RQ_CFQG(req), bio->bi_rw);
2568 cfq_merged_requests(struct request_queue *q, struct request *rq,
2569 struct request *next)
2571 struct cfq_queue *cfqq = RQ_CFQQ(rq);
2572 struct cfq_data *cfqd = q->elevator->elevator_data;
2575 * reposition in fifo if next is older than rq
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;
2584 if (cfqq->next_rq == next)
2586 cfq_remove_request(next);
2587 cfqg_stats_update_io_merged(RQ_CFQG(rq), next->cmd_flags);
2589 cfqq = RQ_CFQQ(next);
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
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);
2600 static int cfq_allow_merge(struct request_queue *q, struct request *rq,
2603 struct cfq_data *cfqd = q->elevator->elevator_data;
2604 struct cfq_io_cq *cic;
2605 struct cfq_queue *cfqq;
2608 * Disallow merge of a sync bio into an async request.
2610 if (cfq_bio_sync(bio) && !rq_is_sync(rq))
2614 * Lookup the cfqq that this bio will be queued with and allow
2615 * merge only if rq is queued there.
2617 cic = cfq_cic_lookup(cfqd, current->io_context);
2621 cfqq = cic_to_cfqq(cic, cfq_bio_sync(bio));
2622 return cfqq == RQ_CFQQ(rq);
2625 static inline void cfq_del_timer(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2627 hrtimer_try_to_cancel(&cfqd->idle_slice_timer);
2628 cfqg_stats_update_idle_time(cfqq->cfqg);
2631 static void __cfq_set_active_queue(struct cfq_data *cfqd,
2632 struct cfq_queue *cfqq)
2635 cfq_log_cfqq(cfqd, cfqq, "set_active wl_class:%d wl_type:%d",
2636 cfqd->serving_wl_class, cfqd->serving_wl_type);
2637 cfqg_stats_update_avg_queue_size(cfqq->cfqg);
2638 cfqq->slice_start = 0;
2639 cfqq->dispatch_start = ktime_get_ns();
2640 cfqq->allocated_slice = 0;
2641 cfqq->slice_end = 0;
2642 cfqq->slice_dispatch = 0;
2643 cfqq->nr_sectors = 0;
2645 cfq_clear_cfqq_wait_request(cfqq);
2646 cfq_clear_cfqq_must_dispatch(cfqq);
2647 cfq_clear_cfqq_must_alloc_slice(cfqq);
2648 cfq_clear_cfqq_fifo_expire(cfqq);
2649 cfq_mark_cfqq_slice_new(cfqq);
2651 cfq_del_timer(cfqd, cfqq);
2654 cfqd->active_queue = cfqq;
2658 * current cfqq expired its slice (or was too idle), select new one
2661 __cfq_slice_expired(struct cfq_data *cfqd, struct cfq_queue *cfqq,
2664 cfq_log_cfqq(cfqd, cfqq, "slice expired t=%d", timed_out);
2666 if (cfq_cfqq_wait_request(cfqq))
2667 cfq_del_timer(cfqd, cfqq);
2669 cfq_clear_cfqq_wait_request(cfqq);
2670 cfq_clear_cfqq_wait_busy(cfqq);
2673 * If this cfqq is shared between multiple processes, check to
2674 * make sure that those processes are still issuing I/Os within
2675 * the mean seek distance. If not, it may be time to break the
2676 * queues apart again.
2678 if (cfq_cfqq_coop(cfqq) && CFQQ_SEEKY(cfqq))
2679 cfq_mark_cfqq_split_coop(cfqq);
2682 * store what was left of this slice, if the queue idled/timed out
2685 if (cfq_cfqq_slice_new(cfqq))
2686 cfqq->slice_resid = cfq_scaled_cfqq_slice(cfqd, cfqq);
2688 cfqq->slice_resid = cfqq->slice_end - ktime_get_ns();
2689 cfq_log_cfqq(cfqd, cfqq, "resid=%lld", cfqq->slice_resid);
2692 cfq_group_served(cfqd, cfqq->cfqg, cfqq);
2694 if (cfq_cfqq_on_rr(cfqq) && RB_EMPTY_ROOT(&cfqq->sort_list))
2695 cfq_del_cfqq_rr(cfqd, cfqq);
2697 cfq_resort_rr_list(cfqd, cfqq);
2699 if (cfqq == cfqd->active_queue)
2700 cfqd->active_queue = NULL;
2702 if (cfqd->active_cic) {
2703 put_io_context(cfqd->active_cic->icq.ioc);
2704 cfqd->active_cic = NULL;
2708 static inline void cfq_slice_expired(struct cfq_data *cfqd, bool timed_out)
2710 struct cfq_queue *cfqq = cfqd->active_queue;
2713 __cfq_slice_expired(cfqd, cfqq, timed_out);
2717 * Get next queue for service. Unless we have a queue preemption,
2718 * we'll simply select the first cfqq in the service tree.
2720 static struct cfq_queue *cfq_get_next_queue(struct cfq_data *cfqd)
2722 struct cfq_rb_root *st = st_for(cfqd->serving_group,
2723 cfqd->serving_wl_class, cfqd->serving_wl_type);
2725 if (!cfqd->rq_queued)
2728 /* There is nothing to dispatch */
2731 if (RB_EMPTY_ROOT(&st->rb))
2733 return cfq_rb_first(st);
2736 static struct cfq_queue *cfq_get_next_queue_forced(struct cfq_data *cfqd)
2738 struct cfq_group *cfqg;
2739 struct cfq_queue *cfqq;
2741 struct cfq_rb_root *st;
2743 if (!cfqd->rq_queued)
2746 cfqg = cfq_get_next_cfqg(cfqd);
2750 for_each_cfqg_st(cfqg, i, j, st) {
2751 cfqq = cfq_rb_first(st);
2759 * Get and set a new active queue for service.
2761 static struct cfq_queue *cfq_set_active_queue(struct cfq_data *cfqd,
2762 struct cfq_queue *cfqq)
2765 cfqq = cfq_get_next_queue(cfqd);
2767 __cfq_set_active_queue(cfqd, cfqq);
2771 static inline sector_t cfq_dist_from_last(struct cfq_data *cfqd,
2774 if (blk_rq_pos(rq) >= cfqd->last_position)
2775 return blk_rq_pos(rq) - cfqd->last_position;
2777 return cfqd->last_position - blk_rq_pos(rq);
2780 static inline int cfq_rq_close(struct cfq_data *cfqd, struct cfq_queue *cfqq,
2783 return cfq_dist_from_last(cfqd, rq) <= CFQQ_CLOSE_THR;
2786 static struct cfq_queue *cfqq_close(struct cfq_data *cfqd,
2787 struct cfq_queue *cur_cfqq)
2789 struct rb_root *root = &cfqd->prio_trees[cur_cfqq->org_ioprio];
2790 struct rb_node *parent, *node;
2791 struct cfq_queue *__cfqq;
2792 sector_t sector = cfqd->last_position;
2794 if (RB_EMPTY_ROOT(root))
2798 * First, if we find a request starting at the end of the last
2799 * request, choose it.
2801 __cfqq = cfq_prio_tree_lookup(cfqd, root, sector, &parent, NULL);
2806 * If the exact sector wasn't found, the parent of the NULL leaf
2807 * will contain the closest sector.
2809 __cfqq = rb_entry(parent, struct cfq_queue, p_node);
2810 if (cfq_rq_close(cfqd, cur_cfqq, __cfqq->next_rq))
2813 if (blk_rq_pos(__cfqq->next_rq) < sector)
2814 node = rb_next(&__cfqq->p_node);
2816 node = rb_prev(&__cfqq->p_node);
2820 __cfqq = rb_entry(node, struct cfq_queue, p_node);
2821 if (cfq_rq_close(cfqd, cur_cfqq, __cfqq->next_rq))
2829 * cur_cfqq - passed in so that we don't decide that the current queue is
2830 * closely cooperating with itself.
2832 * So, basically we're assuming that that cur_cfqq has dispatched at least
2833 * one request, and that cfqd->last_position reflects a position on the disk
2834 * associated with the I/O issued by cur_cfqq. I'm not sure this is a valid
2837 static struct cfq_queue *cfq_close_cooperator(struct cfq_data *cfqd,
2838 struct cfq_queue *cur_cfqq)
2840 struct cfq_queue *cfqq;
2842 if (cfq_class_idle(cur_cfqq))
2844 if (!cfq_cfqq_sync(cur_cfqq))
2846 if (CFQQ_SEEKY(cur_cfqq))
2850 * Don't search priority tree if it's the only queue in the group.
2852 if (cur_cfqq->cfqg->nr_cfqq == 1)
2856 * We should notice if some of the queues are cooperating, eg
2857 * working closely on the same area of the disk. In that case,
2858 * we can group them together and don't waste time idling.
2860 cfqq = cfqq_close(cfqd, cur_cfqq);
2864 /* If new queue belongs to different cfq_group, don't choose it */
2865 if (cur_cfqq->cfqg != cfqq->cfqg)
2869 * It only makes sense to merge sync queues.
2871 if (!cfq_cfqq_sync(cfqq))
2873 if (CFQQ_SEEKY(cfqq))
2877 * Do not merge queues of different priority classes
2879 if (cfq_class_rt(cfqq) != cfq_class_rt(cur_cfqq))
2886 * Determine whether we should enforce idle window for this queue.
2889 static bool cfq_should_idle(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2891 enum wl_class_t wl_class = cfqq_class(cfqq);
2892 struct cfq_rb_root *st = cfqq->service_tree;
2897 if (!cfqd->cfq_slice_idle)
2900 /* We never do for idle class queues. */
2901 if (wl_class == IDLE_WORKLOAD)
2904 /* We do for queues that were marked with idle window flag. */
2905 if (cfq_cfqq_idle_window(cfqq) &&
2906 !(blk_queue_nonrot(cfqd->queue) && cfqd->hw_tag))
2910 * Otherwise, we do only if they are the last ones
2911 * in their service tree.
2913 if (st->count == 1 && cfq_cfqq_sync(cfqq) &&
2914 !cfq_io_thinktime_big(cfqd, &st->ttime, false))
2916 cfq_log_cfqq(cfqd, cfqq, "Not idling. st->count:%d", st->count);
2920 static void cfq_arm_slice_timer(struct cfq_data *cfqd)
2922 struct cfq_queue *cfqq = cfqd->active_queue;
2923 struct cfq_io_cq *cic;
2924 u64 sl, group_idle = 0;
2925 u64 now = ktime_get_ns();
2928 * SSD device without seek penalty, disable idling. But only do so
2929 * for devices that support queuing (and when group idle is 0),
2930 * otherwise we still have a problem with sync vs async workloads.
2932 if (blk_queue_nonrot(cfqd->queue) && cfqd->hw_tag &&
2933 !cfqd->cfq_group_idle)
2936 WARN_ON(!RB_EMPTY_ROOT(&cfqq->sort_list));
2937 WARN_ON(cfq_cfqq_slice_new(cfqq));
2940 * idle is disabled, either manually or by past process history
2942 if (!cfq_should_idle(cfqd, cfqq)) {
2943 /* no queue idling. Check for group idling */
2944 if (cfqd->cfq_group_idle)
2945 group_idle = cfqd->cfq_group_idle;
2951 * still active requests from this queue, don't idle
2953 if (cfqq->dispatched)
2957 * task has exited, don't wait
2959 cic = cfqd->active_cic;
2960 if (!cic || !atomic_read(&cic->icq.ioc->active_ref))
2964 * If our average think time is larger than the remaining time
2965 * slice, then don't idle. This avoids overrunning the allotted
2968 if (sample_valid(cic->ttime.ttime_samples) &&
2969 (cfqq->slice_end - now < cic->ttime.ttime_mean)) {
2970 cfq_log_cfqq(cfqd, cfqq, "Not idling. think_time:%llu",
2971 cic->ttime.ttime_mean);
2975 /* There are other queues in the group, don't do group idle */
2976 if (group_idle && cfqq->cfqg->nr_cfqq > 1)
2979 cfq_mark_cfqq_wait_request(cfqq);
2982 sl = cfqd->cfq_group_idle;
2984 sl = cfqd->cfq_slice_idle;
2986 hrtimer_start(&cfqd->idle_slice_timer, ns_to_ktime(sl),
2988 cfqg_stats_set_start_idle_time(cfqq->cfqg);
2989 cfq_log_cfqq(cfqd, cfqq, "arm_idle: %llu group_idle: %d", sl,
2990 group_idle ? 1 : 0);
2994 * Move request from internal lists to the request queue dispatch list.
2996 static void cfq_dispatch_insert(struct request_queue *q, struct request *rq)
2998 struct cfq_data *cfqd = q->elevator->elevator_data;
2999 struct cfq_queue *cfqq = RQ_CFQQ(rq);
3001 cfq_log_cfqq(cfqd, cfqq, "dispatch_insert");
3003 cfqq->next_rq = cfq_find_next_rq(cfqd, cfqq, rq);
3004 cfq_remove_request(rq);
3006 (RQ_CFQG(rq))->dispatched++;
3007 elv_dispatch_sort(q, rq);
3009 cfqd->rq_in_flight[cfq_cfqq_sync(cfqq)]++;
3010 cfqq->nr_sectors += blk_rq_sectors(rq);
3014 * return expired entry, or NULL to just start from scratch in rbtree
3016 static struct request *cfq_check_fifo(struct cfq_queue *cfqq)
3018 struct request *rq = NULL;
3020 if (cfq_cfqq_fifo_expire(cfqq))
3023 cfq_mark_cfqq_fifo_expire(cfqq);
3025 if (list_empty(&cfqq->fifo))
3028 rq = rq_entry_fifo(cfqq->fifo.next);
3029 if (ktime_get_ns() < rq->fifo_time)
3036 cfq_prio_to_maxrq(struct cfq_data *cfqd, struct cfq_queue *cfqq)
3038 const int base_rq = cfqd->cfq_slice_async_rq;
3040 WARN_ON(cfqq->ioprio >= IOPRIO_BE_NR);
3042 return 2 * base_rq * (IOPRIO_BE_NR - cfqq->ioprio);
3046 * Must be called with the queue_lock held.
3048 static int cfqq_process_refs(struct cfq_queue *cfqq)
3050 int process_refs, io_refs;
3052 io_refs = cfqq->allocated[READ] + cfqq->allocated[WRITE];
3053 process_refs = cfqq->ref - io_refs;
3054 BUG_ON(process_refs < 0);
3055 return process_refs;
3058 static void cfq_setup_merge(struct cfq_queue *cfqq, struct cfq_queue *new_cfqq)
3060 int process_refs, new_process_refs;
3061 struct cfq_queue *__cfqq;
3064 * If there are no process references on the new_cfqq, then it is
3065 * unsafe to follow the ->new_cfqq chain as other cfqq's in the
3066 * chain may have dropped their last reference (not just their
3067 * last process reference).
3069 if (!cfqq_process_refs(new_cfqq))
3072 /* Avoid a circular list and skip interim queue merges */
3073 while ((__cfqq = new_cfqq->new_cfqq)) {
3079 process_refs = cfqq_process_refs(cfqq);
3080 new_process_refs = cfqq_process_refs(new_cfqq);
3082 * If the process for the cfqq has gone away, there is no
3083 * sense in merging the queues.
3085 if (process_refs == 0 || new_process_refs == 0)
3089 * Merge in the direction of the lesser amount of work.
3091 if (new_process_refs >= process_refs) {
3092 cfqq->new_cfqq = new_cfqq;
3093 new_cfqq->ref += process_refs;
3095 new_cfqq->new_cfqq = cfqq;
3096 cfqq->ref += new_process_refs;
3100 static enum wl_type_t cfq_choose_wl_type(struct cfq_data *cfqd,
3101 struct cfq_group *cfqg, enum wl_class_t wl_class)
3103 struct cfq_queue *queue;
3105 bool key_valid = false;
3107 enum wl_type_t cur_best = SYNC_NOIDLE_WORKLOAD;
3109 for (i = 0; i <= SYNC_WORKLOAD; ++i) {
3110 /* select the one with lowest rb_key */
3111 queue = cfq_rb_first(st_for(cfqg, wl_class, i));
3113 (!key_valid || queue->rb_key < lowest_key)) {
3114 lowest_key = queue->rb_key;
3124 choose_wl_class_and_type(struct cfq_data *cfqd, struct cfq_group *cfqg)
3128 struct cfq_rb_root *st;
3130 enum wl_class_t original_class = cfqd->serving_wl_class;
3131 u64 now = ktime_get_ns();
3133 /* Choose next priority. RT > BE > IDLE */
3134 if (cfq_group_busy_queues_wl(RT_WORKLOAD, cfqd, cfqg))
3135 cfqd->serving_wl_class = RT_WORKLOAD;
3136 else if (cfq_group_busy_queues_wl(BE_WORKLOAD, cfqd, cfqg))
3137 cfqd->serving_wl_class = BE_WORKLOAD;
3139 cfqd->serving_wl_class = IDLE_WORKLOAD;
3140 cfqd->workload_expires = now + jiffies_to_nsecs(1);
3144 if (original_class != cfqd->serving_wl_class)
3148 * For RT and BE, we have to choose also the type
3149 * (SYNC, SYNC_NOIDLE, ASYNC), and to compute a workload
3152 st = st_for(cfqg, cfqd->serving_wl_class, cfqd->serving_wl_type);
3156 * check workload expiration, and that we still have other queues ready
3158 if (count && !(now > cfqd->workload_expires))
3162 /* otherwise select new workload type */
3163 cfqd->serving_wl_type = cfq_choose_wl_type(cfqd, cfqg,
3164 cfqd->serving_wl_class);
3165 st = st_for(cfqg, cfqd->serving_wl_class, cfqd->serving_wl_type);
3169 * the workload slice is computed as a fraction of target latency
3170 * proportional to the number of queues in that workload, over
3171 * all the queues in the same priority class
3173 group_slice = cfq_group_slice(cfqd, cfqg);
3175 slice = div_u64(group_slice * count,
3176 max_t(unsigned, cfqg->busy_queues_avg[cfqd->serving_wl_class],
3177 cfq_group_busy_queues_wl(cfqd->serving_wl_class, cfqd,
3180 if (cfqd->serving_wl_type == ASYNC_WORKLOAD) {
3184 * Async queues are currently system wide. Just taking
3185 * proportion of queues with-in same group will lead to higher
3186 * async ratio system wide as generally root group is going
3187 * to have higher weight. A more accurate thing would be to
3188 * calculate system wide asnc/sync ratio.
3190 tmp = cfqd->cfq_target_latency *
3191 cfqg_busy_async_queues(cfqd, cfqg);
3192 tmp = div_u64(tmp, cfqd->busy_queues);
3193 slice = min_t(u64, slice, tmp);
3195 /* async workload slice is scaled down according to
3196 * the sync/async slice ratio. */
3197 slice = div64_u64(slice*cfqd->cfq_slice[0], cfqd->cfq_slice[1]);
3199 /* sync workload slice is at least 2 * cfq_slice_idle */
3200 slice = max(slice, 2 * cfqd->cfq_slice_idle);
3202 slice = max_t(u64, slice, CFQ_MIN_TT);
3203 cfq_log(cfqd, "workload slice:%llu", slice);
3204 cfqd->workload_expires = now + slice;
3207 static struct cfq_group *cfq_get_next_cfqg(struct cfq_data *cfqd)
3209 struct cfq_rb_root *st = &cfqd->grp_service_tree;
3210 struct cfq_group *cfqg;
3212 if (RB_EMPTY_ROOT(&st->rb))
3214 cfqg = cfq_rb_first_group(st);
3215 update_min_vdisktime(st);
3219 static void cfq_choose_cfqg(struct cfq_data *cfqd)
3221 struct cfq_group *cfqg = cfq_get_next_cfqg(cfqd);
3222 u64 now = ktime_get_ns();
3224 cfqd->serving_group = cfqg;
3226 /* Restore the workload type data */
3227 if (cfqg->saved_wl_slice) {
3228 cfqd->workload_expires = now + cfqg->saved_wl_slice;
3229 cfqd->serving_wl_type = cfqg->saved_wl_type;
3230 cfqd->serving_wl_class = cfqg->saved_wl_class;
3232 cfqd->workload_expires = now - 1;
3234 choose_wl_class_and_type(cfqd, cfqg);
3238 * Select a queue for service. If we have a current active queue,
3239 * check whether to continue servicing it, or retrieve and set a new one.
3241 static struct cfq_queue *cfq_select_queue(struct cfq_data *cfqd)
3243 struct cfq_queue *cfqq, *new_cfqq = NULL;
3244 u64 now = ktime_get_ns();
3246 cfqq = cfqd->active_queue;
3250 if (!cfqd->rq_queued)
3254 * We were waiting for group to get backlogged. Expire the queue
3256 if (cfq_cfqq_wait_busy(cfqq) && !RB_EMPTY_ROOT(&cfqq->sort_list))
3260 * The active queue has run out of time, expire it and select new.
3262 if (cfq_slice_used(cfqq) && !cfq_cfqq_must_dispatch(cfqq)) {
3264 * If slice had not expired at the completion of last request
3265 * we might not have turned on wait_busy flag. Don't expire
3266 * the queue yet. Allow the group to get backlogged.
3268 * The very fact that we have used the slice, that means we
3269 * have been idling all along on this queue and it should be
3270 * ok to wait for this request to complete.
3272 if (cfqq->cfqg->nr_cfqq == 1 && RB_EMPTY_ROOT(&cfqq->sort_list)
3273 && cfqq->dispatched && cfq_should_idle(cfqd, cfqq)) {
3277 goto check_group_idle;
3281 * The active queue has requests and isn't expired, allow it to
3284 if (!RB_EMPTY_ROOT(&cfqq->sort_list))
3288 * If another queue has a request waiting within our mean seek
3289 * distance, let it run. The expire code will check for close
3290 * cooperators and put the close queue at the front of the service
3291 * tree. If possible, merge the expiring queue with the new cfqq.
3293 new_cfqq = cfq_close_cooperator(cfqd, cfqq);
3295 if (!cfqq->new_cfqq)
3296 cfq_setup_merge(cfqq, new_cfqq);
3301 * No requests pending. If the active queue still has requests in
3302 * flight or is idling for a new request, allow either of these
3303 * conditions to happen (or time out) before selecting a new queue.
3305 if (hrtimer_active(&cfqd->idle_slice_timer)) {
3311 * This is a deep seek queue, but the device is much faster than
3312 * the queue can deliver, don't idle
3314 if (CFQQ_SEEKY(cfqq) && cfq_cfqq_idle_window(cfqq) &&
3315 (cfq_cfqq_slice_new(cfqq) ||
3316 (cfqq->slice_end - now > now - cfqq->slice_start))) {
3317 cfq_clear_cfqq_deep(cfqq);
3318 cfq_clear_cfqq_idle_window(cfqq);
3321 if (cfqq->dispatched && cfq_should_idle(cfqd, cfqq)) {
3327 * If group idle is enabled and there are requests dispatched from
3328 * this group, wait for requests to complete.
3331 if (cfqd->cfq_group_idle && cfqq->cfqg->nr_cfqq == 1 &&
3332 cfqq->cfqg->dispatched &&
3333 !cfq_io_thinktime_big(cfqd, &cfqq->cfqg->ttime, true)) {
3339 cfq_slice_expired(cfqd, 0);
3342 * Current queue expired. Check if we have to switch to a new
3346 cfq_choose_cfqg(cfqd);
3348 cfqq = cfq_set_active_queue(cfqd, new_cfqq);
3353 static int __cfq_forced_dispatch_cfqq(struct cfq_queue *cfqq)
3357 while (cfqq->next_rq) {
3358 cfq_dispatch_insert(cfqq->cfqd->queue, cfqq->next_rq);
3362 BUG_ON(!list_empty(&cfqq->fifo));
3364 /* By default cfqq is not expired if it is empty. Do it explicitly */
3365 __cfq_slice_expired(cfqq->cfqd, cfqq, 0);
3370 * Drain our current requests. Used for barriers and when switching
3371 * io schedulers on-the-fly.
3373 static int cfq_forced_dispatch(struct cfq_data *cfqd)
3375 struct cfq_queue *cfqq;
3378 /* Expire the timeslice of the current active queue first */
3379 cfq_slice_expired(cfqd, 0);
3380 while ((cfqq = cfq_get_next_queue_forced(cfqd)) != NULL) {
3381 __cfq_set_active_queue(cfqd, cfqq);
3382 dispatched += __cfq_forced_dispatch_cfqq(cfqq);
3385 BUG_ON(cfqd->busy_queues);
3387 cfq_log(cfqd, "forced_dispatch=%d", dispatched);
3391 static inline bool cfq_slice_used_soon(struct cfq_data *cfqd,
3392 struct cfq_queue *cfqq)
3394 u64 now = ktime_get_ns();
3396 /* the queue hasn't finished any request, can't estimate */
3397 if (cfq_cfqq_slice_new(cfqq))
3399 if (now + cfqd->cfq_slice_idle * cfqq->dispatched > cfqq->slice_end)
3405 static bool cfq_may_dispatch(struct cfq_data *cfqd, struct cfq_queue *cfqq)
3407 unsigned int max_dispatch;
3409 if (cfq_cfqq_must_dispatch(cfqq))
3413 * Drain async requests before we start sync IO
3415 if (cfq_should_idle(cfqd, cfqq) && cfqd->rq_in_flight[BLK_RW_ASYNC])
3419 * If this is an async queue and we have sync IO in flight, let it wait
3421 if (cfqd->rq_in_flight[BLK_RW_SYNC] && !cfq_cfqq_sync(cfqq))
3424 max_dispatch = max_t(unsigned int, cfqd->cfq_quantum / 2, 1);
3425 if (cfq_class_idle(cfqq))
3429 * Does this cfqq already have too much IO in flight?
3431 if (cfqq->dispatched >= max_dispatch) {
3432 bool promote_sync = false;
3434 * idle queue must always only have a single IO in flight
3436 if (cfq_class_idle(cfqq))
3440 * If there is only one sync queue
3441 * we can ignore async queue here and give the sync
3442 * queue no dispatch limit. The reason is a sync queue can
3443 * preempt async queue, limiting the sync queue doesn't make
3444 * sense. This is useful for aiostress test.
3446 if (cfq_cfqq_sync(cfqq) && cfqd->busy_sync_queues == 1)
3447 promote_sync = true;
3450 * We have other queues, don't allow more IO from this one
3452 if (cfqd->busy_queues > 1 && cfq_slice_used_soon(cfqd, cfqq) &&
3457 * Sole queue user, no limit
3459 if (cfqd->busy_queues == 1 || promote_sync)
3463 * Normally we start throttling cfqq when cfq_quantum/2
3464 * requests have been dispatched. But we can drive
3465 * deeper queue depths at the beginning of slice
3466 * subjected to upper limit of cfq_quantum.
3468 max_dispatch = cfqd->cfq_quantum;
3472 * Async queues must wait a bit before being allowed dispatch.
3473 * We also ramp up the dispatch depth gradually for async IO,
3474 * based on the last sync IO we serviced
3476 if (!cfq_cfqq_sync(cfqq) && cfqd->cfq_latency) {
3477 u64 last_sync = ktime_get_ns() - cfqd->last_delayed_sync;
3480 depth = div64_u64(last_sync, cfqd->cfq_slice[1]);
3481 if (!depth && !cfqq->dispatched)
3483 if (depth < max_dispatch)
3484 max_dispatch = depth;
3488 * If we're below the current max, allow a dispatch
3490 return cfqq->dispatched < max_dispatch;
3494 * Dispatch a request from cfqq, moving them to the request queue
3497 static bool cfq_dispatch_request(struct cfq_data *cfqd, struct cfq_queue *cfqq)
3501 BUG_ON(RB_EMPTY_ROOT(&cfqq->sort_list));
3503 rq = cfq_check_fifo(cfqq);
3505 cfq_mark_cfqq_must_dispatch(cfqq);
3507 if (!cfq_may_dispatch(cfqd, cfqq))
3511 * follow expired path, else get first next available
3516 cfq_log_cfqq(cfqq->cfqd, cfqq, "fifo=%p", rq);
3519 * insert request into driver dispatch list
3521 cfq_dispatch_insert(cfqd->queue, rq);
3523 if (!cfqd->active_cic) {
3524 struct cfq_io_cq *cic = RQ_CIC(rq);
3526 atomic_long_inc(&cic->icq.ioc->refcount);
3527 cfqd->active_cic = cic;
3534 * Find the cfqq that we need to service and move a request from that to the
3537 static int cfq_dispatch_requests(struct request_queue *q, int force)
3539 struct cfq_data *cfqd = q->elevator->elevator_data;
3540 struct cfq_queue *cfqq;
3542 if (!cfqd->busy_queues)
3545 if (unlikely(force))
3546 return cfq_forced_dispatch(cfqd);
3548 cfqq = cfq_select_queue(cfqd);
3553 * Dispatch a request from this cfqq, if it is allowed
3555 if (!cfq_dispatch_request(cfqd, cfqq))
3558 cfqq->slice_dispatch++;
3559 cfq_clear_cfqq_must_dispatch(cfqq);
3562 * expire an async queue immediately if it has used up its slice. idle
3563 * queue always expire after 1 dispatch round.
3565 if (cfqd->busy_queues > 1 && ((!cfq_cfqq_sync(cfqq) &&
3566 cfqq->slice_dispatch >= cfq_prio_to_maxrq(cfqd, cfqq)) ||
3567 cfq_class_idle(cfqq))) {
3568 cfqq->slice_end = ktime_get_ns() + 1;
3569 cfq_slice_expired(cfqd, 0);
3572 cfq_log_cfqq(cfqd, cfqq, "dispatched a request");
3577 * task holds one reference to the queue, dropped when task exits. each rq
3578 * in-flight on this queue also holds a reference, dropped when rq is freed.
3580 * Each cfq queue took a reference on the parent group. Drop it now.
3581 * queue lock must be held here.
3583 static void cfq_put_queue(struct cfq_queue *cfqq)
3585 struct cfq_data *cfqd = cfqq->cfqd;
3586 struct cfq_group *cfqg;
3588 BUG_ON(cfqq->ref <= 0);
3594 cfq_log_cfqq(cfqd, cfqq, "put_queue");
3595 BUG_ON(rb_first(&cfqq->sort_list));
3596 BUG_ON(cfqq->allocated[READ] + cfqq->allocated[WRITE]);
3599 if (unlikely(cfqd->active_queue == cfqq)) {
3600 __cfq_slice_expired(cfqd, cfqq, 0);
3601 cfq_schedule_dispatch(cfqd);
3604 BUG_ON(cfq_cfqq_on_rr(cfqq));
3605 kmem_cache_free(cfq_pool, cfqq);
3609 static void cfq_put_cooperator(struct cfq_queue *cfqq)
3611 struct cfq_queue *__cfqq, *next;
3614 * If this queue was scheduled to merge with another queue, be
3615 * sure to drop the reference taken on that queue (and others in
3616 * the merge chain). See cfq_setup_merge and cfq_merge_cfqqs.
3618 __cfqq = cfqq->new_cfqq;
3620 if (__cfqq == cfqq) {
3621 WARN(1, "cfqq->new_cfqq loop detected\n");
3624 next = __cfqq->new_cfqq;
3625 cfq_put_queue(__cfqq);
3630 static void cfq_exit_cfqq(struct cfq_data *cfqd, struct cfq_queue *cfqq)
3632 if (unlikely(cfqq == cfqd->active_queue)) {
3633 __cfq_slice_expired(cfqd, cfqq, 0);
3634 cfq_schedule_dispatch(cfqd);
3637 cfq_put_cooperator(cfqq);
3639 cfq_put_queue(cfqq);
3642 static void cfq_init_icq(struct io_cq *icq)
3644 struct cfq_io_cq *cic = icq_to_cic(icq);
3646 cic->ttime.last_end_request = ktime_get_ns();
3649 static void cfq_exit_icq(struct io_cq *icq)
3651 struct cfq_io_cq *cic = icq_to_cic(icq);
3652 struct cfq_data *cfqd = cic_to_cfqd(cic);
3654 if (cic_to_cfqq(cic, false)) {
3655 cfq_exit_cfqq(cfqd, cic_to_cfqq(cic, false));
3656 cic_set_cfqq(cic, NULL, false);
3659 if (cic_to_cfqq(cic, true)) {
3660 cfq_exit_cfqq(cfqd, cic_to_cfqq(cic, true));
3661 cic_set_cfqq(cic, NULL, true);
3665 static void cfq_init_prio_data(struct cfq_queue *cfqq, struct cfq_io_cq *cic)
3667 struct task_struct *tsk = current;
3670 if (!cfq_cfqq_prio_changed(cfqq))
3673 ioprio_class = IOPRIO_PRIO_CLASS(cic->ioprio);
3674 switch (ioprio_class) {
3676 printk(KERN_ERR "cfq: bad prio %x\n", ioprio_class);
3678 case IOPRIO_CLASS_NONE:
3680 * no prio set, inherit CPU scheduling settings
3682 cfqq->ioprio = task_nice_ioprio(tsk);
3683 cfqq->ioprio_class = task_nice_ioclass(tsk);
3685 case IOPRIO_CLASS_RT:
3686 cfqq->ioprio = IOPRIO_PRIO_DATA(cic->ioprio);
3687 cfqq->ioprio_class = IOPRIO_CLASS_RT;
3689 case IOPRIO_CLASS_BE:
3690 cfqq->ioprio = IOPRIO_PRIO_DATA(cic->ioprio);
3691 cfqq->ioprio_class = IOPRIO_CLASS_BE;
3693 case IOPRIO_CLASS_IDLE:
3694 cfqq->ioprio_class = IOPRIO_CLASS_IDLE;
3696 cfq_clear_cfqq_idle_window(cfqq);
3701 * keep track of original prio settings in case we have to temporarily
3702 * elevate the priority of this queue
3704 cfqq->org_ioprio = cfqq->ioprio;
3705 cfq_clear_cfqq_prio_changed(cfqq);
3708 static void check_ioprio_changed(struct cfq_io_cq *cic, struct bio *bio)
3710 int ioprio = cic->icq.ioc->ioprio;
3711 struct cfq_data *cfqd = cic_to_cfqd(cic);
3712 struct cfq_queue *cfqq;
3715 * Check whether ioprio has changed. The condition may trigger
3716 * spuriously on a newly created cic but there's no harm.
3718 if (unlikely(!cfqd) || likely(cic->ioprio == ioprio))
3721 cfqq = cic_to_cfqq(cic, false);
3723 cfq_put_queue(cfqq);
3724 cfqq = cfq_get_queue(cfqd, BLK_RW_ASYNC, cic, bio);
3725 cic_set_cfqq(cic, cfqq, false);
3728 cfqq = cic_to_cfqq(cic, true);
3730 cfq_mark_cfqq_prio_changed(cfqq);
3732 cic->ioprio = ioprio;
3735 static void cfq_init_cfqq(struct cfq_data *cfqd, struct cfq_queue *cfqq,
3736 pid_t pid, bool is_sync)
3738 RB_CLEAR_NODE(&cfqq->rb_node);
3739 RB_CLEAR_NODE(&cfqq->p_node);
3740 INIT_LIST_HEAD(&cfqq->fifo);
3745 cfq_mark_cfqq_prio_changed(cfqq);
3748 if (!cfq_class_idle(cfqq))
3749 cfq_mark_cfqq_idle_window(cfqq);
3750 cfq_mark_cfqq_sync(cfqq);
3755 #ifdef CONFIG_CFQ_GROUP_IOSCHED
3756 static void check_blkcg_changed(struct cfq_io_cq *cic, struct bio *bio)
3758 struct cfq_data *cfqd = cic_to_cfqd(cic);
3759 struct cfq_queue *cfqq;
3763 serial_nr = bio_blkcg(bio)->css.serial_nr;
3767 * Check whether blkcg has changed. The condition may trigger
3768 * spuriously on a newly created cic but there's no harm.
3770 if (unlikely(!cfqd) || likely(cic->blkcg_serial_nr == serial_nr))
3774 * Drop reference to queues. New queues will be assigned in new
3775 * group upon arrival of fresh requests.
3777 cfqq = cic_to_cfqq(cic, false);
3779 cfq_log_cfqq(cfqd, cfqq, "changed cgroup");
3780 cic_set_cfqq(cic, NULL, false);
3781 cfq_put_queue(cfqq);
3784 cfqq = cic_to_cfqq(cic, true);
3786 cfq_log_cfqq(cfqd, cfqq, "changed cgroup");
3787 cic_set_cfqq(cic, NULL, true);
3788 cfq_put_queue(cfqq);
3791 cic->blkcg_serial_nr = serial_nr;
3794 static inline void check_blkcg_changed(struct cfq_io_cq *cic, struct bio *bio) { }
3795 #endif /* CONFIG_CFQ_GROUP_IOSCHED */
3797 static struct cfq_queue **
3798 cfq_async_queue_prio(struct cfq_group *cfqg, int ioprio_class, int ioprio)
3800 switch (ioprio_class) {
3801 case IOPRIO_CLASS_RT:
3802 return &cfqg->async_cfqq[0][ioprio];
3803 case IOPRIO_CLASS_NONE:
3804 ioprio = IOPRIO_NORM;
3806 case IOPRIO_CLASS_BE:
3807 return &cfqg->async_cfqq[1][ioprio];
3808 case IOPRIO_CLASS_IDLE:
3809 return &cfqg->async_idle_cfqq;
3815 static struct cfq_queue *
3816 cfq_get_queue(struct cfq_data *cfqd, bool is_sync, struct cfq_io_cq *cic,
3819 int ioprio_class = IOPRIO_PRIO_CLASS(cic->ioprio);
3820 int ioprio = IOPRIO_PRIO_DATA(cic->ioprio);
3821 struct cfq_queue **async_cfqq = NULL;
3822 struct cfq_queue *cfqq;
3823 struct cfq_group *cfqg;
3826 cfqg = cfq_lookup_cfqg(cfqd, bio_blkcg(bio));
3828 cfqq = &cfqd->oom_cfqq;
3833 if (!ioprio_valid(cic->ioprio)) {
3834 struct task_struct *tsk = current;
3835 ioprio = task_nice_ioprio(tsk);
3836 ioprio_class = task_nice_ioclass(tsk);
3838 async_cfqq = cfq_async_queue_prio(cfqg, ioprio_class, ioprio);
3844 cfqq = kmem_cache_alloc_node(cfq_pool,
3845 GFP_NOWAIT | __GFP_ZERO | __GFP_NOWARN,
3848 cfqq = &cfqd->oom_cfqq;
3852 /* cfq_init_cfqq() assumes cfqq->ioprio_class is initialized. */
3853 cfqq->ioprio_class = IOPRIO_CLASS_NONE;
3854 cfq_init_cfqq(cfqd, cfqq, current->pid, is_sync);
3855 cfq_init_prio_data(cfqq, cic);
3856 cfq_link_cfqq_cfqg(cfqq, cfqg);
3857 cfq_log_cfqq(cfqd, cfqq, "alloced");
3860 /* a new async queue is created, pin and remember */
3871 __cfq_update_io_thinktime(struct cfq_ttime *ttime, u64 slice_idle)
3873 u64 elapsed = ktime_get_ns() - ttime->last_end_request;
3874 elapsed = min(elapsed, 2UL * slice_idle);
3876 ttime->ttime_samples = (7*ttime->ttime_samples + 256) / 8;
3877 ttime->ttime_total = div_u64(7*ttime->ttime_total + 256*elapsed, 8);
3878 ttime->ttime_mean = div64_ul(ttime->ttime_total + 128,
3879 ttime->ttime_samples);
3883 cfq_update_io_thinktime(struct cfq_data *cfqd, struct cfq_queue *cfqq,
3884 struct cfq_io_cq *cic)
3886 if (cfq_cfqq_sync(cfqq)) {
3887 __cfq_update_io_thinktime(&cic->ttime, cfqd->cfq_slice_idle);
3888 __cfq_update_io_thinktime(&cfqq->service_tree->ttime,
3889 cfqd->cfq_slice_idle);
3891 #ifdef CONFIG_CFQ_GROUP_IOSCHED
3892 __cfq_update_io_thinktime(&cfqq->cfqg->ttime, cfqd->cfq_group_idle);
3897 cfq_update_io_seektime(struct cfq_data *cfqd, struct cfq_queue *cfqq,
3901 sector_t n_sec = blk_rq_sectors(rq);
3902 if (cfqq->last_request_pos) {
3903 if (cfqq->last_request_pos < blk_rq_pos(rq))
3904 sdist = blk_rq_pos(rq) - cfqq->last_request_pos;
3906 sdist = cfqq->last_request_pos - blk_rq_pos(rq);
3909 cfqq->seek_history <<= 1;
3910 if (blk_queue_nonrot(cfqd->queue))
3911 cfqq->seek_history |= (n_sec < CFQQ_SECT_THR_NONROT);
3913 cfqq->seek_history |= (sdist > CFQQ_SEEK_THR);
3917 * Disable idle window if the process thinks too long or seeks so much that
3921 cfq_update_idle_window(struct cfq_data *cfqd, struct cfq_queue *cfqq,
3922 struct cfq_io_cq *cic)
3924 int old_idle, enable_idle;
3927 * Don't idle for async or idle io prio class
3929 if (!cfq_cfqq_sync(cfqq) || cfq_class_idle(cfqq))
3932 enable_idle = old_idle = cfq_cfqq_idle_window(cfqq);
3934 if (cfqq->queued[0] + cfqq->queued[1] >= 4)
3935 cfq_mark_cfqq_deep(cfqq);
3937 if (cfqq->next_rq && (cfqq->next_rq->cmd_flags & REQ_NOIDLE))
3939 else if (!atomic_read(&cic->icq.ioc->active_ref) ||
3940 !cfqd->cfq_slice_idle ||
3941 (!cfq_cfqq_deep(cfqq) && CFQQ_SEEKY(cfqq)))
3943 else if (sample_valid(cic->ttime.ttime_samples)) {
3944 if (cic->ttime.ttime_mean > cfqd->cfq_slice_idle)
3950 if (old_idle != enable_idle) {
3951 cfq_log_cfqq(cfqd, cfqq, "idle=%d", enable_idle);
3953 cfq_mark_cfqq_idle_window(cfqq);
3955 cfq_clear_cfqq_idle_window(cfqq);
3960 * Check if new_cfqq should preempt the currently active queue. Return 0 for
3961 * no or if we aren't sure, a 1 will cause a preempt.
3964 cfq_should_preempt(struct cfq_data *cfqd, struct cfq_queue *new_cfqq,
3967 struct cfq_queue *cfqq;
3969 cfqq = cfqd->active_queue;
3973 if (cfq_class_idle(new_cfqq))
3976 if (cfq_class_idle(cfqq))
3980 * Don't allow a non-RT request to preempt an ongoing RT cfqq timeslice.
3982 if (cfq_class_rt(cfqq) && !cfq_class_rt(new_cfqq))
3986 * if the new request is sync, but the currently running queue is
3987 * not, let the sync request have priority.
3989 if (rq_is_sync(rq) && !cfq_cfqq_sync(cfqq) && !cfq_cfqq_must_dispatch(cfqq))
3993 * Treat ancestors of current cgroup the same way as current cgroup.
3994 * For anybody else we disallow preemption to guarantee service
3995 * fairness among cgroups.
3997 if (!cfqg_is_descendant(cfqq->cfqg, new_cfqq->cfqg))
4000 if (cfq_slice_used(cfqq))
4004 * Allow an RT request to pre-empt an ongoing non-RT cfqq timeslice.
4006 if (cfq_class_rt(new_cfqq) && !cfq_class_rt(cfqq))
4009 WARN_ON_ONCE(cfqq->ioprio_class != new_cfqq->ioprio_class);
4010 /* Allow preemption only if we are idling on sync-noidle tree */
4011 if (cfqd->serving_wl_type == SYNC_NOIDLE_WORKLOAD &&
4012 cfqq_type(new_cfqq) == SYNC_NOIDLE_WORKLOAD &&
4013 RB_EMPTY_ROOT(&cfqq->sort_list))
4017 * So both queues are sync. Let the new request get disk time if
4018 * it's a metadata request and the current queue is doing regular IO.
4020 if ((rq->cmd_flags & REQ_PRIO) && !cfqq->prio_pending)
4023 /* An idle queue should not be idle now for some reason */
4024 if (RB_EMPTY_ROOT(&cfqq->sort_list) && !cfq_should_idle(cfqd, cfqq))
4027 if (!cfqd->active_cic || !cfq_cfqq_wait_request(cfqq))
4031 * if this request is as-good as one we would expect from the
4032 * current cfqq, let it preempt
4034 if (cfq_rq_close(cfqd, cfqq, rq))
4041 * cfqq preempts the active queue. if we allowed preempt with no slice left,
4042 * let it have half of its nominal slice.
4044 static void cfq_preempt_queue(struct cfq_data *cfqd, struct cfq_queue *cfqq)
4046 enum wl_type_t old_type = cfqq_type(cfqd->active_queue);
4048 cfq_log_cfqq(cfqd, cfqq, "preempt");
4049 cfq_slice_expired(cfqd, 1);
4052 * workload type is changed, don't save slice, otherwise preempt
4055 if (old_type != cfqq_type(cfqq))
4056 cfqq->cfqg->saved_wl_slice = 0;
4059 * Put the new queue at the front of the of the current list,
4060 * so we know that it will be selected next.
4062 BUG_ON(!cfq_cfqq_on_rr(cfqq));
4064 cfq_service_tree_add(cfqd, cfqq, 1);
4066 cfqq->slice_end = 0;
4067 cfq_mark_cfqq_slice_new(cfqq);
4071 * Called when a new fs request (rq) is added (to cfqq). Check if there's
4072 * something we should do about it
4075 cfq_rq_enqueued(struct cfq_data *cfqd, struct cfq_queue *cfqq,
4078 struct cfq_io_cq *cic = RQ_CIC(rq);
4081 if (rq->cmd_flags & REQ_PRIO)
4082 cfqq->prio_pending++;
4084 cfq_update_io_thinktime(cfqd, cfqq, cic);
4085 cfq_update_io_seektime(cfqd, cfqq, rq);
4086 cfq_update_idle_window(cfqd, cfqq, cic);
4088 cfqq->last_request_pos = blk_rq_pos(rq) + blk_rq_sectors(rq);
4090 if (cfqq == cfqd->active_queue) {
4092 * Remember that we saw a request from this process, but
4093 * don't start queuing just yet. Otherwise we risk seeing lots
4094 * of tiny requests, because we disrupt the normal plugging
4095 * and merging. If the request is already larger than a single
4096 * page, let it rip immediately. For that case we assume that
4097 * merging is already done. Ditto for a busy system that
4098 * has other work pending, don't risk delaying until the
4099 * idle timer unplug to continue working.
4101 if (cfq_cfqq_wait_request(cfqq)) {
4102 if (blk_rq_bytes(rq) > PAGE_CACHE_SIZE ||
4103 cfqd->busy_queues > 1) {
4104 cfq_del_timer(cfqd, cfqq);
4105 cfq_clear_cfqq_wait_request(cfqq);
4106 __blk_run_queue(cfqd->queue);
4108 cfqg_stats_update_idle_time(cfqq->cfqg);
4109 cfq_mark_cfqq_must_dispatch(cfqq);
4112 } else if (cfq_should_preempt(cfqd, cfqq, rq)) {
4114 * not the active queue - expire current slice if it is
4115 * idle and has expired it's mean thinktime or this new queue
4116 * has some old slice time left and is of higher priority or
4117 * this new queue is RT and the current one is BE
4119 cfq_preempt_queue(cfqd, cfqq);
4120 __blk_run_queue(cfqd->queue);
4124 static void cfq_insert_request(struct request_queue *q, struct request *rq)
4126 struct cfq_data *cfqd = q->elevator->elevator_data;
4127 struct cfq_queue *cfqq = RQ_CFQQ(rq);
4129 cfq_log_cfqq(cfqd, cfqq, "insert_request");
4130 cfq_init_prio_data(cfqq, RQ_CIC(rq));
4132 rq->fifo_time = ktime_get_ns() + cfqd->cfq_fifo_expire[rq_is_sync(rq)];
4133 list_add_tail(&rq->queuelist, &cfqq->fifo);
4135 cfqg_stats_update_io_add(RQ_CFQG(rq), cfqd->serving_group,
4137 cfq_rq_enqueued(cfqd, cfqq, rq);
4141 * Update hw_tag based on peak queue depth over 50 samples under
4144 static void cfq_update_hw_tag(struct cfq_data *cfqd)
4146 struct cfq_queue *cfqq = cfqd->active_queue;
4148 if (cfqd->rq_in_driver > cfqd->hw_tag_est_depth)
4149 cfqd->hw_tag_est_depth = cfqd->rq_in_driver;
4151 if (cfqd->hw_tag == 1)
4154 if (cfqd->rq_queued <= CFQ_HW_QUEUE_MIN &&
4155 cfqd->rq_in_driver <= CFQ_HW_QUEUE_MIN)
4159 * If active queue hasn't enough requests and can idle, cfq might not
4160 * dispatch sufficient requests to hardware. Don't zero hw_tag in this
4163 if (cfqq && cfq_cfqq_idle_window(cfqq) &&
4164 cfqq->dispatched + cfqq->queued[0] + cfqq->queued[1] <
4165 CFQ_HW_QUEUE_MIN && cfqd->rq_in_driver < CFQ_HW_QUEUE_MIN)
4168 if (cfqd->hw_tag_samples++ < 50)
4171 if (cfqd->hw_tag_est_depth >= CFQ_HW_QUEUE_MIN)
4177 static bool cfq_should_wait_busy(struct cfq_data *cfqd, struct cfq_queue *cfqq)
4179 struct cfq_io_cq *cic = cfqd->active_cic;
4180 u64 now = ktime_get_ns();
4182 /* If the queue already has requests, don't wait */
4183 if (!RB_EMPTY_ROOT(&cfqq->sort_list))
4186 /* If there are other queues in the group, don't wait */
4187 if (cfqq->cfqg->nr_cfqq > 1)
4190 /* the only queue in the group, but think time is big */
4191 if (cfq_io_thinktime_big(cfqd, &cfqq->cfqg->ttime, true))
4194 if (cfq_slice_used(cfqq))
4197 /* if slice left is less than think time, wait busy */
4198 if (cic && sample_valid(cic->ttime.ttime_samples)
4199 && (cfqq->slice_end - now < cic->ttime.ttime_mean))
4203 * If think times is less than a jiffy than ttime_mean=0 and above
4204 * will not be true. It might happen that slice has not expired yet
4205 * but will expire soon (4-5 ns) during select_queue(). To cover the
4206 * case where think time is less than a jiffy, mark the queue wait
4207 * busy if only 1 jiffy is left in the slice.
4209 if (cfqq->slice_end - now <= jiffies_to_nsecs(1))
4215 static void cfq_completed_request(struct request_queue *q, struct request *rq)
4217 struct cfq_queue *cfqq = RQ_CFQQ(rq);
4218 struct cfq_data *cfqd = cfqq->cfqd;
4219 const int sync = rq_is_sync(rq);
4220 u64 now = ktime_get_ns();
4222 cfq_log_cfqq(cfqd, cfqq, "complete rqnoidle %d",
4223 !!(rq->cmd_flags & REQ_NOIDLE));
4225 cfq_update_hw_tag(cfqd);
4227 WARN_ON(!cfqd->rq_in_driver);
4228 WARN_ON(!cfqq->dispatched);
4229 cfqd->rq_in_driver--;
4231 (RQ_CFQG(rq))->dispatched--;
4232 cfqg_stats_update_completion(cfqq->cfqg, rq_start_time_ns(rq),
4233 rq_io_start_time_ns(rq), rq->cmd_flags);
4235 cfqd->rq_in_flight[cfq_cfqq_sync(cfqq)]--;
4238 struct cfq_rb_root *st;
4240 RQ_CIC(rq)->ttime.last_end_request = now;
4242 if (cfq_cfqq_on_rr(cfqq))
4243 st = cfqq->service_tree;
4245 st = st_for(cfqq->cfqg, cfqq_class(cfqq),
4248 st->ttime.last_end_request = now;
4250 * We have to do this check in jiffies since start_time is in
4251 * jiffies and it is not trivial to convert to ns. If
4252 * cfq_fifo_expire[1] ever comes close to 1 jiffie, this test
4253 * will become problematic but so far we are fine (the default
4256 if (!time_after(rq->start_time +
4257 nsecs_to_jiffies(cfqd->cfq_fifo_expire[1]),
4259 cfqd->last_delayed_sync = now;
4262 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4263 cfqq->cfqg->ttime.last_end_request = now;
4267 * If this is the active queue, check if it needs to be expired,
4268 * or if we want to idle in case it has no pending requests.
4270 if (cfqd->active_queue == cfqq) {
4271 const bool cfqq_empty = RB_EMPTY_ROOT(&cfqq->sort_list);
4273 if (cfq_cfqq_slice_new(cfqq)) {
4274 cfq_set_prio_slice(cfqd, cfqq);
4275 cfq_clear_cfqq_slice_new(cfqq);
4279 * Should we wait for next request to come in before we expire
4282 if (cfq_should_wait_busy(cfqd, cfqq)) {
4283 u64 extend_sl = cfqd->cfq_slice_idle;
4284 if (!cfqd->cfq_slice_idle)
4285 extend_sl = cfqd->cfq_group_idle;
4286 cfqq->slice_end = now + extend_sl;
4287 cfq_mark_cfqq_wait_busy(cfqq);
4288 cfq_log_cfqq(cfqd, cfqq, "will busy wait");
4292 * Idling is not enabled on:
4294 * - idle-priority queues
4296 * - queues with still some requests queued
4297 * - when there is a close cooperator
4299 if (cfq_slice_used(cfqq) || cfq_class_idle(cfqq))
4300 cfq_slice_expired(cfqd, 1);
4301 else if (sync && cfqq_empty &&
4302 !cfq_close_cooperator(cfqd, cfqq)) {
4303 cfq_arm_slice_timer(cfqd);
4307 if (!cfqd->rq_in_driver)
4308 cfq_schedule_dispatch(cfqd);
4311 static inline int __cfq_may_queue(struct cfq_queue *cfqq)
4313 if (cfq_cfqq_wait_request(cfqq) && !cfq_cfqq_must_alloc_slice(cfqq)) {
4314 cfq_mark_cfqq_must_alloc_slice(cfqq);
4315 return ELV_MQUEUE_MUST;
4318 return ELV_MQUEUE_MAY;
4321 static int cfq_may_queue(struct request_queue *q, int rw)
4323 struct cfq_data *cfqd = q->elevator->elevator_data;
4324 struct task_struct *tsk = current;
4325 struct cfq_io_cq *cic;
4326 struct cfq_queue *cfqq;
4329 * don't force setup of a queue from here, as a call to may_queue
4330 * does not necessarily imply that a request actually will be queued.
4331 * so just lookup a possibly existing queue, or return 'may queue'
4334 cic = cfq_cic_lookup(cfqd, tsk->io_context);
4336 return ELV_MQUEUE_MAY;
4338 cfqq = cic_to_cfqq(cic, rw_is_sync(rw));
4340 cfq_init_prio_data(cfqq, cic);
4342 return __cfq_may_queue(cfqq);
4345 return ELV_MQUEUE_MAY;
4349 * queue lock held here
4351 static void cfq_put_request(struct request *rq)
4353 struct cfq_queue *cfqq = RQ_CFQQ(rq);
4356 const int rw = rq_data_dir(rq);
4358 BUG_ON(!cfqq->allocated[rw]);
4359 cfqq->allocated[rw]--;
4361 /* Put down rq reference on cfqg */
4362 cfqg_put(RQ_CFQG(rq));
4363 rq->elv.priv[0] = NULL;
4364 rq->elv.priv[1] = NULL;
4366 cfq_put_queue(cfqq);
4370 static struct cfq_queue *
4371 cfq_merge_cfqqs(struct cfq_data *cfqd, struct cfq_io_cq *cic,
4372 struct cfq_queue *cfqq)
4374 cfq_log_cfqq(cfqd, cfqq, "merging with queue %p", cfqq->new_cfqq);
4375 cic_set_cfqq(cic, cfqq->new_cfqq, 1);
4376 cfq_mark_cfqq_coop(cfqq->new_cfqq);
4377 cfq_put_queue(cfqq);
4378 return cic_to_cfqq(cic, 1);
4382 * Returns NULL if a new cfqq should be allocated, or the old cfqq if this
4383 * was the last process referring to said cfqq.
4385 static struct cfq_queue *
4386 split_cfqq(struct cfq_io_cq *cic, struct cfq_queue *cfqq)
4388 if (cfqq_process_refs(cfqq) == 1) {
4389 cfqq->pid = current->pid;
4390 cfq_clear_cfqq_coop(cfqq);
4391 cfq_clear_cfqq_split_coop(cfqq);
4395 cic_set_cfqq(cic, NULL, 1);
4397 cfq_put_cooperator(cfqq);
4399 cfq_put_queue(cfqq);
4403 * Allocate cfq data structures associated with this request.
4406 cfq_set_request(struct request_queue *q, struct request *rq, struct bio *bio,
4409 struct cfq_data *cfqd = q->elevator->elevator_data;
4410 struct cfq_io_cq *cic = icq_to_cic(rq->elv.icq);
4411 const int rw = rq_data_dir(rq);
4412 const bool is_sync = rq_is_sync(rq);
4413 struct cfq_queue *cfqq;
4415 spin_lock_irq(q->queue_lock);
4417 check_ioprio_changed(cic, bio);
4418 check_blkcg_changed(cic, bio);
4420 cfqq = cic_to_cfqq(cic, is_sync);
4421 if (!cfqq || cfqq == &cfqd->oom_cfqq) {
4423 cfq_put_queue(cfqq);
4424 cfqq = cfq_get_queue(cfqd, is_sync, cic, bio);
4425 cic_set_cfqq(cic, cfqq, is_sync);
4428 * If the queue was seeky for too long, break it apart.
4430 if (cfq_cfqq_coop(cfqq) && cfq_cfqq_split_coop(cfqq)) {
4431 cfq_log_cfqq(cfqd, cfqq, "breaking apart cfqq");
4432 cfqq = split_cfqq(cic, cfqq);
4438 * Check to see if this queue is scheduled to merge with
4439 * another, closely cooperating queue. The merging of
4440 * queues happens here as it must be done in process context.
4441 * The reference on new_cfqq was taken in merge_cfqqs.
4444 cfqq = cfq_merge_cfqqs(cfqd, cic, cfqq);
4447 cfqq->allocated[rw]++;
4450 cfqg_get(cfqq->cfqg);
4451 rq->elv.priv[0] = cfqq;
4452 rq->elv.priv[1] = cfqq->cfqg;
4453 spin_unlock_irq(q->queue_lock);
4457 static void cfq_kick_queue(struct work_struct *work)
4459 struct cfq_data *cfqd =
4460 container_of(work, struct cfq_data, unplug_work);
4461 struct request_queue *q = cfqd->queue;
4463 spin_lock_irq(q->queue_lock);
4464 __blk_run_queue(cfqd->queue);
4465 spin_unlock_irq(q->queue_lock);
4469 * Timer running if the active_queue is currently idling inside its time slice
4471 static enum hrtimer_restart cfq_idle_slice_timer(struct hrtimer *timer)
4473 struct cfq_data *cfqd = container_of(timer, struct cfq_data,
4475 struct cfq_queue *cfqq;
4476 unsigned long flags;
4479 cfq_log(cfqd, "idle timer fired");
4481 spin_lock_irqsave(cfqd->queue->queue_lock, flags);
4483 cfqq = cfqd->active_queue;
4488 * We saw a request before the queue expired, let it through
4490 if (cfq_cfqq_must_dispatch(cfqq))
4496 if (cfq_slice_used(cfqq))
4500 * only expire and reinvoke request handler, if there are
4501 * other queues with pending requests
4503 if (!cfqd->busy_queues)
4507 * not expired and it has a request pending, let it dispatch
4509 if (!RB_EMPTY_ROOT(&cfqq->sort_list))
4513 * Queue depth flag is reset only when the idle didn't succeed
4515 cfq_clear_cfqq_deep(cfqq);
4518 cfq_slice_expired(cfqd, timed_out);
4520 cfq_schedule_dispatch(cfqd);
4522 spin_unlock_irqrestore(cfqd->queue->queue_lock, flags);
4523 return HRTIMER_NORESTART;
4526 static void cfq_shutdown_timer_wq(struct cfq_data *cfqd)
4528 hrtimer_cancel(&cfqd->idle_slice_timer);
4529 cancel_work_sync(&cfqd->unplug_work);
4532 static void cfq_exit_queue(struct elevator_queue *e)
4534 struct cfq_data *cfqd = e->elevator_data;
4535 struct request_queue *q = cfqd->queue;
4537 cfq_shutdown_timer_wq(cfqd);
4539 spin_lock_irq(q->queue_lock);
4541 if (cfqd->active_queue)
4542 __cfq_slice_expired(cfqd, cfqd->active_queue, 0);
4544 spin_unlock_irq(q->queue_lock);
4546 cfq_shutdown_timer_wq(cfqd);
4548 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4549 blkcg_deactivate_policy(q, &blkcg_policy_cfq);
4551 kfree(cfqd->root_group);
4556 static int cfq_init_queue(struct request_queue *q, struct elevator_type *e)
4558 struct cfq_data *cfqd;
4559 struct blkcg_gq *blkg __maybe_unused;
4561 struct elevator_queue *eq;
4563 eq = elevator_alloc(q, e);
4567 cfqd = kzalloc_node(sizeof(*cfqd), GFP_KERNEL, q->node);
4569 kobject_put(&eq->kobj);
4572 eq->elevator_data = cfqd;
4575 spin_lock_irq(q->queue_lock);
4577 spin_unlock_irq(q->queue_lock);
4579 /* Init root service tree */
4580 cfqd->grp_service_tree = CFQ_RB_ROOT;
4582 /* Init root group and prefer root group over other groups by default */
4583 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4584 ret = blkcg_activate_policy(q, &blkcg_policy_cfq);
4588 cfqd->root_group = blkg_to_cfqg(q->root_blkg);
4591 cfqd->root_group = kzalloc_node(sizeof(*cfqd->root_group),
4592 GFP_KERNEL, cfqd->queue->node);
4593 if (!cfqd->root_group)
4596 cfq_init_cfqg_base(cfqd->root_group);
4597 cfqd->root_group->weight = 2 * CFQ_WEIGHT_LEGACY_DFL;
4598 cfqd->root_group->leaf_weight = 2 * CFQ_WEIGHT_LEGACY_DFL;
4602 * Not strictly needed (since RB_ROOT just clears the node and we
4603 * zeroed cfqd on alloc), but better be safe in case someone decides
4604 * to add magic to the rb code
4606 for (i = 0; i < CFQ_PRIO_LISTS; i++)
4607 cfqd->prio_trees[i] = RB_ROOT;
4610 * Our fallback cfqq if cfq_get_queue() runs into OOM issues.
4611 * Grab a permanent reference to it, so that the normal code flow
4612 * will not attempt to free it. oom_cfqq is linked to root_group
4613 * but shouldn't hold a reference as it'll never be unlinked. Lose
4614 * the reference from linking right away.
4616 cfq_init_cfqq(cfqd, &cfqd->oom_cfqq, 1, 0);
4617 cfqd->oom_cfqq.ref++;
4619 spin_lock_irq(q->queue_lock);
4620 cfq_link_cfqq_cfqg(&cfqd->oom_cfqq, cfqd->root_group);
4621 cfqg_put(cfqd->root_group);
4622 spin_unlock_irq(q->queue_lock);
4624 hrtimer_init(&cfqd->idle_slice_timer, CLOCK_MONOTONIC,
4626 cfqd->idle_slice_timer.function = cfq_idle_slice_timer;
4628 INIT_WORK(&cfqd->unplug_work, cfq_kick_queue);
4630 cfqd->cfq_quantum = cfq_quantum;
4631 cfqd->cfq_fifo_expire[0] = cfq_fifo_expire[0];
4632 cfqd->cfq_fifo_expire[1] = cfq_fifo_expire[1];
4633 cfqd->cfq_back_max = cfq_back_max;
4634 cfqd->cfq_back_penalty = cfq_back_penalty;
4635 cfqd->cfq_slice[0] = cfq_slice_async;
4636 cfqd->cfq_slice[1] = cfq_slice_sync;
4637 cfqd->cfq_target_latency = cfq_target_latency;
4638 cfqd->cfq_slice_async_rq = cfq_slice_async_rq;
4639 cfqd->cfq_slice_idle = cfq_slice_idle;
4640 cfqd->cfq_group_idle = cfq_group_idle;
4641 cfqd->cfq_latency = 1;
4644 * we optimistically start assuming sync ops weren't delayed in last
4645 * second, in order to have larger depth for async operations.
4647 cfqd->last_delayed_sync = ktime_get_ns() - NSEC_PER_SEC;
4652 kobject_put(&eq->kobj);
4656 static void cfq_registered_queue(struct request_queue *q)
4658 struct elevator_queue *e = q->elevator;
4659 struct cfq_data *cfqd = e->elevator_data;
4662 * Default to IOPS mode with no idling for SSDs
4664 if (blk_queue_nonrot(q))
4665 cfqd->cfq_slice_idle = 0;
4669 * sysfs parts below -->
4672 cfq_var_show(unsigned int var, char *page)
4674 return sprintf(page, "%u\n", var);
4678 cfq_var_store(unsigned int *var, const char *page, size_t count)
4680 char *p = (char *) page;
4682 *var = simple_strtoul(p, &p, 10);
4686 #define SHOW_FUNCTION(__FUNC, __VAR, __CONV) \
4687 static ssize_t __FUNC(struct elevator_queue *e, char *page) \
4689 struct cfq_data *cfqd = e->elevator_data; \
4690 u64 __data = __VAR; \
4692 __data = div_u64(__data, NSEC_PER_MSEC); \
4693 return cfq_var_show(__data, (page)); \
4695 SHOW_FUNCTION(cfq_quantum_show, cfqd->cfq_quantum, 0);
4696 SHOW_FUNCTION(cfq_fifo_expire_sync_show, cfqd->cfq_fifo_expire[1], 1);
4697 SHOW_FUNCTION(cfq_fifo_expire_async_show, cfqd->cfq_fifo_expire[0], 1);
4698 SHOW_FUNCTION(cfq_back_seek_max_show, cfqd->cfq_back_max, 0);
4699 SHOW_FUNCTION(cfq_back_seek_penalty_show, cfqd->cfq_back_penalty, 0);
4700 SHOW_FUNCTION(cfq_slice_idle_show, cfqd->cfq_slice_idle, 1);
4701 SHOW_FUNCTION(cfq_group_idle_show, cfqd->cfq_group_idle, 1);
4702 SHOW_FUNCTION(cfq_slice_sync_show, cfqd->cfq_slice[1], 1);
4703 SHOW_FUNCTION(cfq_slice_async_show, cfqd->cfq_slice[0], 1);
4704 SHOW_FUNCTION(cfq_slice_async_rq_show, cfqd->cfq_slice_async_rq, 0);
4705 SHOW_FUNCTION(cfq_low_latency_show, cfqd->cfq_latency, 0);
4706 SHOW_FUNCTION(cfq_target_latency_show, cfqd->cfq_target_latency, 1);
4707 #undef SHOW_FUNCTION
4709 #define USEC_SHOW_FUNCTION(__FUNC, __VAR) \
4710 static ssize_t __FUNC(struct elevator_queue *e, char *page) \
4712 struct cfq_data *cfqd = e->elevator_data; \
4713 u64 __data = __VAR; \
4714 __data = div_u64(__data, NSEC_PER_USEC); \
4715 return cfq_var_show(__data, (page)); \
4717 USEC_SHOW_FUNCTION(cfq_slice_idle_us_show, cfqd->cfq_slice_idle);
4718 USEC_SHOW_FUNCTION(cfq_group_idle_us_show, cfqd->cfq_group_idle);
4719 USEC_SHOW_FUNCTION(cfq_slice_sync_us_show, cfqd->cfq_slice[1]);
4720 USEC_SHOW_FUNCTION(cfq_slice_async_us_show, cfqd->cfq_slice[0]);
4721 USEC_SHOW_FUNCTION(cfq_target_latency_us_show, cfqd->cfq_target_latency);
4722 #undef USEC_SHOW_FUNCTION
4724 #define STORE_FUNCTION(__FUNC, __PTR, MIN, MAX, __CONV) \
4725 static ssize_t __FUNC(struct elevator_queue *e, const char *page, size_t count) \
4727 struct cfq_data *cfqd = e->elevator_data; \
4728 unsigned int __data; \
4729 int ret = cfq_var_store(&__data, (page), count); \
4730 if (__data < (MIN)) \
4732 else if (__data > (MAX)) \
4735 *(__PTR) = (u64)__data * NSEC_PER_MSEC; \
4737 *(__PTR) = __data; \
4740 STORE_FUNCTION(cfq_quantum_store, &cfqd->cfq_quantum, 1, UINT_MAX, 0);
4741 STORE_FUNCTION(cfq_fifo_expire_sync_store, &cfqd->cfq_fifo_expire[1], 1,
4743 STORE_FUNCTION(cfq_fifo_expire_async_store, &cfqd->cfq_fifo_expire[0], 1,
4745 STORE_FUNCTION(cfq_back_seek_max_store, &cfqd->cfq_back_max, 0, UINT_MAX, 0);
4746 STORE_FUNCTION(cfq_back_seek_penalty_store, &cfqd->cfq_back_penalty, 1,
4748 STORE_FUNCTION(cfq_slice_idle_store, &cfqd->cfq_slice_idle, 0, UINT_MAX, 1);
4749 STORE_FUNCTION(cfq_group_idle_store, &cfqd->cfq_group_idle, 0, UINT_MAX, 1);
4750 STORE_FUNCTION(cfq_slice_sync_store, &cfqd->cfq_slice[1], 1, UINT_MAX, 1);
4751 STORE_FUNCTION(cfq_slice_async_store, &cfqd->cfq_slice[0], 1, UINT_MAX, 1);
4752 STORE_FUNCTION(cfq_slice_async_rq_store, &cfqd->cfq_slice_async_rq, 1,
4754 STORE_FUNCTION(cfq_low_latency_store, &cfqd->cfq_latency, 0, 1, 0);
4755 STORE_FUNCTION(cfq_target_latency_store, &cfqd->cfq_target_latency, 1, UINT_MAX, 1);
4756 #undef STORE_FUNCTION
4758 #define USEC_STORE_FUNCTION(__FUNC, __PTR, MIN, MAX) \
4759 static ssize_t __FUNC(struct elevator_queue *e, const char *page, size_t count) \
4761 struct cfq_data *cfqd = e->elevator_data; \
4762 unsigned int __data; \
4763 int ret = cfq_var_store(&__data, (page), count); \
4764 if (__data < (MIN)) \
4766 else if (__data > (MAX)) \
4768 *(__PTR) = (u64)__data * NSEC_PER_USEC; \
4771 USEC_STORE_FUNCTION(cfq_slice_idle_us_store, &cfqd->cfq_slice_idle, 0, UINT_MAX);
4772 USEC_STORE_FUNCTION(cfq_group_idle_us_store, &cfqd->cfq_group_idle, 0, UINT_MAX);
4773 USEC_STORE_FUNCTION(cfq_slice_sync_us_store, &cfqd->cfq_slice[1], 1, UINT_MAX);
4774 USEC_STORE_FUNCTION(cfq_slice_async_us_store, &cfqd->cfq_slice[0], 1, UINT_MAX);
4775 USEC_STORE_FUNCTION(cfq_target_latency_us_store, &cfqd->cfq_target_latency, 1, UINT_MAX);
4776 #undef USEC_STORE_FUNCTION
4778 #define CFQ_ATTR(name) \
4779 __ATTR(name, S_IRUGO|S_IWUSR, cfq_##name##_show, cfq_##name##_store)
4781 static struct elv_fs_entry cfq_attrs[] = {
4783 CFQ_ATTR(fifo_expire_sync),
4784 CFQ_ATTR(fifo_expire_async),
4785 CFQ_ATTR(back_seek_max),
4786 CFQ_ATTR(back_seek_penalty),
4787 CFQ_ATTR(slice_sync),
4788 CFQ_ATTR(slice_sync_us),
4789 CFQ_ATTR(slice_async),
4790 CFQ_ATTR(slice_async_us),
4791 CFQ_ATTR(slice_async_rq),
4792 CFQ_ATTR(slice_idle),
4793 CFQ_ATTR(slice_idle_us),
4794 CFQ_ATTR(group_idle),
4795 CFQ_ATTR(group_idle_us),
4796 CFQ_ATTR(low_latency),
4797 CFQ_ATTR(target_latency),
4798 CFQ_ATTR(target_latency_us),
4802 static struct elevator_type iosched_cfq = {
4804 .elevator_merge_fn = cfq_merge,
4805 .elevator_merged_fn = cfq_merged_request,
4806 .elevator_merge_req_fn = cfq_merged_requests,
4807 .elevator_allow_merge_fn = cfq_allow_merge,
4808 .elevator_bio_merged_fn = cfq_bio_merged,
4809 .elevator_dispatch_fn = cfq_dispatch_requests,
4810 .elevator_add_req_fn = cfq_insert_request,
4811 .elevator_activate_req_fn = cfq_activate_request,
4812 .elevator_deactivate_req_fn = cfq_deactivate_request,
4813 .elevator_completed_req_fn = cfq_completed_request,
4814 .elevator_former_req_fn = elv_rb_former_request,
4815 .elevator_latter_req_fn = elv_rb_latter_request,
4816 .elevator_init_icq_fn = cfq_init_icq,
4817 .elevator_exit_icq_fn = cfq_exit_icq,
4818 .elevator_set_req_fn = cfq_set_request,
4819 .elevator_put_req_fn = cfq_put_request,
4820 .elevator_may_queue_fn = cfq_may_queue,
4821 .elevator_init_fn = cfq_init_queue,
4822 .elevator_exit_fn = cfq_exit_queue,
4823 .elevator_registered_fn = cfq_registered_queue,
4825 .icq_size = sizeof(struct cfq_io_cq),
4826 .icq_align = __alignof__(struct cfq_io_cq),
4827 .elevator_attrs = cfq_attrs,
4828 .elevator_name = "cfq",
4829 .elevator_owner = THIS_MODULE,
4832 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4833 static struct blkcg_policy blkcg_policy_cfq = {
4834 .dfl_cftypes = cfq_blkcg_files,
4835 .legacy_cftypes = cfq_blkcg_legacy_files,
4837 .cpd_alloc_fn = cfq_cpd_alloc,
4838 .cpd_init_fn = cfq_cpd_init,
4839 .cpd_free_fn = cfq_cpd_free,
4840 .cpd_bind_fn = cfq_cpd_bind,
4842 .pd_alloc_fn = cfq_pd_alloc,
4843 .pd_init_fn = cfq_pd_init,
4844 .pd_offline_fn = cfq_pd_offline,
4845 .pd_free_fn = cfq_pd_free,
4846 .pd_reset_stats_fn = cfq_pd_reset_stats,
4850 static int __init cfq_init(void)
4854 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4855 ret = blkcg_policy_register(&blkcg_policy_cfq);
4863 cfq_pool = KMEM_CACHE(cfq_queue, 0);
4867 ret = elv_register(&iosched_cfq);
4874 kmem_cache_destroy(cfq_pool);
4876 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4877 blkcg_policy_unregister(&blkcg_policy_cfq);
4882 static void __exit cfq_exit(void)
4884 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4885 blkcg_policy_unregister(&blkcg_policy_cfq);
4887 elv_unregister(&iosched_cfq);
4888 kmem_cache_destroy(cfq_pool);
4891 module_init(cfq_init);
4892 module_exit(cfq_exit);
4894 MODULE_AUTHOR("Jens Axboe");
4895 MODULE_LICENSE("GPL");
4896 MODULE_DESCRIPTION("Completely Fair Queueing IO scheduler");