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/sched/clock.h>
12 #include <linux/blkdev.h>
13 #include <linux/elevator.h>
14 #include <linux/ktime.h>
15 #include <linux/rbtree.h>
16 #include <linux/ioprio.h>
17 #include <linux/blktrace_api.h>
18 #include <linux/blk-cgroup.h>
25 /* max queue in one round of service */
26 static const int cfq_quantum = 8;
27 static const u64 cfq_fifo_expire[2] = { NSEC_PER_SEC / 4, NSEC_PER_SEC / 8 };
28 /* maximum backwards seek, in KiB */
29 static const int cfq_back_max = 16 * 1024;
30 /* penalty of a backwards seek */
31 static const int cfq_back_penalty = 2;
32 static const u64 cfq_slice_sync = NSEC_PER_SEC / 10;
33 static u64 cfq_slice_async = NSEC_PER_SEC / 25;
34 static const int cfq_slice_async_rq = 2;
35 static u64 cfq_slice_idle = NSEC_PER_SEC / 125;
36 static u64 cfq_group_idle = NSEC_PER_SEC / 125;
37 static const u64 cfq_target_latency = (u64)NSEC_PER_SEC * 3/10; /* 300 ms */
38 static const int cfq_hist_divisor = 4;
41 * offset from end of queue service tree for idle class
43 #define CFQ_IDLE_DELAY (NSEC_PER_SEC / 5)
44 /* offset from end of group service tree under time slice mode */
45 #define CFQ_SLICE_MODE_GROUP_DELAY (NSEC_PER_SEC / 5)
46 /* offset from end of group service under IOPS mode */
47 #define CFQ_IOPS_MODE_GROUP_DELAY (HZ / 5)
50 * below this threshold, we consider thinktime immediate
52 #define CFQ_MIN_TT (2 * NSEC_PER_SEC / HZ)
54 #define CFQ_SLICE_SCALE (5)
55 #define CFQ_HW_QUEUE_MIN (5)
56 #define CFQ_SERVICE_SHIFT 12
58 #define CFQQ_SEEK_THR (sector_t)(8 * 100)
59 #define CFQQ_CLOSE_THR (sector_t)(8 * 1024)
60 #define CFQQ_SECT_THR_NONROT (sector_t)(2 * 32)
61 #define CFQQ_SEEKY(cfqq) (hweight32(cfqq->seek_history) > 32/8)
63 #define RQ_CIC(rq) icq_to_cic((rq)->elv.icq)
64 #define RQ_CFQQ(rq) (struct cfq_queue *) ((rq)->elv.priv[0])
65 #define RQ_CFQG(rq) (struct cfq_group *) ((rq)->elv.priv[1])
67 static struct kmem_cache *cfq_pool;
69 #define CFQ_PRIO_LISTS IOPRIO_BE_NR
70 #define cfq_class_idle(cfqq) ((cfqq)->ioprio_class == IOPRIO_CLASS_IDLE)
71 #define cfq_class_rt(cfqq) ((cfqq)->ioprio_class == IOPRIO_CLASS_RT)
73 #define sample_valid(samples) ((samples) > 80)
74 #define rb_entry_cfqg(node) rb_entry((node), struct cfq_group, rb_node)
76 /* blkio-related constants */
77 #define CFQ_WEIGHT_LEGACY_MIN 10
78 #define CFQ_WEIGHT_LEGACY_DFL 500
79 #define CFQ_WEIGHT_LEGACY_MAX 1000
86 unsigned long ttime_samples;
90 * Most of our rbtree usage is for sorting with min extraction, so
91 * if we cache the leftmost node we don't have to walk down the tree
92 * to find it. Idea borrowed from Ingo Molnars CFS scheduler. We should
93 * move this into the elevator for the rq sorting as well.
100 struct cfq_ttime ttime;
102 #define CFQ_RB_ROOT (struct cfq_rb_root) { .rb = RB_ROOT, \
103 .ttime = {.last_end_request = ktime_get_ns(),},}
106 * Per process-grouping structure
109 /* reference count */
111 /* various state flags, see below */
113 /* parent cfq_data */
114 struct cfq_data *cfqd;
115 /* service_tree member */
116 struct rb_node rb_node;
117 /* service_tree key */
119 /* prio tree member */
120 struct rb_node p_node;
121 /* prio tree root we belong to, if any */
122 struct rb_root *p_root;
123 /* sorted list of pending requests */
124 struct rb_root sort_list;
125 /* if fifo isn't expired, next request to serve */
126 struct request *next_rq;
127 /* requests queued in sort_list */
129 /* currently allocated requests */
131 /* fifo list of requests in sort_list */
132 struct list_head fifo;
134 /* time when queue got scheduled in to dispatch first request. */
138 /* time when first request from queue completed and slice started. */
143 /* pending priority requests */
145 /* number of requests that are on the dispatch list or inside driver */
148 /* io prio of this group */
149 unsigned short ioprio, org_ioprio;
150 unsigned short ioprio_class, org_ioprio_class;
155 sector_t last_request_pos;
157 struct cfq_rb_root *service_tree;
158 struct cfq_queue *new_cfqq;
159 struct cfq_group *cfqg;
160 /* Number of sectors dispatched from queue in single dispatch round */
161 unsigned long nr_sectors;
165 * First index in the service_trees.
166 * IDLE is handled separately, so it has negative index
176 * Second index in the service_trees.
180 SYNC_NOIDLE_WORKLOAD = 1,
185 #ifdef CONFIG_CFQ_GROUP_IOSCHED
186 /* number of ios merged */
187 struct blkg_rwstat merged;
188 /* total time spent on device in ns, may not be accurate w/ queueing */
189 struct blkg_rwstat service_time;
190 /* total time spent waiting in scheduler queue in ns */
191 struct blkg_rwstat wait_time;
192 /* number of IOs queued up */
193 struct blkg_rwstat queued;
194 /* total disk time and nr sectors dispatched by this group */
195 struct blkg_stat time;
196 #ifdef CONFIG_DEBUG_BLK_CGROUP
197 /* time not charged to this cgroup */
198 struct blkg_stat unaccounted_time;
199 /* sum of number of ios queued across all samples */
200 struct blkg_stat avg_queue_size_sum;
201 /* count of samples taken for average */
202 struct blkg_stat avg_queue_size_samples;
203 /* how many times this group has been removed from service tree */
204 struct blkg_stat dequeue;
205 /* total time spent waiting for it to be assigned a timeslice. */
206 struct blkg_stat group_wait_time;
207 /* time spent idling for this blkcg_gq */
208 struct blkg_stat idle_time;
209 /* total time with empty current active q with other requests queued */
210 struct blkg_stat empty_time;
211 /* fields after this shouldn't be cleared on stat reset */
212 uint64_t start_group_wait_time;
213 uint64_t start_idle_time;
214 uint64_t start_empty_time;
216 #endif /* CONFIG_DEBUG_BLK_CGROUP */
217 #endif /* CONFIG_CFQ_GROUP_IOSCHED */
220 /* Per-cgroup data */
221 struct cfq_group_data {
222 /* must be the first member */
223 struct blkcg_policy_data cpd;
226 unsigned int leaf_weight;
229 /* This is per cgroup per device grouping structure */
231 /* must be the first member */
232 struct blkg_policy_data pd;
234 /* group service_tree member */
235 struct rb_node rb_node;
237 /* group service_tree key */
241 * The number of active cfqgs and sum of their weights under this
242 * cfqg. This covers this cfqg's leaf_weight and all children's
243 * weights, but does not cover weights of further descendants.
245 * If a cfqg is on the service tree, it's active. An active cfqg
246 * also activates its parent and contributes to the children_weight
250 unsigned int children_weight;
253 * vfraction is the fraction of vdisktime that the tasks in this
254 * cfqg are entitled to. This is determined by compounding the
255 * ratios walking up from this cfqg to the root.
257 * It is in fixed point w/ CFQ_SERVICE_SHIFT and the sum of all
258 * vfractions on a service tree is approximately 1. The sum may
259 * deviate a bit due to rounding errors and fluctuations caused by
260 * cfqgs entering and leaving the service tree.
262 unsigned int vfraction;
265 * There are two weights - (internal) weight is the weight of this
266 * cfqg against the sibling cfqgs. leaf_weight is the wight of
267 * this cfqg against the child cfqgs. For the root cfqg, both
268 * weights are kept in sync for backward compatibility.
271 unsigned int new_weight;
272 unsigned int dev_weight;
274 unsigned int leaf_weight;
275 unsigned int new_leaf_weight;
276 unsigned int dev_leaf_weight;
278 /* number of cfqq currently on this group */
282 * Per group busy queues average. Useful for workload slice calc. We
283 * create the array for each prio class but at run time it is used
284 * only for RT and BE class and slot for IDLE class remains unused.
285 * This is primarily done to avoid confusion and a gcc warning.
287 unsigned int busy_queues_avg[CFQ_PRIO_NR];
289 * rr lists of queues with requests. We maintain service trees for
290 * RT and BE classes. These trees are subdivided in subclasses
291 * of SYNC, SYNC_NOIDLE and ASYNC based on workload type. For IDLE
292 * class there is no subclassification and all the cfq queues go on
293 * a single tree service_tree_idle.
294 * Counts are embedded in the cfq_rb_root
296 struct cfq_rb_root service_trees[2][3];
297 struct cfq_rb_root service_tree_idle;
300 enum wl_type_t saved_wl_type;
301 enum wl_class_t saved_wl_class;
303 /* number of requests that are on the dispatch list or inside driver */
305 struct cfq_ttime ttime;
306 struct cfqg_stats stats; /* stats for this cfqg */
308 /* async queue for each priority case */
309 struct cfq_queue *async_cfqq[2][IOPRIO_BE_NR];
310 struct cfq_queue *async_idle_cfqq;
315 struct io_cq icq; /* must be the first member */
316 struct cfq_queue *cfqq[2];
317 struct cfq_ttime ttime;
318 int ioprio; /* the current ioprio */
319 #ifdef CONFIG_CFQ_GROUP_IOSCHED
320 uint64_t blkcg_serial_nr; /* the current blkcg serial */
325 * Per block device queue structure
328 struct request_queue *queue;
329 /* Root service tree for cfq_groups */
330 struct cfq_rb_root grp_service_tree;
331 struct cfq_group *root_group;
334 * The priority currently being served
336 enum wl_class_t serving_wl_class;
337 enum wl_type_t serving_wl_type;
338 u64 workload_expires;
339 struct cfq_group *serving_group;
342 * Each priority tree is sorted by next_request position. These
343 * trees are used when determining if two or more queues are
344 * interleaving requests (see cfq_close_cooperator).
346 struct rb_root prio_trees[CFQ_PRIO_LISTS];
348 unsigned int busy_queues;
349 unsigned int busy_sync_queues;
355 * queue-depth detection
361 * -1 => indeterminate, (cfq will behave as if NCQ is present, to allow better detection)
362 * 1 => NCQ is present (hw_tag_est_depth is the estimated max depth)
365 int hw_tag_est_depth;
366 unsigned int hw_tag_samples;
369 * idle window management
371 struct hrtimer idle_slice_timer;
372 struct work_struct unplug_work;
374 struct cfq_queue *active_queue;
375 struct cfq_io_cq *active_cic;
377 sector_t last_position;
380 * tunables, see top of file
382 unsigned int cfq_quantum;
383 unsigned int cfq_back_penalty;
384 unsigned int cfq_back_max;
385 unsigned int cfq_slice_async_rq;
386 unsigned int cfq_latency;
387 u64 cfq_fifo_expire[2];
391 u64 cfq_target_latency;
394 * Fallback dummy cfqq for extreme OOM conditions
396 struct cfq_queue oom_cfqq;
398 u64 last_delayed_sync;
401 static struct cfq_group *cfq_get_next_cfqg(struct cfq_data *cfqd);
402 static void cfq_put_queue(struct cfq_queue *cfqq);
404 static struct cfq_rb_root *st_for(struct cfq_group *cfqg,
405 enum wl_class_t class,
411 if (class == IDLE_WORKLOAD)
412 return &cfqg->service_tree_idle;
414 return &cfqg->service_trees[class][type];
417 enum cfqq_state_flags {
418 CFQ_CFQQ_FLAG_on_rr = 0, /* on round-robin busy list */
419 CFQ_CFQQ_FLAG_wait_request, /* waiting for a request */
420 CFQ_CFQQ_FLAG_must_dispatch, /* must be allowed a dispatch */
421 CFQ_CFQQ_FLAG_must_alloc_slice, /* per-slice must_alloc flag */
422 CFQ_CFQQ_FLAG_fifo_expire, /* FIFO checked in this slice */
423 CFQ_CFQQ_FLAG_idle_window, /* slice idling enabled */
424 CFQ_CFQQ_FLAG_prio_changed, /* task priority has changed */
425 CFQ_CFQQ_FLAG_slice_new, /* no requests dispatched in slice */
426 CFQ_CFQQ_FLAG_sync, /* synchronous queue */
427 CFQ_CFQQ_FLAG_coop, /* cfqq is shared */
428 CFQ_CFQQ_FLAG_split_coop, /* shared cfqq will be splitted */
429 CFQ_CFQQ_FLAG_deep, /* sync cfqq experienced large depth */
430 CFQ_CFQQ_FLAG_wait_busy, /* Waiting for next request */
433 #define CFQ_CFQQ_FNS(name) \
434 static inline void cfq_mark_cfqq_##name(struct cfq_queue *cfqq) \
436 (cfqq)->flags |= (1 << CFQ_CFQQ_FLAG_##name); \
438 static inline void cfq_clear_cfqq_##name(struct cfq_queue *cfqq) \
440 (cfqq)->flags &= ~(1 << CFQ_CFQQ_FLAG_##name); \
442 static inline int cfq_cfqq_##name(const struct cfq_queue *cfqq) \
444 return ((cfqq)->flags & (1 << CFQ_CFQQ_FLAG_##name)) != 0; \
448 CFQ_CFQQ_FNS(wait_request);
449 CFQ_CFQQ_FNS(must_dispatch);
450 CFQ_CFQQ_FNS(must_alloc_slice);
451 CFQ_CFQQ_FNS(fifo_expire);
452 CFQ_CFQQ_FNS(idle_window);
453 CFQ_CFQQ_FNS(prio_changed);
454 CFQ_CFQQ_FNS(slice_new);
457 CFQ_CFQQ_FNS(split_coop);
459 CFQ_CFQQ_FNS(wait_busy);
462 #if defined(CONFIG_CFQ_GROUP_IOSCHED) && defined(CONFIG_DEBUG_BLK_CGROUP)
464 /* cfqg stats flags */
465 enum cfqg_stats_flags {
466 CFQG_stats_waiting = 0,
471 #define CFQG_FLAG_FNS(name) \
472 static inline void cfqg_stats_mark_##name(struct cfqg_stats *stats) \
474 stats->flags |= (1 << CFQG_stats_##name); \
476 static inline void cfqg_stats_clear_##name(struct cfqg_stats *stats) \
478 stats->flags &= ~(1 << CFQG_stats_##name); \
480 static inline int cfqg_stats_##name(struct cfqg_stats *stats) \
482 return (stats->flags & (1 << CFQG_stats_##name)) != 0; \
485 CFQG_FLAG_FNS(waiting)
486 CFQG_FLAG_FNS(idling)
490 /* This should be called with the queue_lock held. */
491 static void cfqg_stats_update_group_wait_time(struct cfqg_stats *stats)
493 unsigned long long now;
495 if (!cfqg_stats_waiting(stats))
499 if (time_after64(now, stats->start_group_wait_time))
500 blkg_stat_add(&stats->group_wait_time,
501 now - stats->start_group_wait_time);
502 cfqg_stats_clear_waiting(stats);
505 /* This should be called with the queue_lock held. */
506 static void cfqg_stats_set_start_group_wait_time(struct cfq_group *cfqg,
507 struct cfq_group *curr_cfqg)
509 struct cfqg_stats *stats = &cfqg->stats;
511 if (cfqg_stats_waiting(stats))
513 if (cfqg == curr_cfqg)
515 stats->start_group_wait_time = sched_clock();
516 cfqg_stats_mark_waiting(stats);
519 /* This should be called with the queue_lock held. */
520 static void cfqg_stats_end_empty_time(struct cfqg_stats *stats)
522 unsigned long long now;
524 if (!cfqg_stats_empty(stats))
528 if (time_after64(now, stats->start_empty_time))
529 blkg_stat_add(&stats->empty_time,
530 now - stats->start_empty_time);
531 cfqg_stats_clear_empty(stats);
534 static void cfqg_stats_update_dequeue(struct cfq_group *cfqg)
536 blkg_stat_add(&cfqg->stats.dequeue, 1);
539 static void cfqg_stats_set_start_empty_time(struct cfq_group *cfqg)
541 struct cfqg_stats *stats = &cfqg->stats;
543 if (blkg_rwstat_total(&stats->queued))
547 * group is already marked empty. This can happen if cfqq got new
548 * request in parent group and moved to this group while being added
549 * to service tree. Just ignore the event and move on.
551 if (cfqg_stats_empty(stats))
554 stats->start_empty_time = sched_clock();
555 cfqg_stats_mark_empty(stats);
558 static void cfqg_stats_update_idle_time(struct cfq_group *cfqg)
560 struct cfqg_stats *stats = &cfqg->stats;
562 if (cfqg_stats_idling(stats)) {
563 unsigned long long now = sched_clock();
565 if (time_after64(now, stats->start_idle_time))
566 blkg_stat_add(&stats->idle_time,
567 now - stats->start_idle_time);
568 cfqg_stats_clear_idling(stats);
572 static void cfqg_stats_set_start_idle_time(struct cfq_group *cfqg)
574 struct cfqg_stats *stats = &cfqg->stats;
576 BUG_ON(cfqg_stats_idling(stats));
578 stats->start_idle_time = sched_clock();
579 cfqg_stats_mark_idling(stats);
582 static void cfqg_stats_update_avg_queue_size(struct cfq_group *cfqg)
584 struct cfqg_stats *stats = &cfqg->stats;
586 blkg_stat_add(&stats->avg_queue_size_sum,
587 blkg_rwstat_total(&stats->queued));
588 blkg_stat_add(&stats->avg_queue_size_samples, 1);
589 cfqg_stats_update_group_wait_time(stats);
592 #else /* CONFIG_CFQ_GROUP_IOSCHED && CONFIG_DEBUG_BLK_CGROUP */
594 static inline void cfqg_stats_set_start_group_wait_time(struct cfq_group *cfqg, struct cfq_group *curr_cfqg) { }
595 static inline void cfqg_stats_end_empty_time(struct cfqg_stats *stats) { }
596 static inline void cfqg_stats_update_dequeue(struct cfq_group *cfqg) { }
597 static inline void cfqg_stats_set_start_empty_time(struct cfq_group *cfqg) { }
598 static inline void cfqg_stats_update_idle_time(struct cfq_group *cfqg) { }
599 static inline void cfqg_stats_set_start_idle_time(struct cfq_group *cfqg) { }
600 static inline void cfqg_stats_update_avg_queue_size(struct cfq_group *cfqg) { }
602 #endif /* CONFIG_CFQ_GROUP_IOSCHED && CONFIG_DEBUG_BLK_CGROUP */
604 #ifdef CONFIG_CFQ_GROUP_IOSCHED
606 static inline struct cfq_group *pd_to_cfqg(struct blkg_policy_data *pd)
608 return pd ? container_of(pd, struct cfq_group, pd) : NULL;
611 static struct cfq_group_data
612 *cpd_to_cfqgd(struct blkcg_policy_data *cpd)
614 return cpd ? container_of(cpd, struct cfq_group_data, cpd) : NULL;
617 static inline struct blkcg_gq *cfqg_to_blkg(struct cfq_group *cfqg)
619 return pd_to_blkg(&cfqg->pd);
622 static struct blkcg_policy blkcg_policy_cfq;
624 static inline struct cfq_group *blkg_to_cfqg(struct blkcg_gq *blkg)
626 return pd_to_cfqg(blkg_to_pd(blkg, &blkcg_policy_cfq));
629 static struct cfq_group_data *blkcg_to_cfqgd(struct blkcg *blkcg)
631 return cpd_to_cfqgd(blkcg_to_cpd(blkcg, &blkcg_policy_cfq));
634 static inline struct cfq_group *cfqg_parent(struct cfq_group *cfqg)
636 struct blkcg_gq *pblkg = cfqg_to_blkg(cfqg)->parent;
638 return pblkg ? blkg_to_cfqg(pblkg) : NULL;
641 static inline bool cfqg_is_descendant(struct cfq_group *cfqg,
642 struct cfq_group *ancestor)
644 return cgroup_is_descendant(cfqg_to_blkg(cfqg)->blkcg->css.cgroup,
645 cfqg_to_blkg(ancestor)->blkcg->css.cgroup);
648 static inline void cfqg_get(struct cfq_group *cfqg)
650 return blkg_get(cfqg_to_blkg(cfqg));
653 static inline void cfqg_put(struct cfq_group *cfqg)
655 return blkg_put(cfqg_to_blkg(cfqg));
658 #define cfq_log_cfqq(cfqd, cfqq, fmt, args...) do { \
659 blk_add_cgroup_trace_msg((cfqd)->queue, \
660 cfqg_to_blkg((cfqq)->cfqg)->blkcg, \
661 "cfq%d%c%c " fmt, (cfqq)->pid, \
662 cfq_cfqq_sync((cfqq)) ? 'S' : 'A', \
663 cfqq_type((cfqq)) == SYNC_NOIDLE_WORKLOAD ? 'N' : ' ',\
667 #define cfq_log_cfqg(cfqd, cfqg, fmt, args...) do { \
668 blk_add_cgroup_trace_msg((cfqd)->queue, \
669 cfqg_to_blkg(cfqg)->blkcg, fmt, ##args); \
672 static inline void cfqg_stats_update_io_add(struct cfq_group *cfqg,
673 struct cfq_group *curr_cfqg,
676 blkg_rwstat_add(&cfqg->stats.queued, op, 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,
693 blkg_rwstat_add(&cfqg->stats.queued, op, -1);
696 static inline void cfqg_stats_update_io_merged(struct cfq_group *cfqg,
699 blkg_rwstat_add(&cfqg->stats.merged, op, 1);
702 static inline void cfqg_stats_update_completion(struct cfq_group *cfqg,
703 uint64_t start_time, uint64_t io_start_time,
706 struct cfqg_stats *stats = &cfqg->stats;
707 unsigned long long now = sched_clock();
709 if (time_after64(now, io_start_time))
710 blkg_rwstat_add(&stats->service_time, op, now - io_start_time);
711 if (time_after64(io_start_time, start_time))
712 blkg_rwstat_add(&stats->wait_time, op,
713 io_start_time - start_time);
717 static void cfqg_stats_reset(struct cfqg_stats *stats)
719 /* queued stats shouldn't be cleared */
720 blkg_rwstat_reset(&stats->merged);
721 blkg_rwstat_reset(&stats->service_time);
722 blkg_rwstat_reset(&stats->wait_time);
723 blkg_stat_reset(&stats->time);
724 #ifdef CONFIG_DEBUG_BLK_CGROUP
725 blkg_stat_reset(&stats->unaccounted_time);
726 blkg_stat_reset(&stats->avg_queue_size_sum);
727 blkg_stat_reset(&stats->avg_queue_size_samples);
728 blkg_stat_reset(&stats->dequeue);
729 blkg_stat_reset(&stats->group_wait_time);
730 blkg_stat_reset(&stats->idle_time);
731 blkg_stat_reset(&stats->empty_time);
736 static void cfqg_stats_add_aux(struct cfqg_stats *to, struct cfqg_stats *from)
738 /* queued stats shouldn't be cleared */
739 blkg_rwstat_add_aux(&to->merged, &from->merged);
740 blkg_rwstat_add_aux(&to->service_time, &from->service_time);
741 blkg_rwstat_add_aux(&to->wait_time, &from->wait_time);
742 blkg_stat_add_aux(&from->time, &from->time);
743 #ifdef CONFIG_DEBUG_BLK_CGROUP
744 blkg_stat_add_aux(&to->unaccounted_time, &from->unaccounted_time);
745 blkg_stat_add_aux(&to->avg_queue_size_sum, &from->avg_queue_size_sum);
746 blkg_stat_add_aux(&to->avg_queue_size_samples, &from->avg_queue_size_samples);
747 blkg_stat_add_aux(&to->dequeue, &from->dequeue);
748 blkg_stat_add_aux(&to->group_wait_time, &from->group_wait_time);
749 blkg_stat_add_aux(&to->idle_time, &from->idle_time);
750 blkg_stat_add_aux(&to->empty_time, &from->empty_time);
755 * Transfer @cfqg's stats to its parent's aux counts so that the ancestors'
756 * recursive stats can still account for the amount used by this cfqg after
759 static void cfqg_stats_xfer_dead(struct cfq_group *cfqg)
761 struct cfq_group *parent = cfqg_parent(cfqg);
763 lockdep_assert_held(cfqg_to_blkg(cfqg)->q->queue_lock);
765 if (unlikely(!parent))
768 cfqg_stats_add_aux(&parent->stats, &cfqg->stats);
769 cfqg_stats_reset(&cfqg->stats);
772 #else /* CONFIG_CFQ_GROUP_IOSCHED */
774 static inline struct cfq_group *cfqg_parent(struct cfq_group *cfqg) { return NULL; }
775 static inline bool cfqg_is_descendant(struct cfq_group *cfqg,
776 struct cfq_group *ancestor)
780 static inline void cfqg_get(struct cfq_group *cfqg) { }
781 static inline void cfqg_put(struct cfq_group *cfqg) { }
783 #define cfq_log_cfqq(cfqd, cfqq, fmt, args...) \
784 blk_add_trace_msg((cfqd)->queue, "cfq%d%c%c " fmt, (cfqq)->pid, \
785 cfq_cfqq_sync((cfqq)) ? 'S' : 'A', \
786 cfqq_type((cfqq)) == SYNC_NOIDLE_WORKLOAD ? 'N' : ' ',\
788 #define cfq_log_cfqg(cfqd, cfqg, fmt, args...) do {} while (0)
790 static inline void cfqg_stats_update_io_add(struct cfq_group *cfqg,
791 struct cfq_group *curr_cfqg, unsigned int op) { }
792 static inline void cfqg_stats_update_timeslice_used(struct cfq_group *cfqg,
793 uint64_t time, unsigned long unaccounted_time) { }
794 static inline void cfqg_stats_update_io_remove(struct cfq_group *cfqg,
796 static inline void cfqg_stats_update_io_merged(struct cfq_group *cfqg,
798 static inline void cfqg_stats_update_completion(struct cfq_group *cfqg,
799 uint64_t start_time, uint64_t io_start_time,
802 #endif /* CONFIG_CFQ_GROUP_IOSCHED */
804 #define cfq_log(cfqd, fmt, args...) \
805 blk_add_trace_msg((cfqd)->queue, "cfq " fmt, ##args)
807 /* Traverses through cfq group service trees */
808 #define for_each_cfqg_st(cfqg, i, j, st) \
809 for (i = 0; i <= IDLE_WORKLOAD; i++) \
810 for (j = 0, st = i < IDLE_WORKLOAD ? &cfqg->service_trees[i][j]\
811 : &cfqg->service_tree_idle; \
812 (i < IDLE_WORKLOAD && j <= SYNC_WORKLOAD) || \
813 (i == IDLE_WORKLOAD && j == 0); \
814 j++, st = i < IDLE_WORKLOAD ? \
815 &cfqg->service_trees[i][j]: NULL) \
817 static inline bool cfq_io_thinktime_big(struct cfq_data *cfqd,
818 struct cfq_ttime *ttime, bool group_idle)
821 if (!sample_valid(ttime->ttime_samples))
824 slice = cfqd->cfq_group_idle;
826 slice = cfqd->cfq_slice_idle;
827 return ttime->ttime_mean > slice;
830 static inline bool iops_mode(struct cfq_data *cfqd)
833 * If we are not idling on queues and it is a NCQ drive, parallel
834 * execution of requests is on and measuring time is not possible
835 * in most of the cases until and unless we drive shallower queue
836 * depths and that becomes a performance bottleneck. In such cases
837 * switch to start providing fairness in terms of number of IOs.
839 if (!cfqd->cfq_slice_idle && cfqd->hw_tag)
845 static inline enum wl_class_t cfqq_class(struct cfq_queue *cfqq)
847 if (cfq_class_idle(cfqq))
848 return IDLE_WORKLOAD;
849 if (cfq_class_rt(cfqq))
855 static enum wl_type_t cfqq_type(struct cfq_queue *cfqq)
857 if (!cfq_cfqq_sync(cfqq))
858 return ASYNC_WORKLOAD;
859 if (!cfq_cfqq_idle_window(cfqq))
860 return SYNC_NOIDLE_WORKLOAD;
861 return SYNC_WORKLOAD;
864 static inline int cfq_group_busy_queues_wl(enum wl_class_t wl_class,
865 struct cfq_data *cfqd,
866 struct cfq_group *cfqg)
868 if (wl_class == IDLE_WORKLOAD)
869 return cfqg->service_tree_idle.count;
871 return cfqg->service_trees[wl_class][ASYNC_WORKLOAD].count +
872 cfqg->service_trees[wl_class][SYNC_NOIDLE_WORKLOAD].count +
873 cfqg->service_trees[wl_class][SYNC_WORKLOAD].count;
876 static inline int cfqg_busy_async_queues(struct cfq_data *cfqd,
877 struct cfq_group *cfqg)
879 return cfqg->service_trees[RT_WORKLOAD][ASYNC_WORKLOAD].count +
880 cfqg->service_trees[BE_WORKLOAD][ASYNC_WORKLOAD].count;
883 static void cfq_dispatch_insert(struct request_queue *, struct request *);
884 static struct cfq_queue *cfq_get_queue(struct cfq_data *cfqd, bool is_sync,
885 struct cfq_io_cq *cic, struct bio *bio);
887 static inline struct cfq_io_cq *icq_to_cic(struct io_cq *icq)
889 /* cic->icq is the first member, %NULL will convert to %NULL */
890 return container_of(icq, struct cfq_io_cq, icq);
893 static inline struct cfq_io_cq *cfq_cic_lookup(struct cfq_data *cfqd,
894 struct io_context *ioc)
897 return icq_to_cic(ioc_lookup_icq(ioc, cfqd->queue));
901 static inline struct cfq_queue *cic_to_cfqq(struct cfq_io_cq *cic, bool is_sync)
903 return cic->cfqq[is_sync];
906 static inline void cic_set_cfqq(struct cfq_io_cq *cic, struct cfq_queue *cfqq,
909 cic->cfqq[is_sync] = cfqq;
912 static inline struct cfq_data *cic_to_cfqd(struct cfq_io_cq *cic)
914 return cic->icq.q->elevator->elevator_data;
918 * scheduler run of queue, if there are requests pending and no one in the
919 * driver that will restart queueing
921 static inline void cfq_schedule_dispatch(struct cfq_data *cfqd)
923 if (cfqd->busy_queues) {
924 cfq_log(cfqd, "schedule dispatch");
925 kblockd_schedule_work(&cfqd->unplug_work);
930 * Scale schedule slice based on io priority. Use the sync time slice only
931 * if a queue is marked sync and has sync io queued. A sync queue with async
932 * io only, should not get full sync slice length.
934 static inline u64 cfq_prio_slice(struct cfq_data *cfqd, bool sync,
937 u64 base_slice = cfqd->cfq_slice[sync];
938 u64 slice = div_u64(base_slice, CFQ_SLICE_SCALE);
940 WARN_ON(prio >= IOPRIO_BE_NR);
942 return base_slice + (slice * (4 - prio));
946 cfq_prio_to_slice(struct cfq_data *cfqd, struct cfq_queue *cfqq)
948 return cfq_prio_slice(cfqd, cfq_cfqq_sync(cfqq), cfqq->ioprio);
952 * cfqg_scale_charge - scale disk time charge according to cfqg weight
953 * @charge: disk time being charged
954 * @vfraction: vfraction of the cfqg, fixed point w/ CFQ_SERVICE_SHIFT
956 * Scale @charge according to @vfraction, which is in range (0, 1]. The
957 * scaling is inversely proportional.
959 * scaled = charge / vfraction
961 * The result is also in fixed point w/ CFQ_SERVICE_SHIFT.
963 static inline u64 cfqg_scale_charge(u64 charge,
964 unsigned int vfraction)
966 u64 c = charge << CFQ_SERVICE_SHIFT; /* make it fixed point */
968 /* charge / vfraction */
969 c <<= CFQ_SERVICE_SHIFT;
970 return div_u64(c, vfraction);
973 static inline u64 max_vdisktime(u64 min_vdisktime, u64 vdisktime)
975 s64 delta = (s64)(vdisktime - min_vdisktime);
977 min_vdisktime = vdisktime;
979 return min_vdisktime;
982 static void update_min_vdisktime(struct cfq_rb_root *st)
984 struct cfq_group *cfqg;
987 cfqg = rb_entry_cfqg(st->left);
988 st->min_vdisktime = max_vdisktime(st->min_vdisktime,
994 * get averaged number of queues of RT/BE priority.
995 * average is updated, with a formula that gives more weight to higher numbers,
996 * to quickly follows sudden increases and decrease slowly
999 static inline unsigned cfq_group_get_avg_queues(struct cfq_data *cfqd,
1000 struct cfq_group *cfqg, bool rt)
1002 unsigned min_q, max_q;
1003 unsigned mult = cfq_hist_divisor - 1;
1004 unsigned round = cfq_hist_divisor / 2;
1005 unsigned busy = cfq_group_busy_queues_wl(rt, cfqd, cfqg);
1007 min_q = min(cfqg->busy_queues_avg[rt], busy);
1008 max_q = max(cfqg->busy_queues_avg[rt], busy);
1009 cfqg->busy_queues_avg[rt] = (mult * max_q + min_q + round) /
1011 return cfqg->busy_queues_avg[rt];
1015 cfq_group_slice(struct cfq_data *cfqd, struct cfq_group *cfqg)
1017 return cfqd->cfq_target_latency * cfqg->vfraction >> CFQ_SERVICE_SHIFT;
1021 cfq_scaled_cfqq_slice(struct cfq_data *cfqd, struct cfq_queue *cfqq)
1023 u64 slice = cfq_prio_to_slice(cfqd, cfqq);
1024 if (cfqd->cfq_latency) {
1026 * interested queues (we consider only the ones with the same
1027 * priority class in the cfq group)
1029 unsigned iq = cfq_group_get_avg_queues(cfqd, cfqq->cfqg,
1030 cfq_class_rt(cfqq));
1031 u64 sync_slice = cfqd->cfq_slice[1];
1032 u64 expect_latency = sync_slice * iq;
1033 u64 group_slice = cfq_group_slice(cfqd, cfqq->cfqg);
1035 if (expect_latency > group_slice) {
1036 u64 base_low_slice = 2 * cfqd->cfq_slice_idle;
1039 /* scale low_slice according to IO priority
1040 * and sync vs async */
1041 low_slice = div64_u64(base_low_slice*slice, sync_slice);
1042 low_slice = min(slice, low_slice);
1043 /* the adapted slice value is scaled to fit all iqs
1044 * into the target latency */
1045 slice = div64_u64(slice*group_slice, expect_latency);
1046 slice = max(slice, low_slice);
1053 cfq_set_prio_slice(struct cfq_data *cfqd, struct cfq_queue *cfqq)
1055 u64 slice = cfq_scaled_cfqq_slice(cfqd, cfqq);
1056 u64 now = ktime_get_ns();
1058 cfqq->slice_start = now;
1059 cfqq->slice_end = now + slice;
1060 cfqq->allocated_slice = slice;
1061 cfq_log_cfqq(cfqd, cfqq, "set_slice=%llu", cfqq->slice_end - now);
1065 * We need to wrap this check in cfq_cfqq_slice_new(), since ->slice_end
1066 * isn't valid until the first request from the dispatch is activated
1067 * and the slice time set.
1069 static inline bool cfq_slice_used(struct cfq_queue *cfqq)
1071 if (cfq_cfqq_slice_new(cfqq))
1073 if (ktime_get_ns() < cfqq->slice_end)
1080 * Lifted from AS - choose which of rq1 and rq2 that is best served now.
1081 * We choose the request that is closest to the head right now. Distance
1082 * behind the head is penalized and only allowed to a certain extent.
1084 static struct request *
1085 cfq_choose_req(struct cfq_data *cfqd, struct request *rq1, struct request *rq2, sector_t last)
1087 sector_t s1, s2, d1 = 0, d2 = 0;
1088 unsigned long back_max;
1089 #define CFQ_RQ1_WRAP 0x01 /* request 1 wraps */
1090 #define CFQ_RQ2_WRAP 0x02 /* request 2 wraps */
1091 unsigned wrap = 0; /* bit mask: requests behind the disk head? */
1093 if (rq1 == NULL || rq1 == rq2)
1098 if (rq_is_sync(rq1) != rq_is_sync(rq2))
1099 return rq_is_sync(rq1) ? rq1 : rq2;
1101 if ((rq1->cmd_flags ^ rq2->cmd_flags) & REQ_PRIO)
1102 return rq1->cmd_flags & REQ_PRIO ? rq1 : rq2;
1104 s1 = blk_rq_pos(rq1);
1105 s2 = blk_rq_pos(rq2);
1108 * by definition, 1KiB is 2 sectors
1110 back_max = cfqd->cfq_back_max * 2;
1113 * Strict one way elevator _except_ in the case where we allow
1114 * short backward seeks which are biased as twice the cost of a
1115 * similar forward seek.
1119 else if (s1 + back_max >= last)
1120 d1 = (last - s1) * cfqd->cfq_back_penalty;
1122 wrap |= CFQ_RQ1_WRAP;
1126 else if (s2 + back_max >= last)
1127 d2 = (last - s2) * cfqd->cfq_back_penalty;
1129 wrap |= CFQ_RQ2_WRAP;
1131 /* Found required data */
1134 * By doing switch() on the bit mask "wrap" we avoid having to
1135 * check two variables for all permutations: --> faster!
1138 case 0: /* common case for CFQ: rq1 and rq2 not wrapped */
1154 case (CFQ_RQ1_WRAP|CFQ_RQ2_WRAP): /* both rqs wrapped */
1157 * Since both rqs are wrapped,
1158 * start with the one that's further behind head
1159 * (--> only *one* back seek required),
1160 * since back seek takes more time than forward.
1170 * The below is leftmost cache rbtree addon
1172 static struct cfq_queue *cfq_rb_first(struct cfq_rb_root *root)
1174 /* Service tree is empty */
1179 root->left = rb_first(&root->rb);
1182 return rb_entry(root->left, struct cfq_queue, rb_node);
1187 static struct cfq_group *cfq_rb_first_group(struct cfq_rb_root *root)
1190 root->left = rb_first(&root->rb);
1193 return rb_entry_cfqg(root->left);
1198 static void rb_erase_init(struct rb_node *n, struct rb_root *root)
1204 static void cfq_rb_erase(struct rb_node *n, struct cfq_rb_root *root)
1206 if (root->left == n)
1208 rb_erase_init(n, &root->rb);
1213 * would be nice to take fifo expire time into account as well
1215 static struct request *
1216 cfq_find_next_rq(struct cfq_data *cfqd, struct cfq_queue *cfqq,
1217 struct request *last)
1219 struct rb_node *rbnext = rb_next(&last->rb_node);
1220 struct rb_node *rbprev = rb_prev(&last->rb_node);
1221 struct request *next = NULL, *prev = NULL;
1223 BUG_ON(RB_EMPTY_NODE(&last->rb_node));
1226 prev = rb_entry_rq(rbprev);
1229 next = rb_entry_rq(rbnext);
1231 rbnext = rb_first(&cfqq->sort_list);
1232 if (rbnext && rbnext != &last->rb_node)
1233 next = rb_entry_rq(rbnext);
1236 return cfq_choose_req(cfqd, next, prev, blk_rq_pos(last));
1239 static u64 cfq_slice_offset(struct cfq_data *cfqd,
1240 struct cfq_queue *cfqq)
1243 * just an approximation, should be ok.
1245 return (cfqq->cfqg->nr_cfqq - 1) * (cfq_prio_slice(cfqd, 1, 0) -
1246 cfq_prio_slice(cfqd, cfq_cfqq_sync(cfqq), cfqq->ioprio));
1250 cfqg_key(struct cfq_rb_root *st, struct cfq_group *cfqg)
1252 return cfqg->vdisktime - st->min_vdisktime;
1256 __cfq_group_service_tree_add(struct cfq_rb_root *st, struct cfq_group *cfqg)
1258 struct rb_node **node = &st->rb.rb_node;
1259 struct rb_node *parent = NULL;
1260 struct cfq_group *__cfqg;
1261 s64 key = cfqg_key(st, cfqg);
1264 while (*node != NULL) {
1266 __cfqg = rb_entry_cfqg(parent);
1268 if (key < cfqg_key(st, __cfqg))
1269 node = &parent->rb_left;
1271 node = &parent->rb_right;
1277 st->left = &cfqg->rb_node;
1279 rb_link_node(&cfqg->rb_node, parent, node);
1280 rb_insert_color(&cfqg->rb_node, &st->rb);
1284 * This has to be called only on activation of cfqg
1287 cfq_update_group_weight(struct cfq_group *cfqg)
1289 if (cfqg->new_weight) {
1290 cfqg->weight = cfqg->new_weight;
1291 cfqg->new_weight = 0;
1296 cfq_update_group_leaf_weight(struct cfq_group *cfqg)
1298 BUG_ON(!RB_EMPTY_NODE(&cfqg->rb_node));
1300 if (cfqg->new_leaf_weight) {
1301 cfqg->leaf_weight = cfqg->new_leaf_weight;
1302 cfqg->new_leaf_weight = 0;
1307 cfq_group_service_tree_add(struct cfq_rb_root *st, struct cfq_group *cfqg)
1309 unsigned int vfr = 1 << CFQ_SERVICE_SHIFT; /* start with 1 */
1310 struct cfq_group *pos = cfqg;
1311 struct cfq_group *parent;
1314 /* add to the service tree */
1315 BUG_ON(!RB_EMPTY_NODE(&cfqg->rb_node));
1318 * Update leaf_weight. We cannot update weight at this point
1319 * because cfqg might already have been activated and is
1320 * contributing its current weight to the parent's child_weight.
1322 cfq_update_group_leaf_weight(cfqg);
1323 __cfq_group_service_tree_add(st, cfqg);
1326 * Activate @cfqg and calculate the portion of vfraction @cfqg is
1327 * entitled to. vfraction is calculated by walking the tree
1328 * towards the root calculating the fraction it has at each level.
1329 * The compounded ratio is how much vfraction @cfqg owns.
1331 * Start with the proportion tasks in this cfqg has against active
1332 * children cfqgs - its leaf_weight against children_weight.
1334 propagate = !pos->nr_active++;
1335 pos->children_weight += pos->leaf_weight;
1336 vfr = vfr * pos->leaf_weight / pos->children_weight;
1339 * Compound ->weight walking up the tree. Both activation and
1340 * vfraction calculation are done in the same loop. Propagation
1341 * stops once an already activated node is met. vfraction
1342 * calculation should always continue to the root.
1344 while ((parent = cfqg_parent(pos))) {
1346 cfq_update_group_weight(pos);
1347 propagate = !parent->nr_active++;
1348 parent->children_weight += pos->weight;
1350 vfr = vfr * pos->weight / parent->children_weight;
1354 cfqg->vfraction = max_t(unsigned, vfr, 1);
1357 static inline u64 cfq_get_cfqg_vdisktime_delay(struct cfq_data *cfqd)
1359 if (!iops_mode(cfqd))
1360 return CFQ_SLICE_MODE_GROUP_DELAY;
1362 return CFQ_IOPS_MODE_GROUP_DELAY;
1366 cfq_group_notify_queue_add(struct cfq_data *cfqd, struct cfq_group *cfqg)
1368 struct cfq_rb_root *st = &cfqd->grp_service_tree;
1369 struct cfq_group *__cfqg;
1373 if (!RB_EMPTY_NODE(&cfqg->rb_node))
1377 * Currently put the group at the end. Later implement something
1378 * so that groups get lesser vtime based on their weights, so that
1379 * if group does not loose all if it was not continuously backlogged.
1381 n = rb_last(&st->rb);
1383 __cfqg = rb_entry_cfqg(n);
1384 cfqg->vdisktime = __cfqg->vdisktime +
1385 cfq_get_cfqg_vdisktime_delay(cfqd);
1387 cfqg->vdisktime = st->min_vdisktime;
1388 cfq_group_service_tree_add(st, cfqg);
1392 cfq_group_service_tree_del(struct cfq_rb_root *st, struct cfq_group *cfqg)
1394 struct cfq_group *pos = cfqg;
1398 * Undo activation from cfq_group_service_tree_add(). Deactivate
1399 * @cfqg and propagate deactivation upwards.
1401 propagate = !--pos->nr_active;
1402 pos->children_weight -= pos->leaf_weight;
1405 struct cfq_group *parent = cfqg_parent(pos);
1407 /* @pos has 0 nr_active at this point */
1408 WARN_ON_ONCE(pos->children_weight);
1414 propagate = !--parent->nr_active;
1415 parent->children_weight -= pos->weight;
1419 /* remove from the service tree */
1420 if (!RB_EMPTY_NODE(&cfqg->rb_node))
1421 cfq_rb_erase(&cfqg->rb_node, st);
1425 cfq_group_notify_queue_del(struct cfq_data *cfqd, struct cfq_group *cfqg)
1427 struct cfq_rb_root *st = &cfqd->grp_service_tree;
1429 BUG_ON(cfqg->nr_cfqq < 1);
1432 /* If there are other cfq queues under this group, don't delete it */
1436 cfq_log_cfqg(cfqd, cfqg, "del_from_rr group");
1437 cfq_group_service_tree_del(st, cfqg);
1438 cfqg->saved_wl_slice = 0;
1439 cfqg_stats_update_dequeue(cfqg);
1442 static inline u64 cfq_cfqq_slice_usage(struct cfq_queue *cfqq,
1443 u64 *unaccounted_time)
1446 u64 now = ktime_get_ns();
1449 * Queue got expired before even a single request completed or
1450 * got expired immediately after first request completion.
1452 if (!cfqq->slice_start || cfqq->slice_start == now) {
1454 * Also charge the seek time incurred to the group, otherwise
1455 * if there are mutiple queues in the group, each can dispatch
1456 * a single request on seeky media and cause lots of seek time
1457 * and group will never know it.
1459 slice_used = max_t(u64, (now - cfqq->dispatch_start),
1460 jiffies_to_nsecs(1));
1462 slice_used = now - cfqq->slice_start;
1463 if (slice_used > cfqq->allocated_slice) {
1464 *unaccounted_time = slice_used - cfqq->allocated_slice;
1465 slice_used = cfqq->allocated_slice;
1467 if (cfqq->slice_start > cfqq->dispatch_start)
1468 *unaccounted_time += cfqq->slice_start -
1469 cfqq->dispatch_start;
1475 static void cfq_group_served(struct cfq_data *cfqd, struct cfq_group *cfqg,
1476 struct cfq_queue *cfqq)
1478 struct cfq_rb_root *st = &cfqd->grp_service_tree;
1479 u64 used_sl, charge, unaccounted_sl = 0;
1480 int nr_sync = cfqg->nr_cfqq - cfqg_busy_async_queues(cfqd, cfqg)
1481 - cfqg->service_tree_idle.count;
1483 u64 now = ktime_get_ns();
1485 BUG_ON(nr_sync < 0);
1486 used_sl = charge = cfq_cfqq_slice_usage(cfqq, &unaccounted_sl);
1488 if (iops_mode(cfqd))
1489 charge = cfqq->slice_dispatch;
1490 else if (!cfq_cfqq_sync(cfqq) && !nr_sync)
1491 charge = cfqq->allocated_slice;
1494 * Can't update vdisktime while on service tree and cfqg->vfraction
1495 * is valid only while on it. Cache vfr, leave the service tree,
1496 * update vdisktime and go back on. The re-addition to the tree
1497 * will also update the weights as necessary.
1499 vfr = cfqg->vfraction;
1500 cfq_group_service_tree_del(st, cfqg);
1501 cfqg->vdisktime += cfqg_scale_charge(charge, vfr);
1502 cfq_group_service_tree_add(st, cfqg);
1504 /* This group is being expired. Save the context */
1505 if (cfqd->workload_expires > now) {
1506 cfqg->saved_wl_slice = cfqd->workload_expires - now;
1507 cfqg->saved_wl_type = cfqd->serving_wl_type;
1508 cfqg->saved_wl_class = cfqd->serving_wl_class;
1510 cfqg->saved_wl_slice = 0;
1512 cfq_log_cfqg(cfqd, cfqg, "served: vt=%llu min_vt=%llu", cfqg->vdisktime,
1514 cfq_log_cfqq(cfqq->cfqd, cfqq,
1515 "sl_used=%llu disp=%llu charge=%llu iops=%u sect=%lu",
1516 used_sl, cfqq->slice_dispatch, charge,
1517 iops_mode(cfqd), cfqq->nr_sectors);
1518 cfqg_stats_update_timeslice_used(cfqg, used_sl, unaccounted_sl);
1519 cfqg_stats_set_start_empty_time(cfqg);
1523 * cfq_init_cfqg_base - initialize base part of a cfq_group
1524 * @cfqg: cfq_group to initialize
1526 * Initialize the base part which is used whether %CONFIG_CFQ_GROUP_IOSCHED
1527 * is enabled or not.
1529 static void cfq_init_cfqg_base(struct cfq_group *cfqg)
1531 struct cfq_rb_root *st;
1534 for_each_cfqg_st(cfqg, i, j, st)
1536 RB_CLEAR_NODE(&cfqg->rb_node);
1538 cfqg->ttime.last_end_request = ktime_get_ns();
1541 #ifdef CONFIG_CFQ_GROUP_IOSCHED
1542 static int __cfq_set_weight(struct cgroup_subsys_state *css, u64 val,
1543 bool on_dfl, bool reset_dev, bool is_leaf_weight);
1545 static void cfqg_stats_exit(struct cfqg_stats *stats)
1547 blkg_rwstat_exit(&stats->merged);
1548 blkg_rwstat_exit(&stats->service_time);
1549 blkg_rwstat_exit(&stats->wait_time);
1550 blkg_rwstat_exit(&stats->queued);
1551 blkg_stat_exit(&stats->time);
1552 #ifdef CONFIG_DEBUG_BLK_CGROUP
1553 blkg_stat_exit(&stats->unaccounted_time);
1554 blkg_stat_exit(&stats->avg_queue_size_sum);
1555 blkg_stat_exit(&stats->avg_queue_size_samples);
1556 blkg_stat_exit(&stats->dequeue);
1557 blkg_stat_exit(&stats->group_wait_time);
1558 blkg_stat_exit(&stats->idle_time);
1559 blkg_stat_exit(&stats->empty_time);
1563 static int cfqg_stats_init(struct cfqg_stats *stats, gfp_t gfp)
1565 if (blkg_rwstat_init(&stats->merged, gfp) ||
1566 blkg_rwstat_init(&stats->service_time, gfp) ||
1567 blkg_rwstat_init(&stats->wait_time, gfp) ||
1568 blkg_rwstat_init(&stats->queued, gfp) ||
1569 blkg_stat_init(&stats->time, gfp))
1572 #ifdef CONFIG_DEBUG_BLK_CGROUP
1573 if (blkg_stat_init(&stats->unaccounted_time, gfp) ||
1574 blkg_stat_init(&stats->avg_queue_size_sum, gfp) ||
1575 blkg_stat_init(&stats->avg_queue_size_samples, gfp) ||
1576 blkg_stat_init(&stats->dequeue, gfp) ||
1577 blkg_stat_init(&stats->group_wait_time, gfp) ||
1578 blkg_stat_init(&stats->idle_time, gfp) ||
1579 blkg_stat_init(&stats->empty_time, gfp))
1584 cfqg_stats_exit(stats);
1588 static struct blkcg_policy_data *cfq_cpd_alloc(gfp_t gfp)
1590 struct cfq_group_data *cgd;
1592 cgd = kzalloc(sizeof(*cgd), gfp);
1598 static void cfq_cpd_init(struct blkcg_policy_data *cpd)
1600 struct cfq_group_data *cgd = cpd_to_cfqgd(cpd);
1601 unsigned int weight = cgroup_subsys_on_dfl(io_cgrp_subsys) ?
1602 CGROUP_WEIGHT_DFL : CFQ_WEIGHT_LEGACY_DFL;
1604 if (cpd_to_blkcg(cpd) == &blkcg_root)
1607 cgd->weight = weight;
1608 cgd->leaf_weight = weight;
1611 static void cfq_cpd_free(struct blkcg_policy_data *cpd)
1613 kfree(cpd_to_cfqgd(cpd));
1616 static void cfq_cpd_bind(struct blkcg_policy_data *cpd)
1618 struct blkcg *blkcg = cpd_to_blkcg(cpd);
1619 bool on_dfl = cgroup_subsys_on_dfl(io_cgrp_subsys);
1620 unsigned int weight = on_dfl ? CGROUP_WEIGHT_DFL : CFQ_WEIGHT_LEGACY_DFL;
1622 if (blkcg == &blkcg_root)
1625 WARN_ON_ONCE(__cfq_set_weight(&blkcg->css, weight, on_dfl, true, false));
1626 WARN_ON_ONCE(__cfq_set_weight(&blkcg->css, weight, on_dfl, true, true));
1629 static struct blkg_policy_data *cfq_pd_alloc(gfp_t gfp, int node)
1631 struct cfq_group *cfqg;
1633 cfqg = kzalloc_node(sizeof(*cfqg), gfp, node);
1637 cfq_init_cfqg_base(cfqg);
1638 if (cfqg_stats_init(&cfqg->stats, gfp)) {
1646 static void cfq_pd_init(struct blkg_policy_data *pd)
1648 struct cfq_group *cfqg = pd_to_cfqg(pd);
1649 struct cfq_group_data *cgd = blkcg_to_cfqgd(pd->blkg->blkcg);
1651 cfqg->weight = cgd->weight;
1652 cfqg->leaf_weight = cgd->leaf_weight;
1655 static void cfq_pd_offline(struct blkg_policy_data *pd)
1657 struct cfq_group *cfqg = pd_to_cfqg(pd);
1660 for (i = 0; i < IOPRIO_BE_NR; i++) {
1661 if (cfqg->async_cfqq[0][i])
1662 cfq_put_queue(cfqg->async_cfqq[0][i]);
1663 if (cfqg->async_cfqq[1][i])
1664 cfq_put_queue(cfqg->async_cfqq[1][i]);
1667 if (cfqg->async_idle_cfqq)
1668 cfq_put_queue(cfqg->async_idle_cfqq);
1671 * @blkg is going offline and will be ignored by
1672 * blkg_[rw]stat_recursive_sum(). Transfer stats to the parent so
1673 * that they don't get lost. If IOs complete after this point, the
1674 * stats for them will be lost. Oh well...
1676 cfqg_stats_xfer_dead(cfqg);
1679 static void cfq_pd_free(struct blkg_policy_data *pd)
1681 struct cfq_group *cfqg = pd_to_cfqg(pd);
1683 cfqg_stats_exit(&cfqg->stats);
1687 static void cfq_pd_reset_stats(struct blkg_policy_data *pd)
1689 struct cfq_group *cfqg = pd_to_cfqg(pd);
1691 cfqg_stats_reset(&cfqg->stats);
1694 static struct cfq_group *cfq_lookup_cfqg(struct cfq_data *cfqd,
1695 struct blkcg *blkcg)
1697 struct blkcg_gq *blkg;
1699 blkg = blkg_lookup(blkcg, cfqd->queue);
1701 return blkg_to_cfqg(blkg);
1705 static void cfq_link_cfqq_cfqg(struct cfq_queue *cfqq, struct cfq_group *cfqg)
1708 /* cfqq reference on cfqg */
1712 static u64 cfqg_prfill_weight_device(struct seq_file *sf,
1713 struct blkg_policy_data *pd, int off)
1715 struct cfq_group *cfqg = pd_to_cfqg(pd);
1717 if (!cfqg->dev_weight)
1719 return __blkg_prfill_u64(sf, pd, cfqg->dev_weight);
1722 static int cfqg_print_weight_device(struct seq_file *sf, void *v)
1724 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1725 cfqg_prfill_weight_device, &blkcg_policy_cfq,
1730 static u64 cfqg_prfill_leaf_weight_device(struct seq_file *sf,
1731 struct blkg_policy_data *pd, int off)
1733 struct cfq_group *cfqg = pd_to_cfqg(pd);
1735 if (!cfqg->dev_leaf_weight)
1737 return __blkg_prfill_u64(sf, pd, cfqg->dev_leaf_weight);
1740 static int cfqg_print_leaf_weight_device(struct seq_file *sf, void *v)
1742 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1743 cfqg_prfill_leaf_weight_device, &blkcg_policy_cfq,
1748 static int cfq_print_weight(struct seq_file *sf, void *v)
1750 struct blkcg *blkcg = css_to_blkcg(seq_css(sf));
1751 struct cfq_group_data *cgd = blkcg_to_cfqgd(blkcg);
1752 unsigned int val = 0;
1757 seq_printf(sf, "%u\n", val);
1761 static int cfq_print_leaf_weight(struct seq_file *sf, void *v)
1763 struct blkcg *blkcg = css_to_blkcg(seq_css(sf));
1764 struct cfq_group_data *cgd = blkcg_to_cfqgd(blkcg);
1765 unsigned int val = 0;
1768 val = cgd->leaf_weight;
1770 seq_printf(sf, "%u\n", val);
1774 static ssize_t __cfqg_set_weight_device(struct kernfs_open_file *of,
1775 char *buf, size_t nbytes, loff_t off,
1776 bool on_dfl, bool is_leaf_weight)
1778 unsigned int min = on_dfl ? CGROUP_WEIGHT_MIN : CFQ_WEIGHT_LEGACY_MIN;
1779 unsigned int max = on_dfl ? CGROUP_WEIGHT_MAX : CFQ_WEIGHT_LEGACY_MAX;
1780 struct blkcg *blkcg = css_to_blkcg(of_css(of));
1781 struct blkg_conf_ctx ctx;
1782 struct cfq_group *cfqg;
1783 struct cfq_group_data *cfqgd;
1787 ret = blkg_conf_prep(blkcg, &blkcg_policy_cfq, buf, &ctx);
1791 if (sscanf(ctx.body, "%llu", &v) == 1) {
1792 /* require "default" on dfl */
1796 } else if (!strcmp(strim(ctx.body), "default")) {
1803 cfqg = blkg_to_cfqg(ctx.blkg);
1804 cfqgd = blkcg_to_cfqgd(blkcg);
1807 if (!v || (v >= min && v <= max)) {
1808 if (!is_leaf_weight) {
1809 cfqg->dev_weight = v;
1810 cfqg->new_weight = v ?: cfqgd->weight;
1812 cfqg->dev_leaf_weight = v;
1813 cfqg->new_leaf_weight = v ?: cfqgd->leaf_weight;
1818 blkg_conf_finish(&ctx);
1819 return ret ?: nbytes;
1822 static ssize_t cfqg_set_weight_device(struct kernfs_open_file *of,
1823 char *buf, size_t nbytes, loff_t off)
1825 return __cfqg_set_weight_device(of, buf, nbytes, off, false, false);
1828 static ssize_t cfqg_set_leaf_weight_device(struct kernfs_open_file *of,
1829 char *buf, size_t nbytes, loff_t off)
1831 return __cfqg_set_weight_device(of, buf, nbytes, off, false, true);
1834 static int __cfq_set_weight(struct cgroup_subsys_state *css, u64 val,
1835 bool on_dfl, bool reset_dev, bool is_leaf_weight)
1837 unsigned int min = on_dfl ? CGROUP_WEIGHT_MIN : CFQ_WEIGHT_LEGACY_MIN;
1838 unsigned int max = on_dfl ? CGROUP_WEIGHT_MAX : CFQ_WEIGHT_LEGACY_MAX;
1839 struct blkcg *blkcg = css_to_blkcg(css);
1840 struct blkcg_gq *blkg;
1841 struct cfq_group_data *cfqgd;
1844 if (val < min || val > max)
1847 spin_lock_irq(&blkcg->lock);
1848 cfqgd = blkcg_to_cfqgd(blkcg);
1854 if (!is_leaf_weight)
1855 cfqgd->weight = val;
1857 cfqgd->leaf_weight = val;
1859 hlist_for_each_entry(blkg, &blkcg->blkg_list, blkcg_node) {
1860 struct cfq_group *cfqg = blkg_to_cfqg(blkg);
1865 if (!is_leaf_weight) {
1867 cfqg->dev_weight = 0;
1868 if (!cfqg->dev_weight)
1869 cfqg->new_weight = cfqgd->weight;
1872 cfqg->dev_leaf_weight = 0;
1873 if (!cfqg->dev_leaf_weight)
1874 cfqg->new_leaf_weight = cfqgd->leaf_weight;
1879 spin_unlock_irq(&blkcg->lock);
1883 static int cfq_set_weight(struct cgroup_subsys_state *css, struct cftype *cft,
1886 return __cfq_set_weight(css, val, false, false, false);
1889 static int cfq_set_leaf_weight(struct cgroup_subsys_state *css,
1890 struct cftype *cft, u64 val)
1892 return __cfq_set_weight(css, val, false, false, true);
1895 static int cfqg_print_stat(struct seq_file *sf, void *v)
1897 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), blkg_prfill_stat,
1898 &blkcg_policy_cfq, seq_cft(sf)->private, false);
1902 static int cfqg_print_rwstat(struct seq_file *sf, void *v)
1904 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)), blkg_prfill_rwstat,
1905 &blkcg_policy_cfq, seq_cft(sf)->private, true);
1909 static u64 cfqg_prfill_stat_recursive(struct seq_file *sf,
1910 struct blkg_policy_data *pd, int off)
1912 u64 sum = blkg_stat_recursive_sum(pd_to_blkg(pd),
1913 &blkcg_policy_cfq, off);
1914 return __blkg_prfill_u64(sf, pd, sum);
1917 static u64 cfqg_prfill_rwstat_recursive(struct seq_file *sf,
1918 struct blkg_policy_data *pd, int off)
1920 struct blkg_rwstat sum = blkg_rwstat_recursive_sum(pd_to_blkg(pd),
1921 &blkcg_policy_cfq, off);
1922 return __blkg_prfill_rwstat(sf, pd, &sum);
1925 static int cfqg_print_stat_recursive(struct seq_file *sf, void *v)
1927 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1928 cfqg_prfill_stat_recursive, &blkcg_policy_cfq,
1929 seq_cft(sf)->private, false);
1933 static int cfqg_print_rwstat_recursive(struct seq_file *sf, void *v)
1935 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1936 cfqg_prfill_rwstat_recursive, &blkcg_policy_cfq,
1937 seq_cft(sf)->private, true);
1941 static u64 cfqg_prfill_sectors(struct seq_file *sf, struct blkg_policy_data *pd,
1944 u64 sum = blkg_rwstat_total(&pd->blkg->stat_bytes);
1946 return __blkg_prfill_u64(sf, pd, sum >> 9);
1949 static int cfqg_print_stat_sectors(struct seq_file *sf, void *v)
1951 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1952 cfqg_prfill_sectors, &blkcg_policy_cfq, 0, false);
1956 static u64 cfqg_prfill_sectors_recursive(struct seq_file *sf,
1957 struct blkg_policy_data *pd, int off)
1959 struct blkg_rwstat tmp = blkg_rwstat_recursive_sum(pd->blkg, NULL,
1960 offsetof(struct blkcg_gq, stat_bytes));
1961 u64 sum = atomic64_read(&tmp.aux_cnt[BLKG_RWSTAT_READ]) +
1962 atomic64_read(&tmp.aux_cnt[BLKG_RWSTAT_WRITE]);
1964 return __blkg_prfill_u64(sf, pd, sum >> 9);
1967 static int cfqg_print_stat_sectors_recursive(struct seq_file *sf, void *v)
1969 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1970 cfqg_prfill_sectors_recursive, &blkcg_policy_cfq, 0,
1975 #ifdef CONFIG_DEBUG_BLK_CGROUP
1976 static u64 cfqg_prfill_avg_queue_size(struct seq_file *sf,
1977 struct blkg_policy_data *pd, int off)
1979 struct cfq_group *cfqg = pd_to_cfqg(pd);
1980 u64 samples = blkg_stat_read(&cfqg->stats.avg_queue_size_samples);
1984 v = blkg_stat_read(&cfqg->stats.avg_queue_size_sum);
1985 v = div64_u64(v, samples);
1987 __blkg_prfill_u64(sf, pd, v);
1991 /* print avg_queue_size */
1992 static int cfqg_print_avg_queue_size(struct seq_file *sf, void *v)
1994 blkcg_print_blkgs(sf, css_to_blkcg(seq_css(sf)),
1995 cfqg_prfill_avg_queue_size, &blkcg_policy_cfq,
1999 #endif /* CONFIG_DEBUG_BLK_CGROUP */
2001 static struct cftype cfq_blkcg_legacy_files[] = {
2002 /* on root, weight is mapped to leaf_weight */
2004 .name = "weight_device",
2005 .flags = CFTYPE_ONLY_ON_ROOT,
2006 .seq_show = cfqg_print_leaf_weight_device,
2007 .write = cfqg_set_leaf_weight_device,
2011 .flags = CFTYPE_ONLY_ON_ROOT,
2012 .seq_show = cfq_print_leaf_weight,
2013 .write_u64 = cfq_set_leaf_weight,
2016 /* no such mapping necessary for !roots */
2018 .name = "weight_device",
2019 .flags = CFTYPE_NOT_ON_ROOT,
2020 .seq_show = cfqg_print_weight_device,
2021 .write = cfqg_set_weight_device,
2025 .flags = CFTYPE_NOT_ON_ROOT,
2026 .seq_show = cfq_print_weight,
2027 .write_u64 = cfq_set_weight,
2031 .name = "leaf_weight_device",
2032 .seq_show = cfqg_print_leaf_weight_device,
2033 .write = cfqg_set_leaf_weight_device,
2036 .name = "leaf_weight",
2037 .seq_show = cfq_print_leaf_weight,
2038 .write_u64 = cfq_set_leaf_weight,
2041 /* statistics, covers only the tasks in the cfqg */
2044 .private = offsetof(struct cfq_group, stats.time),
2045 .seq_show = cfqg_print_stat,
2049 .seq_show = cfqg_print_stat_sectors,
2052 .name = "io_service_bytes",
2053 .private = (unsigned long)&blkcg_policy_cfq,
2054 .seq_show = blkg_print_stat_bytes,
2057 .name = "io_serviced",
2058 .private = (unsigned long)&blkcg_policy_cfq,
2059 .seq_show = blkg_print_stat_ios,
2062 .name = "io_service_time",
2063 .private = offsetof(struct cfq_group, stats.service_time),
2064 .seq_show = cfqg_print_rwstat,
2067 .name = "io_wait_time",
2068 .private = offsetof(struct cfq_group, stats.wait_time),
2069 .seq_show = cfqg_print_rwstat,
2072 .name = "io_merged",
2073 .private = offsetof(struct cfq_group, stats.merged),
2074 .seq_show = cfqg_print_rwstat,
2077 .name = "io_queued",
2078 .private = offsetof(struct cfq_group, stats.queued),
2079 .seq_show = cfqg_print_rwstat,
2082 /* the same statictics which cover the cfqg and its descendants */
2084 .name = "time_recursive",
2085 .private = offsetof(struct cfq_group, stats.time),
2086 .seq_show = cfqg_print_stat_recursive,
2089 .name = "sectors_recursive",
2090 .seq_show = cfqg_print_stat_sectors_recursive,
2093 .name = "io_service_bytes_recursive",
2094 .private = (unsigned long)&blkcg_policy_cfq,
2095 .seq_show = blkg_print_stat_bytes_recursive,
2098 .name = "io_serviced_recursive",
2099 .private = (unsigned long)&blkcg_policy_cfq,
2100 .seq_show = blkg_print_stat_ios_recursive,
2103 .name = "io_service_time_recursive",
2104 .private = offsetof(struct cfq_group, stats.service_time),
2105 .seq_show = cfqg_print_rwstat_recursive,
2108 .name = "io_wait_time_recursive",
2109 .private = offsetof(struct cfq_group, stats.wait_time),
2110 .seq_show = cfqg_print_rwstat_recursive,
2113 .name = "io_merged_recursive",
2114 .private = offsetof(struct cfq_group, stats.merged),
2115 .seq_show = cfqg_print_rwstat_recursive,
2118 .name = "io_queued_recursive",
2119 .private = offsetof(struct cfq_group, stats.queued),
2120 .seq_show = cfqg_print_rwstat_recursive,
2122 #ifdef CONFIG_DEBUG_BLK_CGROUP
2124 .name = "avg_queue_size",
2125 .seq_show = cfqg_print_avg_queue_size,
2128 .name = "group_wait_time",
2129 .private = offsetof(struct cfq_group, stats.group_wait_time),
2130 .seq_show = cfqg_print_stat,
2133 .name = "idle_time",
2134 .private = offsetof(struct cfq_group, stats.idle_time),
2135 .seq_show = cfqg_print_stat,
2138 .name = "empty_time",
2139 .private = offsetof(struct cfq_group, stats.empty_time),
2140 .seq_show = cfqg_print_stat,
2144 .private = offsetof(struct cfq_group, stats.dequeue),
2145 .seq_show = cfqg_print_stat,
2148 .name = "unaccounted_time",
2149 .private = offsetof(struct cfq_group, stats.unaccounted_time),
2150 .seq_show = cfqg_print_stat,
2152 #endif /* CONFIG_DEBUG_BLK_CGROUP */
2156 static int cfq_print_weight_on_dfl(struct seq_file *sf, void *v)
2158 struct blkcg *blkcg = css_to_blkcg(seq_css(sf));
2159 struct cfq_group_data *cgd = blkcg_to_cfqgd(blkcg);
2161 seq_printf(sf, "default %u\n", cgd->weight);
2162 blkcg_print_blkgs(sf, blkcg, cfqg_prfill_weight_device,
2163 &blkcg_policy_cfq, 0, false);
2167 static ssize_t cfq_set_weight_on_dfl(struct kernfs_open_file *of,
2168 char *buf, size_t nbytes, loff_t off)
2176 /* "WEIGHT" or "default WEIGHT" sets the default weight */
2177 v = simple_strtoull(buf, &endp, 0);
2178 if (*endp == '\0' || sscanf(buf, "default %llu", &v) == 1) {
2179 ret = __cfq_set_weight(of_css(of), v, true, false, false);
2180 return ret ?: nbytes;
2183 /* "MAJ:MIN WEIGHT" */
2184 return __cfqg_set_weight_device(of, buf, nbytes, off, true, false);
2187 static struct cftype cfq_blkcg_files[] = {
2190 .flags = CFTYPE_NOT_ON_ROOT,
2191 .seq_show = cfq_print_weight_on_dfl,
2192 .write = cfq_set_weight_on_dfl,
2197 #else /* GROUP_IOSCHED */
2198 static struct cfq_group *cfq_lookup_cfqg(struct cfq_data *cfqd,
2199 struct blkcg *blkcg)
2201 return cfqd->root_group;
2205 cfq_link_cfqq_cfqg(struct cfq_queue *cfqq, struct cfq_group *cfqg) {
2209 #endif /* GROUP_IOSCHED */
2212 * The cfqd->service_trees holds all pending cfq_queue's that have
2213 * requests waiting to be processed. It is sorted in the order that
2214 * we will service the queues.
2216 static void cfq_service_tree_add(struct cfq_data *cfqd, struct cfq_queue *cfqq,
2219 struct rb_node **p, *parent;
2220 struct cfq_queue *__cfqq;
2222 struct cfq_rb_root *st;
2225 u64 now = ktime_get_ns();
2227 st = st_for(cfqq->cfqg, cfqq_class(cfqq), cfqq_type(cfqq));
2228 if (cfq_class_idle(cfqq)) {
2229 rb_key = CFQ_IDLE_DELAY;
2230 parent = rb_last(&st->rb);
2231 if (parent && parent != &cfqq->rb_node) {
2232 __cfqq = rb_entry(parent, struct cfq_queue, rb_node);
2233 rb_key += __cfqq->rb_key;
2236 } else if (!add_front) {
2238 * Get our rb key offset. Subtract any residual slice
2239 * value carried from last service. A negative resid
2240 * count indicates slice overrun, and this should position
2241 * the next service time further away in the tree.
2243 rb_key = cfq_slice_offset(cfqd, cfqq) + now;
2244 rb_key -= cfqq->slice_resid;
2245 cfqq->slice_resid = 0;
2247 rb_key = -NSEC_PER_SEC;
2248 __cfqq = cfq_rb_first(st);
2249 rb_key += __cfqq ? __cfqq->rb_key : now;
2252 if (!RB_EMPTY_NODE(&cfqq->rb_node)) {
2255 * same position, nothing more to do
2257 if (rb_key == cfqq->rb_key && cfqq->service_tree == st)
2260 cfq_rb_erase(&cfqq->rb_node, cfqq->service_tree);
2261 cfqq->service_tree = NULL;
2266 cfqq->service_tree = st;
2267 p = &st->rb.rb_node;
2270 __cfqq = rb_entry(parent, struct cfq_queue, rb_node);
2273 * sort by key, that represents service time.
2275 if (rb_key < __cfqq->rb_key)
2276 p = &parent->rb_left;
2278 p = &parent->rb_right;
2284 st->left = &cfqq->rb_node;
2286 cfqq->rb_key = rb_key;
2287 rb_link_node(&cfqq->rb_node, parent, p);
2288 rb_insert_color(&cfqq->rb_node, &st->rb);
2290 if (add_front || !new_cfqq)
2292 cfq_group_notify_queue_add(cfqd, cfqq->cfqg);
2295 static struct cfq_queue *
2296 cfq_prio_tree_lookup(struct cfq_data *cfqd, struct rb_root *root,
2297 sector_t sector, struct rb_node **ret_parent,
2298 struct rb_node ***rb_link)
2300 struct rb_node **p, *parent;
2301 struct cfq_queue *cfqq = NULL;
2309 cfqq = rb_entry(parent, struct cfq_queue, p_node);
2312 * Sort strictly based on sector. Smallest to the left,
2313 * largest to the right.
2315 if (sector > blk_rq_pos(cfqq->next_rq))
2316 n = &(*p)->rb_right;
2317 else if (sector < blk_rq_pos(cfqq->next_rq))
2325 *ret_parent = parent;
2331 static void cfq_prio_tree_add(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2333 struct rb_node **p, *parent;
2334 struct cfq_queue *__cfqq;
2337 rb_erase(&cfqq->p_node, cfqq->p_root);
2338 cfqq->p_root = NULL;
2341 if (cfq_class_idle(cfqq))
2346 cfqq->p_root = &cfqd->prio_trees[cfqq->org_ioprio];
2347 __cfqq = cfq_prio_tree_lookup(cfqd, cfqq->p_root,
2348 blk_rq_pos(cfqq->next_rq), &parent, &p);
2350 rb_link_node(&cfqq->p_node, parent, p);
2351 rb_insert_color(&cfqq->p_node, cfqq->p_root);
2353 cfqq->p_root = NULL;
2357 * Update cfqq's position in the service tree.
2359 static void cfq_resort_rr_list(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2362 * Resorting requires the cfqq to be on the RR list already.
2364 if (cfq_cfqq_on_rr(cfqq)) {
2365 cfq_service_tree_add(cfqd, cfqq, 0);
2366 cfq_prio_tree_add(cfqd, cfqq);
2371 * add to busy list of queues for service, trying to be fair in ordering
2372 * the pending list according to last request service
2374 static void cfq_add_cfqq_rr(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2376 cfq_log_cfqq(cfqd, cfqq, "add_to_rr");
2377 BUG_ON(cfq_cfqq_on_rr(cfqq));
2378 cfq_mark_cfqq_on_rr(cfqq);
2379 cfqd->busy_queues++;
2380 if (cfq_cfqq_sync(cfqq))
2381 cfqd->busy_sync_queues++;
2383 cfq_resort_rr_list(cfqd, cfqq);
2387 * Called when the cfqq no longer has requests pending, remove it from
2390 static void cfq_del_cfqq_rr(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2392 cfq_log_cfqq(cfqd, cfqq, "del_from_rr");
2393 BUG_ON(!cfq_cfqq_on_rr(cfqq));
2394 cfq_clear_cfqq_on_rr(cfqq);
2396 if (!RB_EMPTY_NODE(&cfqq->rb_node)) {
2397 cfq_rb_erase(&cfqq->rb_node, cfqq->service_tree);
2398 cfqq->service_tree = NULL;
2401 rb_erase(&cfqq->p_node, cfqq->p_root);
2402 cfqq->p_root = NULL;
2405 cfq_group_notify_queue_del(cfqd, cfqq->cfqg);
2406 BUG_ON(!cfqd->busy_queues);
2407 cfqd->busy_queues--;
2408 if (cfq_cfqq_sync(cfqq))
2409 cfqd->busy_sync_queues--;
2413 * rb tree support functions
2415 static void cfq_del_rq_rb(struct request *rq)
2417 struct cfq_queue *cfqq = RQ_CFQQ(rq);
2418 const int sync = rq_is_sync(rq);
2420 BUG_ON(!cfqq->queued[sync]);
2421 cfqq->queued[sync]--;
2423 elv_rb_del(&cfqq->sort_list, rq);
2425 if (cfq_cfqq_on_rr(cfqq) && RB_EMPTY_ROOT(&cfqq->sort_list)) {
2427 * Queue will be deleted from service tree when we actually
2428 * expire it later. Right now just remove it from prio tree
2432 rb_erase(&cfqq->p_node, cfqq->p_root);
2433 cfqq->p_root = NULL;
2438 static void cfq_add_rq_rb(struct request *rq)
2440 struct cfq_queue *cfqq = RQ_CFQQ(rq);
2441 struct cfq_data *cfqd = cfqq->cfqd;
2442 struct request *prev;
2444 cfqq->queued[rq_is_sync(rq)]++;
2446 elv_rb_add(&cfqq->sort_list, rq);
2448 if (!cfq_cfqq_on_rr(cfqq))
2449 cfq_add_cfqq_rr(cfqd, cfqq);
2452 * check if this request is a better next-serve candidate
2454 prev = cfqq->next_rq;
2455 cfqq->next_rq = cfq_choose_req(cfqd, cfqq->next_rq, rq, cfqd->last_position);
2458 * adjust priority tree position, if ->next_rq changes
2460 if (prev != cfqq->next_rq)
2461 cfq_prio_tree_add(cfqd, cfqq);
2463 BUG_ON(!cfqq->next_rq);
2466 static void cfq_reposition_rq_rb(struct cfq_queue *cfqq, struct request *rq)
2468 elv_rb_del(&cfqq->sort_list, rq);
2469 cfqq->queued[rq_is_sync(rq)]--;
2470 cfqg_stats_update_io_remove(RQ_CFQG(rq), rq->cmd_flags);
2472 cfqg_stats_update_io_add(RQ_CFQG(rq), cfqq->cfqd->serving_group,
2476 static struct request *
2477 cfq_find_rq_fmerge(struct cfq_data *cfqd, struct bio *bio)
2479 struct task_struct *tsk = current;
2480 struct cfq_io_cq *cic;
2481 struct cfq_queue *cfqq;
2483 cic = cfq_cic_lookup(cfqd, tsk->io_context);
2487 cfqq = cic_to_cfqq(cic, op_is_sync(bio->bi_opf));
2489 return elv_rb_find(&cfqq->sort_list, bio_end_sector(bio));
2494 static void cfq_activate_request(struct request_queue *q, struct request *rq)
2496 struct cfq_data *cfqd = q->elevator->elevator_data;
2498 cfqd->rq_in_driver++;
2499 cfq_log_cfqq(cfqd, RQ_CFQQ(rq), "activate rq, drv=%d",
2500 cfqd->rq_in_driver);
2502 cfqd->last_position = blk_rq_pos(rq) + blk_rq_sectors(rq);
2505 static void cfq_deactivate_request(struct request_queue *q, struct request *rq)
2507 struct cfq_data *cfqd = q->elevator->elevator_data;
2509 WARN_ON(!cfqd->rq_in_driver);
2510 cfqd->rq_in_driver--;
2511 cfq_log_cfqq(cfqd, RQ_CFQQ(rq), "deactivate rq, drv=%d",
2512 cfqd->rq_in_driver);
2515 static void cfq_remove_request(struct request *rq)
2517 struct cfq_queue *cfqq = RQ_CFQQ(rq);
2519 if (cfqq->next_rq == rq)
2520 cfqq->next_rq = cfq_find_next_rq(cfqq->cfqd, cfqq, rq);
2522 list_del_init(&rq->queuelist);
2525 cfqq->cfqd->rq_queued--;
2526 cfqg_stats_update_io_remove(RQ_CFQG(rq), rq->cmd_flags);
2527 if (rq->cmd_flags & REQ_PRIO) {
2528 WARN_ON(!cfqq->prio_pending);
2529 cfqq->prio_pending--;
2533 static enum elv_merge cfq_merge(struct request_queue *q, struct request **req,
2536 struct cfq_data *cfqd = q->elevator->elevator_data;
2537 struct request *__rq;
2539 __rq = cfq_find_rq_fmerge(cfqd, bio);
2540 if (__rq && elv_bio_merge_ok(__rq, bio)) {
2542 return ELEVATOR_FRONT_MERGE;
2545 return ELEVATOR_NO_MERGE;
2548 static void cfq_merged_request(struct request_queue *q, struct request *req,
2549 enum elv_merge type)
2551 if (type == ELEVATOR_FRONT_MERGE) {
2552 struct cfq_queue *cfqq = RQ_CFQQ(req);
2554 cfq_reposition_rq_rb(cfqq, req);
2558 static void cfq_bio_merged(struct request_queue *q, struct request *req,
2561 cfqg_stats_update_io_merged(RQ_CFQG(req), bio->bi_opf);
2565 cfq_merged_requests(struct request_queue *q, struct request *rq,
2566 struct request *next)
2568 struct cfq_queue *cfqq = RQ_CFQQ(rq);
2569 struct cfq_data *cfqd = q->elevator->elevator_data;
2572 * reposition in fifo if next is older than rq
2574 if (!list_empty(&rq->queuelist) && !list_empty(&next->queuelist) &&
2575 next->fifo_time < rq->fifo_time &&
2576 cfqq == RQ_CFQQ(next)) {
2577 list_move(&rq->queuelist, &next->queuelist);
2578 rq->fifo_time = next->fifo_time;
2581 if (cfqq->next_rq == next)
2583 cfq_remove_request(next);
2584 cfqg_stats_update_io_merged(RQ_CFQG(rq), next->cmd_flags);
2586 cfqq = RQ_CFQQ(next);
2588 * all requests of this queue are merged to other queues, delete it
2589 * from the service tree. If it's the active_queue,
2590 * cfq_dispatch_requests() will choose to expire it or do idle
2592 if (cfq_cfqq_on_rr(cfqq) && RB_EMPTY_ROOT(&cfqq->sort_list) &&
2593 cfqq != cfqd->active_queue)
2594 cfq_del_cfqq_rr(cfqd, cfqq);
2597 static int cfq_allow_bio_merge(struct request_queue *q, struct request *rq,
2600 struct cfq_data *cfqd = q->elevator->elevator_data;
2601 bool is_sync = op_is_sync(bio->bi_opf);
2602 struct cfq_io_cq *cic;
2603 struct cfq_queue *cfqq;
2606 * Disallow merge of a sync bio into an async request.
2608 if (is_sync && !rq_is_sync(rq))
2612 * Lookup the cfqq that this bio will be queued with and allow
2613 * merge only if rq is queued there.
2615 cic = cfq_cic_lookup(cfqd, current->io_context);
2619 cfqq = cic_to_cfqq(cic, is_sync);
2620 return cfqq == RQ_CFQQ(rq);
2623 static int cfq_allow_rq_merge(struct request_queue *q, struct request *rq,
2624 struct request *next)
2626 return RQ_CFQQ(rq) == RQ_CFQQ(next);
2629 static inline void cfq_del_timer(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2631 hrtimer_try_to_cancel(&cfqd->idle_slice_timer);
2632 cfqg_stats_update_idle_time(cfqq->cfqg);
2635 static void __cfq_set_active_queue(struct cfq_data *cfqd,
2636 struct cfq_queue *cfqq)
2639 cfq_log_cfqq(cfqd, cfqq, "set_active wl_class:%d wl_type:%d",
2640 cfqd->serving_wl_class, cfqd->serving_wl_type);
2641 cfqg_stats_update_avg_queue_size(cfqq->cfqg);
2642 cfqq->slice_start = 0;
2643 cfqq->dispatch_start = ktime_get_ns();
2644 cfqq->allocated_slice = 0;
2645 cfqq->slice_end = 0;
2646 cfqq->slice_dispatch = 0;
2647 cfqq->nr_sectors = 0;
2649 cfq_clear_cfqq_wait_request(cfqq);
2650 cfq_clear_cfqq_must_dispatch(cfqq);
2651 cfq_clear_cfqq_must_alloc_slice(cfqq);
2652 cfq_clear_cfqq_fifo_expire(cfqq);
2653 cfq_mark_cfqq_slice_new(cfqq);
2655 cfq_del_timer(cfqd, cfqq);
2658 cfqd->active_queue = cfqq;
2662 * current cfqq expired its slice (or was too idle), select new one
2665 __cfq_slice_expired(struct cfq_data *cfqd, struct cfq_queue *cfqq,
2668 cfq_log_cfqq(cfqd, cfqq, "slice expired t=%d", timed_out);
2670 if (cfq_cfqq_wait_request(cfqq))
2671 cfq_del_timer(cfqd, cfqq);
2673 cfq_clear_cfqq_wait_request(cfqq);
2674 cfq_clear_cfqq_wait_busy(cfqq);
2677 * If this cfqq is shared between multiple processes, check to
2678 * make sure that those processes are still issuing I/Os within
2679 * the mean seek distance. If not, it may be time to break the
2680 * queues apart again.
2682 if (cfq_cfqq_coop(cfqq) && CFQQ_SEEKY(cfqq))
2683 cfq_mark_cfqq_split_coop(cfqq);
2686 * store what was left of this slice, if the queue idled/timed out
2689 if (cfq_cfqq_slice_new(cfqq))
2690 cfqq->slice_resid = cfq_scaled_cfqq_slice(cfqd, cfqq);
2692 cfqq->slice_resid = cfqq->slice_end - ktime_get_ns();
2693 cfq_log_cfqq(cfqd, cfqq, "resid=%lld", cfqq->slice_resid);
2696 cfq_group_served(cfqd, cfqq->cfqg, cfqq);
2698 if (cfq_cfqq_on_rr(cfqq) && RB_EMPTY_ROOT(&cfqq->sort_list))
2699 cfq_del_cfqq_rr(cfqd, cfqq);
2701 cfq_resort_rr_list(cfqd, cfqq);
2703 if (cfqq == cfqd->active_queue)
2704 cfqd->active_queue = NULL;
2706 if (cfqd->active_cic) {
2707 put_io_context(cfqd->active_cic->icq.ioc);
2708 cfqd->active_cic = NULL;
2712 static inline void cfq_slice_expired(struct cfq_data *cfqd, bool timed_out)
2714 struct cfq_queue *cfqq = cfqd->active_queue;
2717 __cfq_slice_expired(cfqd, cfqq, timed_out);
2721 * Get next queue for service. Unless we have a queue preemption,
2722 * we'll simply select the first cfqq in the service tree.
2724 static struct cfq_queue *cfq_get_next_queue(struct cfq_data *cfqd)
2726 struct cfq_rb_root *st = st_for(cfqd->serving_group,
2727 cfqd->serving_wl_class, cfqd->serving_wl_type);
2729 if (!cfqd->rq_queued)
2732 /* There is nothing to dispatch */
2735 if (RB_EMPTY_ROOT(&st->rb))
2737 return cfq_rb_first(st);
2740 static struct cfq_queue *cfq_get_next_queue_forced(struct cfq_data *cfqd)
2742 struct cfq_group *cfqg;
2743 struct cfq_queue *cfqq;
2745 struct cfq_rb_root *st;
2747 if (!cfqd->rq_queued)
2750 cfqg = cfq_get_next_cfqg(cfqd);
2754 for_each_cfqg_st(cfqg, i, j, st) {
2755 cfqq = cfq_rb_first(st);
2763 * Get and set a new active queue for service.
2765 static struct cfq_queue *cfq_set_active_queue(struct cfq_data *cfqd,
2766 struct cfq_queue *cfqq)
2769 cfqq = cfq_get_next_queue(cfqd);
2771 __cfq_set_active_queue(cfqd, cfqq);
2775 static inline sector_t cfq_dist_from_last(struct cfq_data *cfqd,
2778 if (blk_rq_pos(rq) >= cfqd->last_position)
2779 return blk_rq_pos(rq) - cfqd->last_position;
2781 return cfqd->last_position - blk_rq_pos(rq);
2784 static inline int cfq_rq_close(struct cfq_data *cfqd, struct cfq_queue *cfqq,
2787 return cfq_dist_from_last(cfqd, rq) <= CFQQ_CLOSE_THR;
2790 static struct cfq_queue *cfqq_close(struct cfq_data *cfqd,
2791 struct cfq_queue *cur_cfqq)
2793 struct rb_root *root = &cfqd->prio_trees[cur_cfqq->org_ioprio];
2794 struct rb_node *parent, *node;
2795 struct cfq_queue *__cfqq;
2796 sector_t sector = cfqd->last_position;
2798 if (RB_EMPTY_ROOT(root))
2802 * First, if we find a request starting at the end of the last
2803 * request, choose it.
2805 __cfqq = cfq_prio_tree_lookup(cfqd, root, sector, &parent, NULL);
2810 * If the exact sector wasn't found, the parent of the NULL leaf
2811 * will contain the closest sector.
2813 __cfqq = rb_entry(parent, struct cfq_queue, p_node);
2814 if (cfq_rq_close(cfqd, cur_cfqq, __cfqq->next_rq))
2817 if (blk_rq_pos(__cfqq->next_rq) < sector)
2818 node = rb_next(&__cfqq->p_node);
2820 node = rb_prev(&__cfqq->p_node);
2824 __cfqq = rb_entry(node, struct cfq_queue, p_node);
2825 if (cfq_rq_close(cfqd, cur_cfqq, __cfqq->next_rq))
2833 * cur_cfqq - passed in so that we don't decide that the current queue is
2834 * closely cooperating with itself.
2836 * So, basically we're assuming that that cur_cfqq has dispatched at least
2837 * one request, and that cfqd->last_position reflects a position on the disk
2838 * associated with the I/O issued by cur_cfqq. I'm not sure this is a valid
2841 static struct cfq_queue *cfq_close_cooperator(struct cfq_data *cfqd,
2842 struct cfq_queue *cur_cfqq)
2844 struct cfq_queue *cfqq;
2846 if (cfq_class_idle(cur_cfqq))
2848 if (!cfq_cfqq_sync(cur_cfqq))
2850 if (CFQQ_SEEKY(cur_cfqq))
2854 * Don't search priority tree if it's the only queue in the group.
2856 if (cur_cfqq->cfqg->nr_cfqq == 1)
2860 * We should notice if some of the queues are cooperating, eg
2861 * working closely on the same area of the disk. In that case,
2862 * we can group them together and don't waste time idling.
2864 cfqq = cfqq_close(cfqd, cur_cfqq);
2868 /* If new queue belongs to different cfq_group, don't choose it */
2869 if (cur_cfqq->cfqg != cfqq->cfqg)
2873 * It only makes sense to merge sync queues.
2875 if (!cfq_cfqq_sync(cfqq))
2877 if (CFQQ_SEEKY(cfqq))
2881 * Do not merge queues of different priority classes
2883 if (cfq_class_rt(cfqq) != cfq_class_rt(cur_cfqq))
2890 * Determine whether we should enforce idle window for this queue.
2893 static bool cfq_should_idle(struct cfq_data *cfqd, struct cfq_queue *cfqq)
2895 enum wl_class_t wl_class = cfqq_class(cfqq);
2896 struct cfq_rb_root *st = cfqq->service_tree;
2901 if (!cfqd->cfq_slice_idle)
2904 /* We never do for idle class queues. */
2905 if (wl_class == IDLE_WORKLOAD)
2908 /* We do for queues that were marked with idle window flag. */
2909 if (cfq_cfqq_idle_window(cfqq) &&
2910 !(blk_queue_nonrot(cfqd->queue) && cfqd->hw_tag))
2914 * Otherwise, we do only if they are the last ones
2915 * in their service tree.
2917 if (st->count == 1 && cfq_cfqq_sync(cfqq) &&
2918 !cfq_io_thinktime_big(cfqd, &st->ttime, false))
2920 cfq_log_cfqq(cfqd, cfqq, "Not idling. st->count:%d", st->count);
2924 static void cfq_arm_slice_timer(struct cfq_data *cfqd)
2926 struct cfq_queue *cfqq = cfqd->active_queue;
2927 struct cfq_rb_root *st = cfqq->service_tree;
2928 struct cfq_io_cq *cic;
2929 u64 sl, group_idle = 0;
2930 u64 now = ktime_get_ns();
2933 * SSD device without seek penalty, disable idling. But only do so
2934 * for devices that support queuing, otherwise we still have a problem
2935 * with sync vs async workloads.
2937 if (blk_queue_nonrot(cfqd->queue) && cfqd->hw_tag &&
2938 !cfqd->cfq_group_idle)
2941 WARN_ON(!RB_EMPTY_ROOT(&cfqq->sort_list));
2942 WARN_ON(cfq_cfqq_slice_new(cfqq));
2945 * idle is disabled, either manually or by past process history
2947 if (!cfq_should_idle(cfqd, cfqq)) {
2948 /* no queue idling. Check for group idling */
2949 if (cfqd->cfq_group_idle)
2950 group_idle = cfqd->cfq_group_idle;
2956 * still active requests from this queue, don't idle
2958 if (cfqq->dispatched)
2962 * task has exited, don't wait
2964 cic = cfqd->active_cic;
2965 if (!cic || !atomic_read(&cic->icq.ioc->active_ref))
2969 * If our average think time is larger than the remaining time
2970 * slice, then don't idle. This avoids overrunning the allotted
2973 if (sample_valid(cic->ttime.ttime_samples) &&
2974 (cfqq->slice_end - now < cic->ttime.ttime_mean)) {
2975 cfq_log_cfqq(cfqd, cfqq, "Not idling. think_time:%llu",
2976 cic->ttime.ttime_mean);
2981 * There are other queues in the group or this is the only group and
2982 * it has too big thinktime, don't do group idle.
2985 (cfqq->cfqg->nr_cfqq > 1 ||
2986 cfq_io_thinktime_big(cfqd, &st->ttime, true)))
2989 cfq_mark_cfqq_wait_request(cfqq);
2992 sl = cfqd->cfq_group_idle;
2994 sl = cfqd->cfq_slice_idle;
2996 hrtimer_start(&cfqd->idle_slice_timer, ns_to_ktime(sl),
2998 cfqg_stats_set_start_idle_time(cfqq->cfqg);
2999 cfq_log_cfqq(cfqd, cfqq, "arm_idle: %llu group_idle: %d", sl,
3000 group_idle ? 1 : 0);
3004 * Move request from internal lists to the request queue dispatch list.
3006 static void cfq_dispatch_insert(struct request_queue *q, struct request *rq)
3008 struct cfq_data *cfqd = q->elevator->elevator_data;
3009 struct cfq_queue *cfqq = RQ_CFQQ(rq);
3011 cfq_log_cfqq(cfqd, cfqq, "dispatch_insert");
3013 cfqq->next_rq = cfq_find_next_rq(cfqd, cfqq, rq);
3014 cfq_remove_request(rq);
3016 (RQ_CFQG(rq))->dispatched++;
3017 elv_dispatch_sort(q, rq);
3019 cfqd->rq_in_flight[cfq_cfqq_sync(cfqq)]++;
3020 cfqq->nr_sectors += blk_rq_sectors(rq);
3024 * return expired entry, or NULL to just start from scratch in rbtree
3026 static struct request *cfq_check_fifo(struct cfq_queue *cfqq)
3028 struct request *rq = NULL;
3030 if (cfq_cfqq_fifo_expire(cfqq))
3033 cfq_mark_cfqq_fifo_expire(cfqq);
3035 if (list_empty(&cfqq->fifo))
3038 rq = rq_entry_fifo(cfqq->fifo.next);
3039 if (ktime_get_ns() < rq->fifo_time)
3046 cfq_prio_to_maxrq(struct cfq_data *cfqd, struct cfq_queue *cfqq)
3048 const int base_rq = cfqd->cfq_slice_async_rq;
3050 WARN_ON(cfqq->ioprio >= IOPRIO_BE_NR);
3052 return 2 * base_rq * (IOPRIO_BE_NR - cfqq->ioprio);
3056 * Must be called with the queue_lock held.
3058 static int cfqq_process_refs(struct cfq_queue *cfqq)
3060 int process_refs, io_refs;
3062 io_refs = cfqq->allocated[READ] + cfqq->allocated[WRITE];
3063 process_refs = cfqq->ref - io_refs;
3064 BUG_ON(process_refs < 0);
3065 return process_refs;
3068 static void cfq_setup_merge(struct cfq_queue *cfqq, struct cfq_queue *new_cfqq)
3070 int process_refs, new_process_refs;
3071 struct cfq_queue *__cfqq;
3074 * If there are no process references on the new_cfqq, then it is
3075 * unsafe to follow the ->new_cfqq chain as other cfqq's in the
3076 * chain may have dropped their last reference (not just their
3077 * last process reference).
3079 if (!cfqq_process_refs(new_cfqq))
3082 /* Avoid a circular list and skip interim queue merges */
3083 while ((__cfqq = new_cfqq->new_cfqq)) {
3089 process_refs = cfqq_process_refs(cfqq);
3090 new_process_refs = cfqq_process_refs(new_cfqq);
3092 * If the process for the cfqq has gone away, there is no
3093 * sense in merging the queues.
3095 if (process_refs == 0 || new_process_refs == 0)
3099 * Merge in the direction of the lesser amount of work.
3101 if (new_process_refs >= process_refs) {
3102 cfqq->new_cfqq = new_cfqq;
3103 new_cfqq->ref += process_refs;
3105 new_cfqq->new_cfqq = cfqq;
3106 cfqq->ref += new_process_refs;
3110 static enum wl_type_t cfq_choose_wl_type(struct cfq_data *cfqd,
3111 struct cfq_group *cfqg, enum wl_class_t wl_class)
3113 struct cfq_queue *queue;
3115 bool key_valid = false;
3117 enum wl_type_t cur_best = SYNC_NOIDLE_WORKLOAD;
3119 for (i = 0; i <= SYNC_WORKLOAD; ++i) {
3120 /* select the one with lowest rb_key */
3121 queue = cfq_rb_first(st_for(cfqg, wl_class, i));
3123 (!key_valid || queue->rb_key < lowest_key)) {
3124 lowest_key = queue->rb_key;
3134 choose_wl_class_and_type(struct cfq_data *cfqd, struct cfq_group *cfqg)
3138 struct cfq_rb_root *st;
3140 enum wl_class_t original_class = cfqd->serving_wl_class;
3141 u64 now = ktime_get_ns();
3143 /* Choose next priority. RT > BE > IDLE */
3144 if (cfq_group_busy_queues_wl(RT_WORKLOAD, cfqd, cfqg))
3145 cfqd->serving_wl_class = RT_WORKLOAD;
3146 else if (cfq_group_busy_queues_wl(BE_WORKLOAD, cfqd, cfqg))
3147 cfqd->serving_wl_class = BE_WORKLOAD;
3149 cfqd->serving_wl_class = IDLE_WORKLOAD;
3150 cfqd->workload_expires = now + jiffies_to_nsecs(1);
3154 if (original_class != cfqd->serving_wl_class)
3158 * For RT and BE, we have to choose also the type
3159 * (SYNC, SYNC_NOIDLE, ASYNC), and to compute a workload
3162 st = st_for(cfqg, cfqd->serving_wl_class, cfqd->serving_wl_type);
3166 * check workload expiration, and that we still have other queues ready
3168 if (count && !(now > cfqd->workload_expires))
3172 /* otherwise select new workload type */
3173 cfqd->serving_wl_type = cfq_choose_wl_type(cfqd, cfqg,
3174 cfqd->serving_wl_class);
3175 st = st_for(cfqg, cfqd->serving_wl_class, cfqd->serving_wl_type);
3179 * the workload slice is computed as a fraction of target latency
3180 * proportional to the number of queues in that workload, over
3181 * all the queues in the same priority class
3183 group_slice = cfq_group_slice(cfqd, cfqg);
3185 slice = div_u64(group_slice * count,
3186 max_t(unsigned, cfqg->busy_queues_avg[cfqd->serving_wl_class],
3187 cfq_group_busy_queues_wl(cfqd->serving_wl_class, cfqd,
3190 if (cfqd->serving_wl_type == ASYNC_WORKLOAD) {
3194 * Async queues are currently system wide. Just taking
3195 * proportion of queues with-in same group will lead to higher
3196 * async ratio system wide as generally root group is going
3197 * to have higher weight. A more accurate thing would be to
3198 * calculate system wide asnc/sync ratio.
3200 tmp = cfqd->cfq_target_latency *
3201 cfqg_busy_async_queues(cfqd, cfqg);
3202 tmp = div_u64(tmp, cfqd->busy_queues);
3203 slice = min_t(u64, slice, tmp);
3205 /* async workload slice is scaled down according to
3206 * the sync/async slice ratio. */
3207 slice = div64_u64(slice*cfqd->cfq_slice[0], cfqd->cfq_slice[1]);
3209 /* sync workload slice is at least 2 * cfq_slice_idle */
3210 slice = max(slice, 2 * cfqd->cfq_slice_idle);
3212 slice = max_t(u64, slice, CFQ_MIN_TT);
3213 cfq_log(cfqd, "workload slice:%llu", slice);
3214 cfqd->workload_expires = now + slice;
3217 static struct cfq_group *cfq_get_next_cfqg(struct cfq_data *cfqd)
3219 struct cfq_rb_root *st = &cfqd->grp_service_tree;
3220 struct cfq_group *cfqg;
3222 if (RB_EMPTY_ROOT(&st->rb))
3224 cfqg = cfq_rb_first_group(st);
3225 update_min_vdisktime(st);
3229 static void cfq_choose_cfqg(struct cfq_data *cfqd)
3231 struct cfq_group *cfqg = cfq_get_next_cfqg(cfqd);
3232 u64 now = ktime_get_ns();
3234 cfqd->serving_group = cfqg;
3236 /* Restore the workload type data */
3237 if (cfqg->saved_wl_slice) {
3238 cfqd->workload_expires = now + cfqg->saved_wl_slice;
3239 cfqd->serving_wl_type = cfqg->saved_wl_type;
3240 cfqd->serving_wl_class = cfqg->saved_wl_class;
3242 cfqd->workload_expires = now - 1;
3244 choose_wl_class_and_type(cfqd, cfqg);
3248 * Select a queue for service. If we have a current active queue,
3249 * check whether to continue servicing it, or retrieve and set a new one.
3251 static struct cfq_queue *cfq_select_queue(struct cfq_data *cfqd)
3253 struct cfq_queue *cfqq, *new_cfqq = NULL;
3254 u64 now = ktime_get_ns();
3256 cfqq = cfqd->active_queue;
3260 if (!cfqd->rq_queued)
3264 * We were waiting for group to get backlogged. Expire the queue
3266 if (cfq_cfqq_wait_busy(cfqq) && !RB_EMPTY_ROOT(&cfqq->sort_list))
3270 * The active queue has run out of time, expire it and select new.
3272 if (cfq_slice_used(cfqq) && !cfq_cfqq_must_dispatch(cfqq)) {
3274 * If slice had not expired at the completion of last request
3275 * we might not have turned on wait_busy flag. Don't expire
3276 * the queue yet. Allow the group to get backlogged.
3278 * The very fact that we have used the slice, that means we
3279 * have been idling all along on this queue and it should be
3280 * ok to wait for this request to complete.
3282 if (cfqq->cfqg->nr_cfqq == 1 && RB_EMPTY_ROOT(&cfqq->sort_list)
3283 && cfqq->dispatched && cfq_should_idle(cfqd, cfqq)) {
3287 goto check_group_idle;
3291 * The active queue has requests and isn't expired, allow it to
3294 if (!RB_EMPTY_ROOT(&cfqq->sort_list))
3298 * If another queue has a request waiting within our mean seek
3299 * distance, let it run. The expire code will check for close
3300 * cooperators and put the close queue at the front of the service
3301 * tree. If possible, merge the expiring queue with the new cfqq.
3303 new_cfqq = cfq_close_cooperator(cfqd, cfqq);
3305 if (!cfqq->new_cfqq)
3306 cfq_setup_merge(cfqq, new_cfqq);
3311 * No requests pending. If the active queue still has requests in
3312 * flight or is idling for a new request, allow either of these
3313 * conditions to happen (or time out) before selecting a new queue.
3315 if (hrtimer_active(&cfqd->idle_slice_timer)) {
3321 * This is a deep seek queue, but the device is much faster than
3322 * the queue can deliver, don't idle
3324 if (CFQQ_SEEKY(cfqq) && cfq_cfqq_idle_window(cfqq) &&
3325 (cfq_cfqq_slice_new(cfqq) ||
3326 (cfqq->slice_end - now > now - cfqq->slice_start))) {
3327 cfq_clear_cfqq_deep(cfqq);
3328 cfq_clear_cfqq_idle_window(cfqq);
3331 if (cfqq->dispatched && cfq_should_idle(cfqd, cfqq)) {
3337 * If group idle is enabled and there are requests dispatched from
3338 * this group, wait for requests to complete.
3341 if (cfqd->cfq_group_idle && cfqq->cfqg->nr_cfqq == 1 &&
3342 cfqq->cfqg->dispatched &&
3343 !cfq_io_thinktime_big(cfqd, &cfqq->cfqg->ttime, true)) {
3349 cfq_slice_expired(cfqd, 0);
3352 * Current queue expired. Check if we have to switch to a new
3356 cfq_choose_cfqg(cfqd);
3358 cfqq = cfq_set_active_queue(cfqd, new_cfqq);
3363 static int __cfq_forced_dispatch_cfqq(struct cfq_queue *cfqq)
3367 while (cfqq->next_rq) {
3368 cfq_dispatch_insert(cfqq->cfqd->queue, cfqq->next_rq);
3372 BUG_ON(!list_empty(&cfqq->fifo));
3374 /* By default cfqq is not expired if it is empty. Do it explicitly */
3375 __cfq_slice_expired(cfqq->cfqd, cfqq, 0);
3380 * Drain our current requests. Used for barriers and when switching
3381 * io schedulers on-the-fly.
3383 static int cfq_forced_dispatch(struct cfq_data *cfqd)
3385 struct cfq_queue *cfqq;
3388 /* Expire the timeslice of the current active queue first */
3389 cfq_slice_expired(cfqd, 0);
3390 while ((cfqq = cfq_get_next_queue_forced(cfqd)) != NULL) {
3391 __cfq_set_active_queue(cfqd, cfqq);
3392 dispatched += __cfq_forced_dispatch_cfqq(cfqq);
3395 BUG_ON(cfqd->busy_queues);
3397 cfq_log(cfqd, "forced_dispatch=%d", dispatched);
3401 static inline bool cfq_slice_used_soon(struct cfq_data *cfqd,
3402 struct cfq_queue *cfqq)
3404 u64 now = ktime_get_ns();
3406 /* the queue hasn't finished any request, can't estimate */
3407 if (cfq_cfqq_slice_new(cfqq))
3409 if (now + cfqd->cfq_slice_idle * cfqq->dispatched > cfqq->slice_end)
3415 static bool cfq_may_dispatch(struct cfq_data *cfqd, struct cfq_queue *cfqq)
3417 unsigned int max_dispatch;
3419 if (cfq_cfqq_must_dispatch(cfqq))
3423 * Drain async requests before we start sync IO
3425 if (cfq_should_idle(cfqd, cfqq) && cfqd->rq_in_flight[BLK_RW_ASYNC])
3429 * If this is an async queue and we have sync IO in flight, let it wait
3431 if (cfqd->rq_in_flight[BLK_RW_SYNC] && !cfq_cfqq_sync(cfqq))
3434 max_dispatch = max_t(unsigned int, cfqd->cfq_quantum / 2, 1);
3435 if (cfq_class_idle(cfqq))
3439 * Does this cfqq already have too much IO in flight?
3441 if (cfqq->dispatched >= max_dispatch) {
3442 bool promote_sync = false;
3444 * idle queue must always only have a single IO in flight
3446 if (cfq_class_idle(cfqq))
3450 * If there is only one sync queue
3451 * we can ignore async queue here and give the sync
3452 * queue no dispatch limit. The reason is a sync queue can
3453 * preempt async queue, limiting the sync queue doesn't make
3454 * sense. This is useful for aiostress test.
3456 if (cfq_cfqq_sync(cfqq) && cfqd->busy_sync_queues == 1)
3457 promote_sync = true;
3460 * We have other queues, don't allow more IO from this one
3462 if (cfqd->busy_queues > 1 && cfq_slice_used_soon(cfqd, cfqq) &&
3467 * Sole queue user, no limit
3469 if (cfqd->busy_queues == 1 || promote_sync)
3473 * Normally we start throttling cfqq when cfq_quantum/2
3474 * requests have been dispatched. But we can drive
3475 * deeper queue depths at the beginning of slice
3476 * subjected to upper limit of cfq_quantum.
3478 max_dispatch = cfqd->cfq_quantum;
3482 * Async queues must wait a bit before being allowed dispatch.
3483 * We also ramp up the dispatch depth gradually for async IO,
3484 * based on the last sync IO we serviced
3486 if (!cfq_cfqq_sync(cfqq) && cfqd->cfq_latency) {
3487 u64 last_sync = ktime_get_ns() - cfqd->last_delayed_sync;
3490 depth = div64_u64(last_sync, cfqd->cfq_slice[1]);
3491 if (!depth && !cfqq->dispatched)
3493 if (depth < max_dispatch)
3494 max_dispatch = depth;
3498 * If we're below the current max, allow a dispatch
3500 return cfqq->dispatched < max_dispatch;
3504 * Dispatch a request from cfqq, moving them to the request queue
3507 static bool cfq_dispatch_request(struct cfq_data *cfqd, struct cfq_queue *cfqq)
3511 BUG_ON(RB_EMPTY_ROOT(&cfqq->sort_list));
3513 rq = cfq_check_fifo(cfqq);
3515 cfq_mark_cfqq_must_dispatch(cfqq);
3517 if (!cfq_may_dispatch(cfqd, cfqq))
3521 * follow expired path, else get first next available
3526 cfq_log_cfqq(cfqq->cfqd, cfqq, "fifo=%p", rq);
3529 * insert request into driver dispatch list
3531 cfq_dispatch_insert(cfqd->queue, rq);
3533 if (!cfqd->active_cic) {
3534 struct cfq_io_cq *cic = RQ_CIC(rq);
3536 atomic_long_inc(&cic->icq.ioc->refcount);
3537 cfqd->active_cic = cic;
3544 * Find the cfqq that we need to service and move a request from that to the
3547 static int cfq_dispatch_requests(struct request_queue *q, int force)
3549 struct cfq_data *cfqd = q->elevator->elevator_data;
3550 struct cfq_queue *cfqq;
3552 if (!cfqd->busy_queues)
3555 if (unlikely(force))
3556 return cfq_forced_dispatch(cfqd);
3558 cfqq = cfq_select_queue(cfqd);
3563 * Dispatch a request from this cfqq, if it is allowed
3565 if (!cfq_dispatch_request(cfqd, cfqq))
3568 cfqq->slice_dispatch++;
3569 cfq_clear_cfqq_must_dispatch(cfqq);
3572 * expire an async queue immediately if it has used up its slice. idle
3573 * queue always expire after 1 dispatch round.
3575 if (cfqd->busy_queues > 1 && ((!cfq_cfqq_sync(cfqq) &&
3576 cfqq->slice_dispatch >= cfq_prio_to_maxrq(cfqd, cfqq)) ||
3577 cfq_class_idle(cfqq))) {
3578 cfqq->slice_end = ktime_get_ns() + 1;
3579 cfq_slice_expired(cfqd, 0);
3582 cfq_log_cfqq(cfqd, cfqq, "dispatched a request");
3587 * task holds one reference to the queue, dropped when task exits. each rq
3588 * in-flight on this queue also holds a reference, dropped when rq is freed.
3590 * Each cfq queue took a reference on the parent group. Drop it now.
3591 * queue lock must be held here.
3593 static void cfq_put_queue(struct cfq_queue *cfqq)
3595 struct cfq_data *cfqd = cfqq->cfqd;
3596 struct cfq_group *cfqg;
3598 BUG_ON(cfqq->ref <= 0);
3604 cfq_log_cfqq(cfqd, cfqq, "put_queue");
3605 BUG_ON(rb_first(&cfqq->sort_list));
3606 BUG_ON(cfqq->allocated[READ] + cfqq->allocated[WRITE]);
3609 if (unlikely(cfqd->active_queue == cfqq)) {
3610 __cfq_slice_expired(cfqd, cfqq, 0);
3611 cfq_schedule_dispatch(cfqd);
3614 BUG_ON(cfq_cfqq_on_rr(cfqq));
3615 kmem_cache_free(cfq_pool, cfqq);
3619 static void cfq_put_cooperator(struct cfq_queue *cfqq)
3621 struct cfq_queue *__cfqq, *next;
3624 * If this queue was scheduled to merge with another queue, be
3625 * sure to drop the reference taken on that queue (and others in
3626 * the merge chain). See cfq_setup_merge and cfq_merge_cfqqs.
3628 __cfqq = cfqq->new_cfqq;
3630 if (__cfqq == cfqq) {
3631 WARN(1, "cfqq->new_cfqq loop detected\n");
3634 next = __cfqq->new_cfqq;
3635 cfq_put_queue(__cfqq);
3640 static void cfq_exit_cfqq(struct cfq_data *cfqd, struct cfq_queue *cfqq)
3642 if (unlikely(cfqq == cfqd->active_queue)) {
3643 __cfq_slice_expired(cfqd, cfqq, 0);
3644 cfq_schedule_dispatch(cfqd);
3647 cfq_put_cooperator(cfqq);
3649 cfq_put_queue(cfqq);
3652 static void cfq_init_icq(struct io_cq *icq)
3654 struct cfq_io_cq *cic = icq_to_cic(icq);
3656 cic->ttime.last_end_request = ktime_get_ns();
3659 static void cfq_exit_icq(struct io_cq *icq)
3661 struct cfq_io_cq *cic = icq_to_cic(icq);
3662 struct cfq_data *cfqd = cic_to_cfqd(cic);
3664 if (cic_to_cfqq(cic, false)) {
3665 cfq_exit_cfqq(cfqd, cic_to_cfqq(cic, false));
3666 cic_set_cfqq(cic, NULL, false);
3669 if (cic_to_cfqq(cic, true)) {
3670 cfq_exit_cfqq(cfqd, cic_to_cfqq(cic, true));
3671 cic_set_cfqq(cic, NULL, true);
3675 static void cfq_init_prio_data(struct cfq_queue *cfqq, struct cfq_io_cq *cic)
3677 struct task_struct *tsk = current;
3680 if (!cfq_cfqq_prio_changed(cfqq))
3683 ioprio_class = IOPRIO_PRIO_CLASS(cic->ioprio);
3684 switch (ioprio_class) {
3686 printk(KERN_ERR "cfq: bad prio %x\n", ioprio_class);
3687 case IOPRIO_CLASS_NONE:
3689 * no prio set, inherit CPU scheduling settings
3691 cfqq->ioprio = task_nice_ioprio(tsk);
3692 cfqq->ioprio_class = task_nice_ioclass(tsk);
3694 case IOPRIO_CLASS_RT:
3695 cfqq->ioprio = IOPRIO_PRIO_DATA(cic->ioprio);
3696 cfqq->ioprio_class = IOPRIO_CLASS_RT;
3698 case IOPRIO_CLASS_BE:
3699 cfqq->ioprio = IOPRIO_PRIO_DATA(cic->ioprio);
3700 cfqq->ioprio_class = IOPRIO_CLASS_BE;
3702 case IOPRIO_CLASS_IDLE:
3703 cfqq->ioprio_class = IOPRIO_CLASS_IDLE;
3705 cfq_clear_cfqq_idle_window(cfqq);
3710 * keep track of original prio settings in case we have to temporarily
3711 * elevate the priority of this queue
3713 cfqq->org_ioprio = cfqq->ioprio;
3714 cfqq->org_ioprio_class = cfqq->ioprio_class;
3715 cfq_clear_cfqq_prio_changed(cfqq);
3718 static void check_ioprio_changed(struct cfq_io_cq *cic, struct bio *bio)
3720 int ioprio = cic->icq.ioc->ioprio;
3721 struct cfq_data *cfqd = cic_to_cfqd(cic);
3722 struct cfq_queue *cfqq;
3725 * Check whether ioprio has changed. The condition may trigger
3726 * spuriously on a newly created cic but there's no harm.
3728 if (unlikely(!cfqd) || likely(cic->ioprio == ioprio))
3731 cfqq = cic_to_cfqq(cic, false);
3733 cfq_put_queue(cfqq);
3734 cfqq = cfq_get_queue(cfqd, BLK_RW_ASYNC, cic, bio);
3735 cic_set_cfqq(cic, cfqq, false);
3738 cfqq = cic_to_cfqq(cic, true);
3740 cfq_mark_cfqq_prio_changed(cfqq);
3742 cic->ioprio = ioprio;
3745 static void cfq_init_cfqq(struct cfq_data *cfqd, struct cfq_queue *cfqq,
3746 pid_t pid, bool is_sync)
3748 RB_CLEAR_NODE(&cfqq->rb_node);
3749 RB_CLEAR_NODE(&cfqq->p_node);
3750 INIT_LIST_HEAD(&cfqq->fifo);
3755 cfq_mark_cfqq_prio_changed(cfqq);
3758 if (!cfq_class_idle(cfqq))
3759 cfq_mark_cfqq_idle_window(cfqq);
3760 cfq_mark_cfqq_sync(cfqq);
3765 #ifdef CONFIG_CFQ_GROUP_IOSCHED
3766 static void check_blkcg_changed(struct cfq_io_cq *cic, struct bio *bio)
3768 struct cfq_data *cfqd = cic_to_cfqd(cic);
3769 struct cfq_queue *cfqq;
3773 serial_nr = bio_blkcg(bio)->css.serial_nr;
3777 * Check whether blkcg has changed. The condition may trigger
3778 * spuriously on a newly created cic but there's no harm.
3780 if (unlikely(!cfqd) || likely(cic->blkcg_serial_nr == serial_nr))
3784 * Drop reference to queues. New queues will be assigned in new
3785 * group upon arrival of fresh requests.
3787 cfqq = cic_to_cfqq(cic, false);
3789 cfq_log_cfqq(cfqd, cfqq, "changed cgroup");
3790 cic_set_cfqq(cic, NULL, false);
3791 cfq_put_queue(cfqq);
3794 cfqq = cic_to_cfqq(cic, true);
3796 cfq_log_cfqq(cfqd, cfqq, "changed cgroup");
3797 cic_set_cfqq(cic, NULL, true);
3798 cfq_put_queue(cfqq);
3801 cic->blkcg_serial_nr = serial_nr;
3804 static inline void check_blkcg_changed(struct cfq_io_cq *cic, struct bio *bio)
3807 #endif /* CONFIG_CFQ_GROUP_IOSCHED */
3809 static struct cfq_queue **
3810 cfq_async_queue_prio(struct cfq_group *cfqg, int ioprio_class, int ioprio)
3812 switch (ioprio_class) {
3813 case IOPRIO_CLASS_RT:
3814 return &cfqg->async_cfqq[0][ioprio];
3815 case IOPRIO_CLASS_NONE:
3816 ioprio = IOPRIO_NORM;
3818 case IOPRIO_CLASS_BE:
3819 return &cfqg->async_cfqq[1][ioprio];
3820 case IOPRIO_CLASS_IDLE:
3821 return &cfqg->async_idle_cfqq;
3827 static struct cfq_queue *
3828 cfq_get_queue(struct cfq_data *cfqd, bool is_sync, struct cfq_io_cq *cic,
3831 int ioprio_class = IOPRIO_PRIO_CLASS(cic->ioprio);
3832 int ioprio = IOPRIO_PRIO_DATA(cic->ioprio);
3833 struct cfq_queue **async_cfqq = NULL;
3834 struct cfq_queue *cfqq;
3835 struct cfq_group *cfqg;
3838 cfqg = cfq_lookup_cfqg(cfqd, bio_blkcg(bio));
3840 cfqq = &cfqd->oom_cfqq;
3845 if (!ioprio_valid(cic->ioprio)) {
3846 struct task_struct *tsk = current;
3847 ioprio = task_nice_ioprio(tsk);
3848 ioprio_class = task_nice_ioclass(tsk);
3850 async_cfqq = cfq_async_queue_prio(cfqg, ioprio_class, ioprio);
3856 cfqq = kmem_cache_alloc_node(cfq_pool,
3857 GFP_NOWAIT | __GFP_ZERO | __GFP_NOWARN,
3860 cfqq = &cfqd->oom_cfqq;
3864 /* cfq_init_cfqq() assumes cfqq->ioprio_class is initialized. */
3865 cfqq->ioprio_class = IOPRIO_CLASS_NONE;
3866 cfq_init_cfqq(cfqd, cfqq, current->pid, is_sync);
3867 cfq_init_prio_data(cfqq, cic);
3868 cfq_link_cfqq_cfqg(cfqq, cfqg);
3869 cfq_log_cfqq(cfqd, cfqq, "alloced");
3872 /* a new async queue is created, pin and remember */
3883 __cfq_update_io_thinktime(struct cfq_ttime *ttime, u64 slice_idle)
3885 u64 elapsed = ktime_get_ns() - ttime->last_end_request;
3886 elapsed = min(elapsed, 2UL * slice_idle);
3888 ttime->ttime_samples = (7*ttime->ttime_samples + 256) / 8;
3889 ttime->ttime_total = div_u64(7*ttime->ttime_total + 256*elapsed, 8);
3890 ttime->ttime_mean = div64_ul(ttime->ttime_total + 128,
3891 ttime->ttime_samples);
3895 cfq_update_io_thinktime(struct cfq_data *cfqd, struct cfq_queue *cfqq,
3896 struct cfq_io_cq *cic)
3898 if (cfq_cfqq_sync(cfqq)) {
3899 __cfq_update_io_thinktime(&cic->ttime, cfqd->cfq_slice_idle);
3900 __cfq_update_io_thinktime(&cfqq->service_tree->ttime,
3901 cfqd->cfq_slice_idle);
3903 #ifdef CONFIG_CFQ_GROUP_IOSCHED
3904 __cfq_update_io_thinktime(&cfqq->cfqg->ttime, cfqd->cfq_group_idle);
3909 cfq_update_io_seektime(struct cfq_data *cfqd, struct cfq_queue *cfqq,
3913 sector_t n_sec = blk_rq_sectors(rq);
3914 if (cfqq->last_request_pos) {
3915 if (cfqq->last_request_pos < blk_rq_pos(rq))
3916 sdist = blk_rq_pos(rq) - cfqq->last_request_pos;
3918 sdist = cfqq->last_request_pos - blk_rq_pos(rq);
3921 cfqq->seek_history <<= 1;
3922 if (blk_queue_nonrot(cfqd->queue))
3923 cfqq->seek_history |= (n_sec < CFQQ_SECT_THR_NONROT);
3925 cfqq->seek_history |= (sdist > CFQQ_SEEK_THR);
3928 static inline bool req_noidle(struct request *req)
3930 return req_op(req) == REQ_OP_WRITE &&
3931 (req->cmd_flags & (REQ_SYNC | REQ_IDLE)) == REQ_SYNC;
3935 * Disable idle window if the process thinks too long or seeks so much that
3939 cfq_update_idle_window(struct cfq_data *cfqd, struct cfq_queue *cfqq,
3940 struct cfq_io_cq *cic)
3942 int old_idle, enable_idle;
3945 * Don't idle for async or idle io prio class
3947 if (!cfq_cfqq_sync(cfqq) || cfq_class_idle(cfqq))
3950 enable_idle = old_idle = cfq_cfqq_idle_window(cfqq);
3952 if (cfqq->queued[0] + cfqq->queued[1] >= 4)
3953 cfq_mark_cfqq_deep(cfqq);
3955 if (cfqq->next_rq && req_noidle(cfqq->next_rq))
3957 else if (!atomic_read(&cic->icq.ioc->active_ref) ||
3958 !cfqd->cfq_slice_idle ||
3959 (!cfq_cfqq_deep(cfqq) && CFQQ_SEEKY(cfqq)))
3961 else if (sample_valid(cic->ttime.ttime_samples)) {
3962 if (cic->ttime.ttime_mean > cfqd->cfq_slice_idle)
3968 if (old_idle != enable_idle) {
3969 cfq_log_cfqq(cfqd, cfqq, "idle=%d", enable_idle);
3971 cfq_mark_cfqq_idle_window(cfqq);
3973 cfq_clear_cfqq_idle_window(cfqq);
3978 * Check if new_cfqq should preempt the currently active queue. Return 0 for
3979 * no or if we aren't sure, a 1 will cause a preempt.
3982 cfq_should_preempt(struct cfq_data *cfqd, struct cfq_queue *new_cfqq,
3985 struct cfq_queue *cfqq;
3987 cfqq = cfqd->active_queue;
3991 if (cfq_class_idle(new_cfqq))
3994 if (cfq_class_idle(cfqq))
3998 * Don't allow a non-RT request to preempt an ongoing RT cfqq timeslice.
4000 if (cfq_class_rt(cfqq) && !cfq_class_rt(new_cfqq))
4004 * if the new request is sync, but the currently running queue is
4005 * not, let the sync request have priority.
4007 if (rq_is_sync(rq) && !cfq_cfqq_sync(cfqq) && !cfq_cfqq_must_dispatch(cfqq))
4011 * Treat ancestors of current cgroup the same way as current cgroup.
4012 * For anybody else we disallow preemption to guarantee service
4013 * fairness among cgroups.
4015 if (!cfqg_is_descendant(cfqq->cfqg, new_cfqq->cfqg))
4018 if (cfq_slice_used(cfqq))
4022 * Allow an RT request to pre-empt an ongoing non-RT cfqq timeslice.
4024 if (cfq_class_rt(new_cfqq) && !cfq_class_rt(cfqq))
4027 WARN_ON_ONCE(cfqq->ioprio_class != new_cfqq->ioprio_class);
4028 /* Allow preemption only if we are idling on sync-noidle tree */
4029 if (cfqd->serving_wl_type == SYNC_NOIDLE_WORKLOAD &&
4030 cfqq_type(new_cfqq) == SYNC_NOIDLE_WORKLOAD &&
4031 RB_EMPTY_ROOT(&cfqq->sort_list))
4035 * So both queues are sync. Let the new request get disk time if
4036 * it's a metadata request and the current queue is doing regular IO.
4038 if ((rq->cmd_flags & REQ_PRIO) && !cfqq->prio_pending)
4041 /* An idle queue should not be idle now for some reason */
4042 if (RB_EMPTY_ROOT(&cfqq->sort_list) && !cfq_should_idle(cfqd, cfqq))
4045 if (!cfqd->active_cic || !cfq_cfqq_wait_request(cfqq))
4049 * if this request is as-good as one we would expect from the
4050 * current cfqq, let it preempt
4052 if (cfq_rq_close(cfqd, cfqq, rq))
4059 * cfqq preempts the active queue. if we allowed preempt with no slice left,
4060 * let it have half of its nominal slice.
4062 static void cfq_preempt_queue(struct cfq_data *cfqd, struct cfq_queue *cfqq)
4064 enum wl_type_t old_type = cfqq_type(cfqd->active_queue);
4066 cfq_log_cfqq(cfqd, cfqq, "preempt");
4067 cfq_slice_expired(cfqd, 1);
4070 * workload type is changed, don't save slice, otherwise preempt
4073 if (old_type != cfqq_type(cfqq))
4074 cfqq->cfqg->saved_wl_slice = 0;
4077 * Put the new queue at the front of the of the current list,
4078 * so we know that it will be selected next.
4080 BUG_ON(!cfq_cfqq_on_rr(cfqq));
4082 cfq_service_tree_add(cfqd, cfqq, 1);
4084 cfqq->slice_end = 0;
4085 cfq_mark_cfqq_slice_new(cfqq);
4089 * Called when a new fs request (rq) is added (to cfqq). Check if there's
4090 * something we should do about it
4093 cfq_rq_enqueued(struct cfq_data *cfqd, struct cfq_queue *cfqq,
4096 struct cfq_io_cq *cic = RQ_CIC(rq);
4099 if (rq->cmd_flags & REQ_PRIO)
4100 cfqq->prio_pending++;
4102 cfq_update_io_thinktime(cfqd, cfqq, cic);
4103 cfq_update_io_seektime(cfqd, cfqq, rq);
4104 cfq_update_idle_window(cfqd, cfqq, cic);
4106 cfqq->last_request_pos = blk_rq_pos(rq) + blk_rq_sectors(rq);
4108 if (cfqq == cfqd->active_queue) {
4110 * Remember that we saw a request from this process, but
4111 * don't start queuing just yet. Otherwise we risk seeing lots
4112 * of tiny requests, because we disrupt the normal plugging
4113 * and merging. If the request is already larger than a single
4114 * page, let it rip immediately. For that case we assume that
4115 * merging is already done. Ditto for a busy system that
4116 * has other work pending, don't risk delaying until the
4117 * idle timer unplug to continue working.
4119 if (cfq_cfqq_wait_request(cfqq)) {
4120 if (blk_rq_bytes(rq) > PAGE_SIZE ||
4121 cfqd->busy_queues > 1) {
4122 cfq_del_timer(cfqd, cfqq);
4123 cfq_clear_cfqq_wait_request(cfqq);
4124 __blk_run_queue(cfqd->queue);
4126 cfqg_stats_update_idle_time(cfqq->cfqg);
4127 cfq_mark_cfqq_must_dispatch(cfqq);
4130 } else if (cfq_should_preempt(cfqd, cfqq, rq)) {
4132 * not the active queue - expire current slice if it is
4133 * idle and has expired it's mean thinktime or this new queue
4134 * has some old slice time left and is of higher priority or
4135 * this new queue is RT and the current one is BE
4137 cfq_preempt_queue(cfqd, cfqq);
4138 __blk_run_queue(cfqd->queue);
4142 static void cfq_insert_request(struct request_queue *q, struct request *rq)
4144 struct cfq_data *cfqd = q->elevator->elevator_data;
4145 struct cfq_queue *cfqq = RQ_CFQQ(rq);
4147 cfq_log_cfqq(cfqd, cfqq, "insert_request");
4148 cfq_init_prio_data(cfqq, RQ_CIC(rq));
4150 rq->fifo_time = ktime_get_ns() + cfqd->cfq_fifo_expire[rq_is_sync(rq)];
4151 list_add_tail(&rq->queuelist, &cfqq->fifo);
4153 cfqg_stats_update_io_add(RQ_CFQG(rq), cfqd->serving_group,
4155 cfq_rq_enqueued(cfqd, cfqq, rq);
4159 * Update hw_tag based on peak queue depth over 50 samples under
4162 static void cfq_update_hw_tag(struct cfq_data *cfqd)
4164 struct cfq_queue *cfqq = cfqd->active_queue;
4166 if (cfqd->rq_in_driver > cfqd->hw_tag_est_depth)
4167 cfqd->hw_tag_est_depth = cfqd->rq_in_driver;
4169 if (cfqd->hw_tag == 1)
4172 if (cfqd->rq_queued <= CFQ_HW_QUEUE_MIN &&
4173 cfqd->rq_in_driver <= CFQ_HW_QUEUE_MIN)
4177 * If active queue hasn't enough requests and can idle, cfq might not
4178 * dispatch sufficient requests to hardware. Don't zero hw_tag in this
4181 if (cfqq && cfq_cfqq_idle_window(cfqq) &&
4182 cfqq->dispatched + cfqq->queued[0] + cfqq->queued[1] <
4183 CFQ_HW_QUEUE_MIN && cfqd->rq_in_driver < CFQ_HW_QUEUE_MIN)
4186 if (cfqd->hw_tag_samples++ < 50)
4189 if (cfqd->hw_tag_est_depth >= CFQ_HW_QUEUE_MIN)
4195 static bool cfq_should_wait_busy(struct cfq_data *cfqd, struct cfq_queue *cfqq)
4197 struct cfq_io_cq *cic = cfqd->active_cic;
4198 u64 now = ktime_get_ns();
4200 /* If the queue already has requests, don't wait */
4201 if (!RB_EMPTY_ROOT(&cfqq->sort_list))
4204 /* If there are other queues in the group, don't wait */
4205 if (cfqq->cfqg->nr_cfqq > 1)
4208 /* the only queue in the group, but think time is big */
4209 if (cfq_io_thinktime_big(cfqd, &cfqq->cfqg->ttime, true))
4212 if (cfq_slice_used(cfqq))
4215 /* if slice left is less than think time, wait busy */
4216 if (cic && sample_valid(cic->ttime.ttime_samples)
4217 && (cfqq->slice_end - now < cic->ttime.ttime_mean))
4221 * If think times is less than a jiffy than ttime_mean=0 and above
4222 * will not be true. It might happen that slice has not expired yet
4223 * but will expire soon (4-5 ns) during select_queue(). To cover the
4224 * case where think time is less than a jiffy, mark the queue wait
4225 * busy if only 1 jiffy is left in the slice.
4227 if (cfqq->slice_end - now <= jiffies_to_nsecs(1))
4233 static void cfq_completed_request(struct request_queue *q, struct request *rq)
4235 struct cfq_queue *cfqq = RQ_CFQQ(rq);
4236 struct cfq_data *cfqd = cfqq->cfqd;
4237 const int sync = rq_is_sync(rq);
4238 u64 now = ktime_get_ns();
4240 cfq_log_cfqq(cfqd, cfqq, "complete rqnoidle %d", req_noidle(rq));
4242 cfq_update_hw_tag(cfqd);
4244 WARN_ON(!cfqd->rq_in_driver);
4245 WARN_ON(!cfqq->dispatched);
4246 cfqd->rq_in_driver--;
4248 (RQ_CFQG(rq))->dispatched--;
4249 cfqg_stats_update_completion(cfqq->cfqg, rq_start_time_ns(rq),
4250 rq_io_start_time_ns(rq), rq->cmd_flags);
4252 cfqd->rq_in_flight[cfq_cfqq_sync(cfqq)]--;
4255 struct cfq_rb_root *st;
4257 RQ_CIC(rq)->ttime.last_end_request = now;
4259 if (cfq_cfqq_on_rr(cfqq))
4260 st = cfqq->service_tree;
4262 st = st_for(cfqq->cfqg, cfqq_class(cfqq),
4265 st->ttime.last_end_request = now;
4267 * We have to do this check in jiffies since start_time is in
4268 * jiffies and it is not trivial to convert to ns. If
4269 * cfq_fifo_expire[1] ever comes close to 1 jiffie, this test
4270 * will become problematic but so far we are fine (the default
4273 if (!time_after(rq->start_time +
4274 nsecs_to_jiffies(cfqd->cfq_fifo_expire[1]),
4276 cfqd->last_delayed_sync = now;
4279 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4280 cfqq->cfqg->ttime.last_end_request = now;
4284 * If this is the active queue, check if it needs to be expired,
4285 * or if we want to idle in case it has no pending requests.
4287 if (cfqd->active_queue == cfqq) {
4288 const bool cfqq_empty = RB_EMPTY_ROOT(&cfqq->sort_list);
4290 if (cfq_cfqq_slice_new(cfqq)) {
4291 cfq_set_prio_slice(cfqd, cfqq);
4292 cfq_clear_cfqq_slice_new(cfqq);
4296 * Should we wait for next request to come in before we expire
4299 if (cfq_should_wait_busy(cfqd, cfqq)) {
4300 u64 extend_sl = cfqd->cfq_slice_idle;
4301 if (!cfqd->cfq_slice_idle)
4302 extend_sl = cfqd->cfq_group_idle;
4303 cfqq->slice_end = now + extend_sl;
4304 cfq_mark_cfqq_wait_busy(cfqq);
4305 cfq_log_cfqq(cfqd, cfqq, "will busy wait");
4309 * Idling is not enabled on:
4311 * - idle-priority queues
4313 * - queues with still some requests queued
4314 * - when there is a close cooperator
4316 if (cfq_slice_used(cfqq) || cfq_class_idle(cfqq))
4317 cfq_slice_expired(cfqd, 1);
4318 else if (sync && cfqq_empty &&
4319 !cfq_close_cooperator(cfqd, cfqq)) {
4320 cfq_arm_slice_timer(cfqd);
4324 if (!cfqd->rq_in_driver)
4325 cfq_schedule_dispatch(cfqd);
4328 static void cfqq_boost_on_prio(struct cfq_queue *cfqq, unsigned int op)
4331 * If REQ_PRIO is set, boost class and prio level, if it's below
4332 * BE/NORM. If prio is not set, restore the potentially boosted
4335 if (!(op & REQ_PRIO)) {
4336 cfqq->ioprio_class = cfqq->org_ioprio_class;
4337 cfqq->ioprio = cfqq->org_ioprio;
4339 if (cfq_class_idle(cfqq))
4340 cfqq->ioprio_class = IOPRIO_CLASS_BE;
4341 if (cfqq->ioprio > IOPRIO_NORM)
4342 cfqq->ioprio = IOPRIO_NORM;
4346 static inline int __cfq_may_queue(struct cfq_queue *cfqq)
4348 if (cfq_cfqq_wait_request(cfqq) && !cfq_cfqq_must_alloc_slice(cfqq)) {
4349 cfq_mark_cfqq_must_alloc_slice(cfqq);
4350 return ELV_MQUEUE_MUST;
4353 return ELV_MQUEUE_MAY;
4356 static int cfq_may_queue(struct request_queue *q, unsigned int op)
4358 struct cfq_data *cfqd = q->elevator->elevator_data;
4359 struct task_struct *tsk = current;
4360 struct cfq_io_cq *cic;
4361 struct cfq_queue *cfqq;
4364 * don't force setup of a queue from here, as a call to may_queue
4365 * does not necessarily imply that a request actually will be queued.
4366 * so just lookup a possibly existing queue, or return 'may queue'
4369 cic = cfq_cic_lookup(cfqd, tsk->io_context);
4371 return ELV_MQUEUE_MAY;
4373 cfqq = cic_to_cfqq(cic, op_is_sync(op));
4375 cfq_init_prio_data(cfqq, cic);
4376 cfqq_boost_on_prio(cfqq, op);
4378 return __cfq_may_queue(cfqq);
4381 return ELV_MQUEUE_MAY;
4385 * queue lock held here
4387 static void cfq_put_request(struct request *rq)
4389 struct cfq_queue *cfqq = RQ_CFQQ(rq);
4392 const int rw = rq_data_dir(rq);
4394 BUG_ON(!cfqq->allocated[rw]);
4395 cfqq->allocated[rw]--;
4397 /* Put down rq reference on cfqg */
4398 cfqg_put(RQ_CFQG(rq));
4399 rq->elv.priv[0] = NULL;
4400 rq->elv.priv[1] = NULL;
4402 cfq_put_queue(cfqq);
4406 static struct cfq_queue *
4407 cfq_merge_cfqqs(struct cfq_data *cfqd, struct cfq_io_cq *cic,
4408 struct cfq_queue *cfqq)
4410 cfq_log_cfqq(cfqd, cfqq, "merging with queue %p", cfqq->new_cfqq);
4411 cic_set_cfqq(cic, cfqq->new_cfqq, 1);
4412 cfq_mark_cfqq_coop(cfqq->new_cfqq);
4413 cfq_put_queue(cfqq);
4414 return cic_to_cfqq(cic, 1);
4418 * Returns NULL if a new cfqq should be allocated, or the old cfqq if this
4419 * was the last process referring to said cfqq.
4421 static struct cfq_queue *
4422 split_cfqq(struct cfq_io_cq *cic, struct cfq_queue *cfqq)
4424 if (cfqq_process_refs(cfqq) == 1) {
4425 cfqq->pid = current->pid;
4426 cfq_clear_cfqq_coop(cfqq);
4427 cfq_clear_cfqq_split_coop(cfqq);
4431 cic_set_cfqq(cic, NULL, 1);
4433 cfq_put_cooperator(cfqq);
4435 cfq_put_queue(cfqq);
4439 * Allocate cfq data structures associated with this request.
4442 cfq_set_request(struct request_queue *q, struct request *rq, struct bio *bio,
4445 struct cfq_data *cfqd = q->elevator->elevator_data;
4446 struct cfq_io_cq *cic = icq_to_cic(rq->elv.icq);
4447 const int rw = rq_data_dir(rq);
4448 const bool is_sync = rq_is_sync(rq);
4449 struct cfq_queue *cfqq;
4451 spin_lock_irq(q->queue_lock);
4453 check_ioprio_changed(cic, bio);
4454 check_blkcg_changed(cic, bio);
4456 cfqq = cic_to_cfqq(cic, is_sync);
4457 if (!cfqq || cfqq == &cfqd->oom_cfqq) {
4459 cfq_put_queue(cfqq);
4460 cfqq = cfq_get_queue(cfqd, is_sync, cic, bio);
4461 cic_set_cfqq(cic, cfqq, is_sync);
4464 * If the queue was seeky for too long, break it apart.
4466 if (cfq_cfqq_coop(cfqq) && cfq_cfqq_split_coop(cfqq)) {
4467 cfq_log_cfqq(cfqd, cfqq, "breaking apart cfqq");
4468 cfqq = split_cfqq(cic, cfqq);
4474 * Check to see if this queue is scheduled to merge with
4475 * another, closely cooperating queue. The merging of
4476 * queues happens here as it must be done in process context.
4477 * The reference on new_cfqq was taken in merge_cfqqs.
4480 cfqq = cfq_merge_cfqqs(cfqd, cic, cfqq);
4483 cfqq->allocated[rw]++;
4486 cfqg_get(cfqq->cfqg);
4487 rq->elv.priv[0] = cfqq;
4488 rq->elv.priv[1] = cfqq->cfqg;
4489 spin_unlock_irq(q->queue_lock);
4494 static void cfq_kick_queue(struct work_struct *work)
4496 struct cfq_data *cfqd =
4497 container_of(work, struct cfq_data, unplug_work);
4498 struct request_queue *q = cfqd->queue;
4500 spin_lock_irq(q->queue_lock);
4501 __blk_run_queue(cfqd->queue);
4502 spin_unlock_irq(q->queue_lock);
4506 * Timer running if the active_queue is currently idling inside its time slice
4508 static enum hrtimer_restart cfq_idle_slice_timer(struct hrtimer *timer)
4510 struct cfq_data *cfqd = container_of(timer, struct cfq_data,
4512 struct cfq_queue *cfqq;
4513 unsigned long flags;
4516 cfq_log(cfqd, "idle timer fired");
4518 spin_lock_irqsave(cfqd->queue->queue_lock, flags);
4520 cfqq = cfqd->active_queue;
4525 * We saw a request before the queue expired, let it through
4527 if (cfq_cfqq_must_dispatch(cfqq))
4533 if (cfq_slice_used(cfqq))
4537 * only expire and reinvoke request handler, if there are
4538 * other queues with pending requests
4540 if (!cfqd->busy_queues)
4544 * not expired and it has a request pending, let it dispatch
4546 if (!RB_EMPTY_ROOT(&cfqq->sort_list))
4550 * Queue depth flag is reset only when the idle didn't succeed
4552 cfq_clear_cfqq_deep(cfqq);
4555 cfq_slice_expired(cfqd, timed_out);
4557 cfq_schedule_dispatch(cfqd);
4559 spin_unlock_irqrestore(cfqd->queue->queue_lock, flags);
4560 return HRTIMER_NORESTART;
4563 static void cfq_shutdown_timer_wq(struct cfq_data *cfqd)
4565 hrtimer_cancel(&cfqd->idle_slice_timer);
4566 cancel_work_sync(&cfqd->unplug_work);
4569 static void cfq_exit_queue(struct elevator_queue *e)
4571 struct cfq_data *cfqd = e->elevator_data;
4572 struct request_queue *q = cfqd->queue;
4574 cfq_shutdown_timer_wq(cfqd);
4576 spin_lock_irq(q->queue_lock);
4578 if (cfqd->active_queue)
4579 __cfq_slice_expired(cfqd, cfqd->active_queue, 0);
4581 spin_unlock_irq(q->queue_lock);
4583 cfq_shutdown_timer_wq(cfqd);
4585 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4586 blkcg_deactivate_policy(q, &blkcg_policy_cfq);
4588 kfree(cfqd->root_group);
4593 static int cfq_init_queue(struct request_queue *q, struct elevator_type *e)
4595 struct cfq_data *cfqd;
4596 struct blkcg_gq *blkg __maybe_unused;
4598 struct elevator_queue *eq;
4600 eq = elevator_alloc(q, e);
4604 cfqd = kzalloc_node(sizeof(*cfqd), GFP_KERNEL, q->node);
4606 kobject_put(&eq->kobj);
4609 eq->elevator_data = cfqd;
4612 spin_lock_irq(q->queue_lock);
4614 spin_unlock_irq(q->queue_lock);
4616 /* Init root service tree */
4617 cfqd->grp_service_tree = CFQ_RB_ROOT;
4619 /* Init root group and prefer root group over other groups by default */
4620 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4621 ret = blkcg_activate_policy(q, &blkcg_policy_cfq);
4625 cfqd->root_group = blkg_to_cfqg(q->root_blkg);
4628 cfqd->root_group = kzalloc_node(sizeof(*cfqd->root_group),
4629 GFP_KERNEL, cfqd->queue->node);
4630 if (!cfqd->root_group)
4633 cfq_init_cfqg_base(cfqd->root_group);
4634 cfqd->root_group->weight = 2 * CFQ_WEIGHT_LEGACY_DFL;
4635 cfqd->root_group->leaf_weight = 2 * CFQ_WEIGHT_LEGACY_DFL;
4639 * Not strictly needed (since RB_ROOT just clears the node and we
4640 * zeroed cfqd on alloc), but better be safe in case someone decides
4641 * to add magic to the rb code
4643 for (i = 0; i < CFQ_PRIO_LISTS; i++)
4644 cfqd->prio_trees[i] = RB_ROOT;
4647 * Our fallback cfqq if cfq_get_queue() runs into OOM issues.
4648 * Grab a permanent reference to it, so that the normal code flow
4649 * will not attempt to free it. oom_cfqq is linked to root_group
4650 * but shouldn't hold a reference as it'll never be unlinked. Lose
4651 * the reference from linking right away.
4653 cfq_init_cfqq(cfqd, &cfqd->oom_cfqq, 1, 0);
4654 cfqd->oom_cfqq.ref++;
4656 spin_lock_irq(q->queue_lock);
4657 cfq_link_cfqq_cfqg(&cfqd->oom_cfqq, cfqd->root_group);
4658 cfqg_put(cfqd->root_group);
4659 spin_unlock_irq(q->queue_lock);
4661 hrtimer_init(&cfqd->idle_slice_timer, CLOCK_MONOTONIC,
4663 cfqd->idle_slice_timer.function = cfq_idle_slice_timer;
4665 INIT_WORK(&cfqd->unplug_work, cfq_kick_queue);
4667 cfqd->cfq_quantum = cfq_quantum;
4668 cfqd->cfq_fifo_expire[0] = cfq_fifo_expire[0];
4669 cfqd->cfq_fifo_expire[1] = cfq_fifo_expire[1];
4670 cfqd->cfq_back_max = cfq_back_max;
4671 cfqd->cfq_back_penalty = cfq_back_penalty;
4672 cfqd->cfq_slice[0] = cfq_slice_async;
4673 cfqd->cfq_slice[1] = cfq_slice_sync;
4674 cfqd->cfq_target_latency = cfq_target_latency;
4675 cfqd->cfq_slice_async_rq = cfq_slice_async_rq;
4676 cfqd->cfq_slice_idle = cfq_slice_idle;
4677 cfqd->cfq_group_idle = cfq_group_idle;
4678 cfqd->cfq_latency = 1;
4681 * we optimistically start assuming sync ops weren't delayed in last
4682 * second, in order to have larger depth for async operations.
4684 cfqd->last_delayed_sync = ktime_get_ns() - NSEC_PER_SEC;
4689 kobject_put(&eq->kobj);
4693 static void cfq_registered_queue(struct request_queue *q)
4695 struct elevator_queue *e = q->elevator;
4696 struct cfq_data *cfqd = e->elevator_data;
4699 * Default to IOPS mode with no idling for SSDs
4701 if (blk_queue_nonrot(q))
4702 cfqd->cfq_slice_idle = 0;
4703 wbt_disable_default(q);
4707 * sysfs parts below -->
4710 cfq_var_show(unsigned int var, char *page)
4712 return sprintf(page, "%u\n", var);
4716 cfq_var_store(unsigned int *var, const char *page, size_t count)
4718 char *p = (char *) page;
4720 *var = simple_strtoul(p, &p, 10);
4724 #define SHOW_FUNCTION(__FUNC, __VAR, __CONV) \
4725 static ssize_t __FUNC(struct elevator_queue *e, char *page) \
4727 struct cfq_data *cfqd = e->elevator_data; \
4728 u64 __data = __VAR; \
4730 __data = div_u64(__data, NSEC_PER_MSEC); \
4731 return cfq_var_show(__data, (page)); \
4733 SHOW_FUNCTION(cfq_quantum_show, cfqd->cfq_quantum, 0);
4734 SHOW_FUNCTION(cfq_fifo_expire_sync_show, cfqd->cfq_fifo_expire[1], 1);
4735 SHOW_FUNCTION(cfq_fifo_expire_async_show, cfqd->cfq_fifo_expire[0], 1);
4736 SHOW_FUNCTION(cfq_back_seek_max_show, cfqd->cfq_back_max, 0);
4737 SHOW_FUNCTION(cfq_back_seek_penalty_show, cfqd->cfq_back_penalty, 0);
4738 SHOW_FUNCTION(cfq_slice_idle_show, cfqd->cfq_slice_idle, 1);
4739 SHOW_FUNCTION(cfq_group_idle_show, cfqd->cfq_group_idle, 1);
4740 SHOW_FUNCTION(cfq_slice_sync_show, cfqd->cfq_slice[1], 1);
4741 SHOW_FUNCTION(cfq_slice_async_show, cfqd->cfq_slice[0], 1);
4742 SHOW_FUNCTION(cfq_slice_async_rq_show, cfqd->cfq_slice_async_rq, 0);
4743 SHOW_FUNCTION(cfq_low_latency_show, cfqd->cfq_latency, 0);
4744 SHOW_FUNCTION(cfq_target_latency_show, cfqd->cfq_target_latency, 1);
4745 #undef SHOW_FUNCTION
4747 #define USEC_SHOW_FUNCTION(__FUNC, __VAR) \
4748 static ssize_t __FUNC(struct elevator_queue *e, char *page) \
4750 struct cfq_data *cfqd = e->elevator_data; \
4751 u64 __data = __VAR; \
4752 __data = div_u64(__data, NSEC_PER_USEC); \
4753 return cfq_var_show(__data, (page)); \
4755 USEC_SHOW_FUNCTION(cfq_slice_idle_us_show, cfqd->cfq_slice_idle);
4756 USEC_SHOW_FUNCTION(cfq_group_idle_us_show, cfqd->cfq_group_idle);
4757 USEC_SHOW_FUNCTION(cfq_slice_sync_us_show, cfqd->cfq_slice[1]);
4758 USEC_SHOW_FUNCTION(cfq_slice_async_us_show, cfqd->cfq_slice[0]);
4759 USEC_SHOW_FUNCTION(cfq_target_latency_us_show, cfqd->cfq_target_latency);
4760 #undef USEC_SHOW_FUNCTION
4762 #define STORE_FUNCTION(__FUNC, __PTR, MIN, MAX, __CONV) \
4763 static ssize_t __FUNC(struct elevator_queue *e, const char *page, size_t count) \
4765 struct cfq_data *cfqd = e->elevator_data; \
4766 unsigned int __data; \
4767 int ret = cfq_var_store(&__data, (page), count); \
4768 if (__data < (MIN)) \
4770 else if (__data > (MAX)) \
4773 *(__PTR) = (u64)__data * NSEC_PER_MSEC; \
4775 *(__PTR) = __data; \
4778 STORE_FUNCTION(cfq_quantum_store, &cfqd->cfq_quantum, 1, UINT_MAX, 0);
4779 STORE_FUNCTION(cfq_fifo_expire_sync_store, &cfqd->cfq_fifo_expire[1], 1,
4781 STORE_FUNCTION(cfq_fifo_expire_async_store, &cfqd->cfq_fifo_expire[0], 1,
4783 STORE_FUNCTION(cfq_back_seek_max_store, &cfqd->cfq_back_max, 0, UINT_MAX, 0);
4784 STORE_FUNCTION(cfq_back_seek_penalty_store, &cfqd->cfq_back_penalty, 1,
4786 STORE_FUNCTION(cfq_slice_idle_store, &cfqd->cfq_slice_idle, 0, UINT_MAX, 1);
4787 STORE_FUNCTION(cfq_group_idle_store, &cfqd->cfq_group_idle, 0, UINT_MAX, 1);
4788 STORE_FUNCTION(cfq_slice_sync_store, &cfqd->cfq_slice[1], 1, UINT_MAX, 1);
4789 STORE_FUNCTION(cfq_slice_async_store, &cfqd->cfq_slice[0], 1, UINT_MAX, 1);
4790 STORE_FUNCTION(cfq_slice_async_rq_store, &cfqd->cfq_slice_async_rq, 1,
4792 STORE_FUNCTION(cfq_low_latency_store, &cfqd->cfq_latency, 0, 1, 0);
4793 STORE_FUNCTION(cfq_target_latency_store, &cfqd->cfq_target_latency, 1, UINT_MAX, 1);
4794 #undef STORE_FUNCTION
4796 #define USEC_STORE_FUNCTION(__FUNC, __PTR, MIN, MAX) \
4797 static ssize_t __FUNC(struct elevator_queue *e, const char *page, size_t count) \
4799 struct cfq_data *cfqd = e->elevator_data; \
4800 unsigned int __data; \
4801 int ret = cfq_var_store(&__data, (page), count); \
4802 if (__data < (MIN)) \
4804 else if (__data > (MAX)) \
4806 *(__PTR) = (u64)__data * NSEC_PER_USEC; \
4809 USEC_STORE_FUNCTION(cfq_slice_idle_us_store, &cfqd->cfq_slice_idle, 0, UINT_MAX);
4810 USEC_STORE_FUNCTION(cfq_group_idle_us_store, &cfqd->cfq_group_idle, 0, UINT_MAX);
4811 USEC_STORE_FUNCTION(cfq_slice_sync_us_store, &cfqd->cfq_slice[1], 1, UINT_MAX);
4812 USEC_STORE_FUNCTION(cfq_slice_async_us_store, &cfqd->cfq_slice[0], 1, UINT_MAX);
4813 USEC_STORE_FUNCTION(cfq_target_latency_us_store, &cfqd->cfq_target_latency, 1, UINT_MAX);
4814 #undef USEC_STORE_FUNCTION
4816 #define CFQ_ATTR(name) \
4817 __ATTR(name, S_IRUGO|S_IWUSR, cfq_##name##_show, cfq_##name##_store)
4819 static struct elv_fs_entry cfq_attrs[] = {
4821 CFQ_ATTR(fifo_expire_sync),
4822 CFQ_ATTR(fifo_expire_async),
4823 CFQ_ATTR(back_seek_max),
4824 CFQ_ATTR(back_seek_penalty),
4825 CFQ_ATTR(slice_sync),
4826 CFQ_ATTR(slice_sync_us),
4827 CFQ_ATTR(slice_async),
4828 CFQ_ATTR(slice_async_us),
4829 CFQ_ATTR(slice_async_rq),
4830 CFQ_ATTR(slice_idle),
4831 CFQ_ATTR(slice_idle_us),
4832 CFQ_ATTR(group_idle),
4833 CFQ_ATTR(group_idle_us),
4834 CFQ_ATTR(low_latency),
4835 CFQ_ATTR(target_latency),
4836 CFQ_ATTR(target_latency_us),
4840 static struct elevator_type iosched_cfq = {
4842 .elevator_merge_fn = cfq_merge,
4843 .elevator_merged_fn = cfq_merged_request,
4844 .elevator_merge_req_fn = cfq_merged_requests,
4845 .elevator_allow_bio_merge_fn = cfq_allow_bio_merge,
4846 .elevator_allow_rq_merge_fn = cfq_allow_rq_merge,
4847 .elevator_bio_merged_fn = cfq_bio_merged,
4848 .elevator_dispatch_fn = cfq_dispatch_requests,
4849 .elevator_add_req_fn = cfq_insert_request,
4850 .elevator_activate_req_fn = cfq_activate_request,
4851 .elevator_deactivate_req_fn = cfq_deactivate_request,
4852 .elevator_completed_req_fn = cfq_completed_request,
4853 .elevator_former_req_fn = elv_rb_former_request,
4854 .elevator_latter_req_fn = elv_rb_latter_request,
4855 .elevator_init_icq_fn = cfq_init_icq,
4856 .elevator_exit_icq_fn = cfq_exit_icq,
4857 .elevator_set_req_fn = cfq_set_request,
4858 .elevator_put_req_fn = cfq_put_request,
4859 .elevator_may_queue_fn = cfq_may_queue,
4860 .elevator_init_fn = cfq_init_queue,
4861 .elevator_exit_fn = cfq_exit_queue,
4862 .elevator_registered_fn = cfq_registered_queue,
4864 .icq_size = sizeof(struct cfq_io_cq),
4865 .icq_align = __alignof__(struct cfq_io_cq),
4866 .elevator_attrs = cfq_attrs,
4867 .elevator_name = "cfq",
4868 .elevator_owner = THIS_MODULE,
4871 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4872 static struct blkcg_policy blkcg_policy_cfq = {
4873 .dfl_cftypes = cfq_blkcg_files,
4874 .legacy_cftypes = cfq_blkcg_legacy_files,
4876 .cpd_alloc_fn = cfq_cpd_alloc,
4877 .cpd_init_fn = cfq_cpd_init,
4878 .cpd_free_fn = cfq_cpd_free,
4879 .cpd_bind_fn = cfq_cpd_bind,
4881 .pd_alloc_fn = cfq_pd_alloc,
4882 .pd_init_fn = cfq_pd_init,
4883 .pd_offline_fn = cfq_pd_offline,
4884 .pd_free_fn = cfq_pd_free,
4885 .pd_reset_stats_fn = cfq_pd_reset_stats,
4889 static int __init cfq_init(void)
4893 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4894 ret = blkcg_policy_register(&blkcg_policy_cfq);
4902 cfq_pool = KMEM_CACHE(cfq_queue, 0);
4906 ret = elv_register(&iosched_cfq);
4913 kmem_cache_destroy(cfq_pool);
4915 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4916 blkcg_policy_unregister(&blkcg_policy_cfq);
4921 static void __exit cfq_exit(void)
4923 #ifdef CONFIG_CFQ_GROUP_IOSCHED
4924 blkcg_policy_unregister(&blkcg_policy_cfq);
4926 elv_unregister(&iosched_cfq);
4927 kmem_cache_destroy(cfq_pool);
4930 module_init(cfq_init);
4931 module_exit(cfq_exit);
4933 MODULE_AUTHOR("Jens Axboe");
4934 MODULE_LICENSE("GPL");
4935 MODULE_DESCRIPTION("Completely Fair Queueing IO scheduler");