block: cleanup the lockdep handling in *alloc_disk
[linux-2.6-microblaze.git] / block / mq-deadline-main.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  MQ Deadline i/o scheduler - adaptation of the legacy deadline scheduler,
4  *  for the blk-mq scheduling framework
5  *
6  *  Copyright (C) 2016 Jens Axboe <axboe@kernel.dk>
7  */
8 #include <linux/kernel.h>
9 #include <linux/fs.h>
10 #include <linux/blkdev.h>
11 #include <linux/blk-mq.h>
12 #include <linux/elevator.h>
13 #include <linux/bio.h>
14 #include <linux/module.h>
15 #include <linux/slab.h>
16 #include <linux/init.h>
17 #include <linux/compiler.h>
18 #include <linux/rbtree.h>
19 #include <linux/sbitmap.h>
20
21 #include <trace/events/block.h>
22
23 #include "blk.h"
24 #include "blk-mq.h"
25 #include "blk-mq-debugfs.h"
26 #include "blk-mq-tag.h"
27 #include "blk-mq-sched.h"
28 #include "mq-deadline-cgroup.h"
29
30 /*
31  * See Documentation/block/deadline-iosched.rst
32  */
33 static const int read_expire = HZ / 2;  /* max time before a read is submitted. */
34 static const int write_expire = 5 * HZ; /* ditto for writes, these limits are SOFT! */
35 /*
36  * Time after which to dispatch lower priority requests even if higher
37  * priority requests are pending.
38  */
39 static const int aging_expire = 10 * HZ;
40 static const int writes_starved = 2;    /* max times reads can starve a write */
41 static const int fifo_batch = 16;       /* # of sequential requests treated as one
42                                      by the above parameters. For throughput. */
43
44 enum dd_data_dir {
45         DD_READ         = READ,
46         DD_WRITE        = WRITE,
47 };
48
49 enum { DD_DIR_COUNT = 2 };
50
51 enum dd_prio {
52         DD_RT_PRIO      = 0,
53         DD_BE_PRIO      = 1,
54         DD_IDLE_PRIO    = 2,
55         DD_PRIO_MAX     = 2,
56 };
57
58 enum { DD_PRIO_COUNT = 3 };
59
60 /* I/O statistics for all I/O priorities (enum dd_prio). */
61 struct io_stats {
62         struct io_stats_per_prio stats[DD_PRIO_COUNT];
63 };
64
65 /*
66  * Deadline scheduler data per I/O priority (enum dd_prio). Requests are
67  * present on both sort_list[] and fifo_list[].
68  */
69 struct dd_per_prio {
70         struct list_head dispatch;
71         struct rb_root sort_list[DD_DIR_COUNT];
72         struct list_head fifo_list[DD_DIR_COUNT];
73         /* Next request in FIFO order. Read, write or both are NULL. */
74         struct request *next_rq[DD_DIR_COUNT];
75 };
76
77 struct deadline_data {
78         /*
79          * run time data
80          */
81
82         /* Request queue that owns this data structure. */
83         struct request_queue *queue;
84
85         struct dd_per_prio per_prio[DD_PRIO_COUNT];
86
87         /* Data direction of latest dispatched request. */
88         enum dd_data_dir last_dir;
89         unsigned int batching;          /* number of sequential requests made */
90         unsigned int starved;           /* times reads have starved writes */
91
92         struct io_stats __percpu *stats;
93
94         /*
95          * settings that change how the i/o scheduler behaves
96          */
97         int fifo_expire[DD_DIR_COUNT];
98         int fifo_batch;
99         int writes_starved;
100         int front_merges;
101         u32 async_depth;
102         int aging_expire;
103
104         spinlock_t lock;
105         spinlock_t zone_lock;
106 };
107
108 /* Count one event of type 'event_type' and with I/O priority 'prio' */
109 #define dd_count(dd, event_type, prio) do {                             \
110         struct io_stats *io_stats = get_cpu_ptr((dd)->stats);           \
111                                                                         \
112         BUILD_BUG_ON(!__same_type((dd), struct deadline_data *));       \
113         BUILD_BUG_ON(!__same_type((prio), enum dd_prio));               \
114         local_inc(&io_stats->stats[(prio)].event_type);                 \
115         put_cpu_ptr(io_stats);                                          \
116 } while (0)
117
118 /*
119  * Returns the total number of dd_count(dd, event_type, prio) calls across all
120  * CPUs. No locking or barriers since it is fine if the returned sum is slightly
121  * outdated.
122  */
123 #define dd_sum(dd, event_type, prio) ({                                 \
124         unsigned int cpu;                                               \
125         u32 sum = 0;                                                    \
126                                                                         \
127         BUILD_BUG_ON(!__same_type((dd), struct deadline_data *));       \
128         BUILD_BUG_ON(!__same_type((prio), enum dd_prio));               \
129         for_each_present_cpu(cpu)                                       \
130                 sum += local_read(&per_cpu_ptr((dd)->stats, cpu)->      \
131                                   stats[(prio)].event_type);            \
132         sum;                                                            \
133 })
134
135 /* Maps an I/O priority class to a deadline scheduler priority. */
136 static const enum dd_prio ioprio_class_to_prio[] = {
137         [IOPRIO_CLASS_NONE]     = DD_BE_PRIO,
138         [IOPRIO_CLASS_RT]       = DD_RT_PRIO,
139         [IOPRIO_CLASS_BE]       = DD_BE_PRIO,
140         [IOPRIO_CLASS_IDLE]     = DD_IDLE_PRIO,
141 };
142
143 static inline struct rb_root *
144 deadline_rb_root(struct dd_per_prio *per_prio, struct request *rq)
145 {
146         return &per_prio->sort_list[rq_data_dir(rq)];
147 }
148
149 /*
150  * Returns the I/O priority class (IOPRIO_CLASS_*) that has been assigned to a
151  * request.
152  */
153 static u8 dd_rq_ioclass(struct request *rq)
154 {
155         return IOPRIO_PRIO_CLASS(req_get_ioprio(rq));
156 }
157
158 /*
159  * get the request after `rq' in sector-sorted order
160  */
161 static inline struct request *
162 deadline_latter_request(struct request *rq)
163 {
164         struct rb_node *node = rb_next(&rq->rb_node);
165
166         if (node)
167                 return rb_entry_rq(node);
168
169         return NULL;
170 }
171
172 static void
173 deadline_add_rq_rb(struct dd_per_prio *per_prio, struct request *rq)
174 {
175         struct rb_root *root = deadline_rb_root(per_prio, rq);
176
177         elv_rb_add(root, rq);
178 }
179
180 static inline void
181 deadline_del_rq_rb(struct dd_per_prio *per_prio, struct request *rq)
182 {
183         const enum dd_data_dir data_dir = rq_data_dir(rq);
184
185         if (per_prio->next_rq[data_dir] == rq)
186                 per_prio->next_rq[data_dir] = deadline_latter_request(rq);
187
188         elv_rb_del(deadline_rb_root(per_prio, rq), rq);
189 }
190
191 /*
192  * remove rq from rbtree and fifo.
193  */
194 static void deadline_remove_request(struct request_queue *q,
195                                     struct dd_per_prio *per_prio,
196                                     struct request *rq)
197 {
198         list_del_init(&rq->queuelist);
199
200         /*
201          * We might not be on the rbtree, if we are doing an insert merge
202          */
203         if (!RB_EMPTY_NODE(&rq->rb_node))
204                 deadline_del_rq_rb(per_prio, rq);
205
206         elv_rqhash_del(q, rq);
207         if (q->last_merge == rq)
208                 q->last_merge = NULL;
209 }
210
211 static void dd_request_merged(struct request_queue *q, struct request *req,
212                               enum elv_merge type)
213 {
214         struct deadline_data *dd = q->elevator->elevator_data;
215         const u8 ioprio_class = dd_rq_ioclass(req);
216         const enum dd_prio prio = ioprio_class_to_prio[ioprio_class];
217         struct dd_per_prio *per_prio = &dd->per_prio[prio];
218
219         /*
220          * if the merge was a front merge, we need to reposition request
221          */
222         if (type == ELEVATOR_FRONT_MERGE) {
223                 elv_rb_del(deadline_rb_root(per_prio, req), req);
224                 deadline_add_rq_rb(per_prio, req);
225         }
226 }
227
228 /*
229  * Callback function that is invoked after @next has been merged into @req.
230  */
231 static void dd_merged_requests(struct request_queue *q, struct request *req,
232                                struct request *next)
233 {
234         struct deadline_data *dd = q->elevator->elevator_data;
235         const u8 ioprio_class = dd_rq_ioclass(next);
236         const enum dd_prio prio = ioprio_class_to_prio[ioprio_class];
237         struct dd_blkcg *blkcg = next->elv.priv[0];
238
239         dd_count(dd, merged, prio);
240         ddcg_count(blkcg, merged, ioprio_class);
241
242         /*
243          * if next expires before rq, assign its expire time to rq
244          * and move into next position (next will be deleted) in fifo
245          */
246         if (!list_empty(&req->queuelist) && !list_empty(&next->queuelist)) {
247                 if (time_before((unsigned long)next->fifo_time,
248                                 (unsigned long)req->fifo_time)) {
249                         list_move(&req->queuelist, &next->queuelist);
250                         req->fifo_time = next->fifo_time;
251                 }
252         }
253
254         /*
255          * kill knowledge of next, this one is a goner
256          */
257         deadline_remove_request(q, &dd->per_prio[prio], next);
258 }
259
260 /*
261  * move an entry to dispatch queue
262  */
263 static void
264 deadline_move_request(struct deadline_data *dd, struct dd_per_prio *per_prio,
265                       struct request *rq)
266 {
267         const enum dd_data_dir data_dir = rq_data_dir(rq);
268
269         per_prio->next_rq[data_dir] = deadline_latter_request(rq);
270
271         /*
272          * take it off the sort and fifo list
273          */
274         deadline_remove_request(rq->q, per_prio, rq);
275 }
276
277 /* Number of requests queued for a given priority level. */
278 static u32 dd_queued(struct deadline_data *dd, enum dd_prio prio)
279 {
280         return dd_sum(dd, inserted, prio) - dd_sum(dd, completed, prio);
281 }
282
283 /*
284  * deadline_check_fifo returns 0 if there are no expired requests on the fifo,
285  * 1 otherwise. Requires !list_empty(&dd->fifo_list[data_dir])
286  */
287 static inline int deadline_check_fifo(struct dd_per_prio *per_prio,
288                                       enum dd_data_dir data_dir)
289 {
290         struct request *rq = rq_entry_fifo(per_prio->fifo_list[data_dir].next);
291
292         /*
293          * rq is expired!
294          */
295         if (time_after_eq(jiffies, (unsigned long)rq->fifo_time))
296                 return 1;
297
298         return 0;
299 }
300
301 /*
302  * For the specified data direction, return the next request to
303  * dispatch using arrival ordered lists.
304  */
305 static struct request *
306 deadline_fifo_request(struct deadline_data *dd, struct dd_per_prio *per_prio,
307                       enum dd_data_dir data_dir)
308 {
309         struct request *rq;
310         unsigned long flags;
311
312         if (list_empty(&per_prio->fifo_list[data_dir]))
313                 return NULL;
314
315         rq = rq_entry_fifo(per_prio->fifo_list[data_dir].next);
316         if (data_dir == DD_READ || !blk_queue_is_zoned(rq->q))
317                 return rq;
318
319         /*
320          * Look for a write request that can be dispatched, that is one with
321          * an unlocked target zone.
322          */
323         spin_lock_irqsave(&dd->zone_lock, flags);
324         list_for_each_entry(rq, &per_prio->fifo_list[DD_WRITE], queuelist) {
325                 if (blk_req_can_dispatch_to_zone(rq))
326                         goto out;
327         }
328         rq = NULL;
329 out:
330         spin_unlock_irqrestore(&dd->zone_lock, flags);
331
332         return rq;
333 }
334
335 /*
336  * For the specified data direction, return the next request to
337  * dispatch using sector position sorted lists.
338  */
339 static struct request *
340 deadline_next_request(struct deadline_data *dd, struct dd_per_prio *per_prio,
341                       enum dd_data_dir data_dir)
342 {
343         struct request *rq;
344         unsigned long flags;
345
346         rq = per_prio->next_rq[data_dir];
347         if (!rq)
348                 return NULL;
349
350         if (data_dir == DD_READ || !blk_queue_is_zoned(rq->q))
351                 return rq;
352
353         /*
354          * Look for a write request that can be dispatched, that is one with
355          * an unlocked target zone.
356          */
357         spin_lock_irqsave(&dd->zone_lock, flags);
358         while (rq) {
359                 if (blk_req_can_dispatch_to_zone(rq))
360                         break;
361                 rq = deadline_latter_request(rq);
362         }
363         spin_unlock_irqrestore(&dd->zone_lock, flags);
364
365         return rq;
366 }
367
368 /*
369  * deadline_dispatch_requests selects the best request according to
370  * read/write expire, fifo_batch, etc and with a start time <= @latest.
371  */
372 static struct request *__dd_dispatch_request(struct deadline_data *dd,
373                                              struct dd_per_prio *per_prio,
374                                              u64 latest_start_ns)
375 {
376         struct request *rq, *next_rq;
377         enum dd_data_dir data_dir;
378         struct dd_blkcg *blkcg;
379         enum dd_prio prio;
380         u8 ioprio_class;
381
382         lockdep_assert_held(&dd->lock);
383
384         if (!list_empty(&per_prio->dispatch)) {
385                 rq = list_first_entry(&per_prio->dispatch, struct request,
386                                       queuelist);
387                 if (rq->start_time_ns > latest_start_ns)
388                         return NULL;
389                 list_del_init(&rq->queuelist);
390                 goto done;
391         }
392
393         /*
394          * batches are currently reads XOR writes
395          */
396         rq = deadline_next_request(dd, per_prio, dd->last_dir);
397         if (rq && dd->batching < dd->fifo_batch)
398                 /* we have a next request are still entitled to batch */
399                 goto dispatch_request;
400
401         /*
402          * at this point we are not running a batch. select the appropriate
403          * data direction (read / write)
404          */
405
406         if (!list_empty(&per_prio->fifo_list[DD_READ])) {
407                 BUG_ON(RB_EMPTY_ROOT(&per_prio->sort_list[DD_READ]));
408
409                 if (deadline_fifo_request(dd, per_prio, DD_WRITE) &&
410                     (dd->starved++ >= dd->writes_starved))
411                         goto dispatch_writes;
412
413                 data_dir = DD_READ;
414
415                 goto dispatch_find_request;
416         }
417
418         /*
419          * there are either no reads or writes have been starved
420          */
421
422         if (!list_empty(&per_prio->fifo_list[DD_WRITE])) {
423 dispatch_writes:
424                 BUG_ON(RB_EMPTY_ROOT(&per_prio->sort_list[DD_WRITE]));
425
426                 dd->starved = 0;
427
428                 data_dir = DD_WRITE;
429
430                 goto dispatch_find_request;
431         }
432
433         return NULL;
434
435 dispatch_find_request:
436         /*
437          * we are not running a batch, find best request for selected data_dir
438          */
439         next_rq = deadline_next_request(dd, per_prio, data_dir);
440         if (deadline_check_fifo(per_prio, data_dir) || !next_rq) {
441                 /*
442                  * A deadline has expired, the last request was in the other
443                  * direction, or we have run out of higher-sectored requests.
444                  * Start again from the request with the earliest expiry time.
445                  */
446                 rq = deadline_fifo_request(dd, per_prio, data_dir);
447         } else {
448                 /*
449                  * The last req was the same dir and we have a next request in
450                  * sort order. No expired requests so continue on from here.
451                  */
452                 rq = next_rq;
453         }
454
455         /*
456          * For a zoned block device, if we only have writes queued and none of
457          * them can be dispatched, rq will be NULL.
458          */
459         if (!rq)
460                 return NULL;
461
462         dd->last_dir = data_dir;
463         dd->batching = 0;
464
465 dispatch_request:
466         if (rq->start_time_ns > latest_start_ns)
467                 return NULL;
468         /*
469          * rq is the selected appropriate request.
470          */
471         dd->batching++;
472         deadline_move_request(dd, per_prio, rq);
473 done:
474         ioprio_class = dd_rq_ioclass(rq);
475         prio = ioprio_class_to_prio[ioprio_class];
476         dd_count(dd, dispatched, prio);
477         blkcg = rq->elv.priv[0];
478         ddcg_count(blkcg, dispatched, ioprio_class);
479         /*
480          * If the request needs its target zone locked, do it.
481          */
482         blk_req_zone_write_lock(rq);
483         rq->rq_flags |= RQF_STARTED;
484         return rq;
485 }
486
487 /*
488  * Called from blk_mq_run_hw_queue() -> __blk_mq_sched_dispatch_requests().
489  *
490  * One confusing aspect here is that we get called for a specific
491  * hardware queue, but we may return a request that is for a
492  * different hardware queue. This is because mq-deadline has shared
493  * state for all hardware queues, in terms of sorting, FIFOs, etc.
494  */
495 static struct request *dd_dispatch_request(struct blk_mq_hw_ctx *hctx)
496 {
497         struct deadline_data *dd = hctx->queue->elevator->elevator_data;
498         const u64 now_ns = ktime_get_ns();
499         struct request *rq = NULL;
500         enum dd_prio prio;
501
502         spin_lock(&dd->lock);
503         /*
504          * Start with dispatching requests whose deadline expired more than
505          * aging_expire jiffies ago.
506          */
507         for (prio = DD_BE_PRIO; prio <= DD_PRIO_MAX; prio++) {
508                 rq = __dd_dispatch_request(dd, &dd->per_prio[prio], now_ns -
509                                            jiffies_to_nsecs(dd->aging_expire));
510                 if (rq)
511                         goto unlock;
512         }
513         /*
514          * Next, dispatch requests in priority order. Ignore lower priority
515          * requests if any higher priority requests are pending.
516          */
517         for (prio = 0; prio <= DD_PRIO_MAX; prio++) {
518                 rq = __dd_dispatch_request(dd, &dd->per_prio[prio], now_ns);
519                 if (rq || dd_queued(dd, prio))
520                         break;
521         }
522
523 unlock:
524         spin_unlock(&dd->lock);
525
526         return rq;
527 }
528
529 /*
530  * Called by __blk_mq_alloc_request(). The shallow_depth value set by this
531  * function is used by __blk_mq_get_tag().
532  */
533 static void dd_limit_depth(unsigned int op, struct blk_mq_alloc_data *data)
534 {
535         struct deadline_data *dd = data->q->elevator->elevator_data;
536
537         /* Do not throttle synchronous reads. */
538         if (op_is_sync(op) && !op_is_write(op))
539                 return;
540
541         /*
542          * Throttle asynchronous requests and writes such that these requests
543          * do not block the allocation of synchronous requests.
544          */
545         data->shallow_depth = dd->async_depth;
546 }
547
548 /* Called by blk_mq_update_nr_requests(). */
549 static void dd_depth_updated(struct blk_mq_hw_ctx *hctx)
550 {
551         struct request_queue *q = hctx->queue;
552         struct deadline_data *dd = q->elevator->elevator_data;
553         struct blk_mq_tags *tags = hctx->sched_tags;
554
555         dd->async_depth = max(1UL, 3 * q->nr_requests / 4);
556
557         sbitmap_queue_min_shallow_depth(tags->bitmap_tags, dd->async_depth);
558 }
559
560 /* Called by blk_mq_init_hctx() and blk_mq_init_sched(). */
561 static int dd_init_hctx(struct blk_mq_hw_ctx *hctx, unsigned int hctx_idx)
562 {
563         dd_depth_updated(hctx);
564         return 0;
565 }
566
567 static void dd_exit_sched(struct elevator_queue *e)
568 {
569         struct deadline_data *dd = e->elevator_data;
570         enum dd_prio prio;
571
572         dd_deactivate_policy(dd->queue);
573
574         for (prio = 0; prio <= DD_PRIO_MAX; prio++) {
575                 struct dd_per_prio *per_prio = &dd->per_prio[prio];
576
577                 WARN_ON_ONCE(!list_empty(&per_prio->fifo_list[DD_READ]));
578                 WARN_ON_ONCE(!list_empty(&per_prio->fifo_list[DD_WRITE]));
579         }
580
581         free_percpu(dd->stats);
582
583         kfree(dd);
584 }
585
586 /*
587  * Initialize elevator private data (deadline_data) and associate with blkcg.
588  */
589 static int dd_init_sched(struct request_queue *q, struct elevator_type *e)
590 {
591         struct deadline_data *dd;
592         struct elevator_queue *eq;
593         enum dd_prio prio;
594         int ret = -ENOMEM;
595
596         /*
597          * Initialization would be very tricky if the queue is not frozen,
598          * hence the warning statement below.
599          */
600         WARN_ON_ONCE(!percpu_ref_is_zero(&q->q_usage_counter));
601
602         eq = elevator_alloc(q, e);
603         if (!eq)
604                 return ret;
605
606         dd = kzalloc_node(sizeof(*dd), GFP_KERNEL, q->node);
607         if (!dd)
608                 goto put_eq;
609
610         eq->elevator_data = dd;
611
612         dd->stats = alloc_percpu_gfp(typeof(*dd->stats),
613                                      GFP_KERNEL | __GFP_ZERO);
614         if (!dd->stats)
615                 goto free_dd;
616
617         dd->queue = q;
618
619         for (prio = 0; prio <= DD_PRIO_MAX; prio++) {
620                 struct dd_per_prio *per_prio = &dd->per_prio[prio];
621
622                 INIT_LIST_HEAD(&per_prio->dispatch);
623                 INIT_LIST_HEAD(&per_prio->fifo_list[DD_READ]);
624                 INIT_LIST_HEAD(&per_prio->fifo_list[DD_WRITE]);
625                 per_prio->sort_list[DD_READ] = RB_ROOT;
626                 per_prio->sort_list[DD_WRITE] = RB_ROOT;
627         }
628         dd->fifo_expire[DD_READ] = read_expire;
629         dd->fifo_expire[DD_WRITE] = write_expire;
630         dd->writes_starved = writes_starved;
631         dd->front_merges = 1;
632         dd->last_dir = DD_WRITE;
633         dd->fifo_batch = fifo_batch;
634         dd->aging_expire = aging_expire;
635         spin_lock_init(&dd->lock);
636         spin_lock_init(&dd->zone_lock);
637
638         ret = dd_activate_policy(q);
639         if (ret)
640                 goto free_stats;
641
642         ret = 0;
643         q->elevator = eq;
644         return 0;
645
646 free_stats:
647         free_percpu(dd->stats);
648
649 free_dd:
650         kfree(dd);
651
652 put_eq:
653         kobject_put(&eq->kobj);
654         return ret;
655 }
656
657 /*
658  * Try to merge @bio into an existing request. If @bio has been merged into
659  * an existing request, store the pointer to that request into *@rq.
660  */
661 static int dd_request_merge(struct request_queue *q, struct request **rq,
662                             struct bio *bio)
663 {
664         struct deadline_data *dd = q->elevator->elevator_data;
665         const u8 ioprio_class = IOPRIO_PRIO_CLASS(bio->bi_ioprio);
666         const enum dd_prio prio = ioprio_class_to_prio[ioprio_class];
667         struct dd_per_prio *per_prio = &dd->per_prio[prio];
668         sector_t sector = bio_end_sector(bio);
669         struct request *__rq;
670
671         if (!dd->front_merges)
672                 return ELEVATOR_NO_MERGE;
673
674         __rq = elv_rb_find(&per_prio->sort_list[bio_data_dir(bio)], sector);
675         if (__rq) {
676                 BUG_ON(sector != blk_rq_pos(__rq));
677
678                 if (elv_bio_merge_ok(__rq, bio)) {
679                         *rq = __rq;
680                         if (blk_discard_mergable(__rq))
681                                 return ELEVATOR_DISCARD_MERGE;
682                         return ELEVATOR_FRONT_MERGE;
683                 }
684         }
685
686         return ELEVATOR_NO_MERGE;
687 }
688
689 /*
690  * Attempt to merge a bio into an existing request. This function is called
691  * before @bio is associated with a request.
692  */
693 static bool dd_bio_merge(struct request_queue *q, struct bio *bio,
694                 unsigned int nr_segs)
695 {
696         struct deadline_data *dd = q->elevator->elevator_data;
697         struct request *free = NULL;
698         bool ret;
699
700         spin_lock(&dd->lock);
701         ret = blk_mq_sched_try_merge(q, bio, nr_segs, &free);
702         spin_unlock(&dd->lock);
703
704         if (free)
705                 blk_mq_free_request(free);
706
707         return ret;
708 }
709
710 /*
711  * add rq to rbtree and fifo
712  */
713 static void dd_insert_request(struct blk_mq_hw_ctx *hctx, struct request *rq,
714                               bool at_head)
715 {
716         struct request_queue *q = hctx->queue;
717         struct deadline_data *dd = q->elevator->elevator_data;
718         const enum dd_data_dir data_dir = rq_data_dir(rq);
719         u16 ioprio = req_get_ioprio(rq);
720         u8 ioprio_class = IOPRIO_PRIO_CLASS(ioprio);
721         struct dd_per_prio *per_prio;
722         enum dd_prio prio;
723         struct dd_blkcg *blkcg;
724         LIST_HEAD(free);
725
726         lockdep_assert_held(&dd->lock);
727
728         /*
729          * This may be a requeue of a write request that has locked its
730          * target zone. If it is the case, this releases the zone lock.
731          */
732         blk_req_zone_write_unlock(rq);
733
734         /*
735          * If a block cgroup has been associated with the submitter and if an
736          * I/O priority has been set in the associated block cgroup, use the
737          * lowest of the cgroup priority and the request priority for the
738          * request. If no priority has been set in the request, use the cgroup
739          * priority.
740          */
741         prio = ioprio_class_to_prio[ioprio_class];
742         dd_count(dd, inserted, prio);
743         blkcg = dd_blkcg_from_bio(rq->bio);
744         ddcg_count(blkcg, inserted, ioprio_class);
745         rq->elv.priv[0] = blkcg;
746
747         if (blk_mq_sched_try_insert_merge(q, rq, &free)) {
748                 blk_mq_free_requests(&free);
749                 return;
750         }
751
752         trace_block_rq_insert(rq);
753
754         per_prio = &dd->per_prio[prio];
755         if (at_head) {
756                 list_add(&rq->queuelist, &per_prio->dispatch);
757         } else {
758                 deadline_add_rq_rb(per_prio, rq);
759
760                 if (rq_mergeable(rq)) {
761                         elv_rqhash_add(q, rq);
762                         if (!q->last_merge)
763                                 q->last_merge = rq;
764                 }
765
766                 /*
767                  * set expire time and add to fifo list
768                  */
769                 rq->fifo_time = jiffies + dd->fifo_expire[data_dir];
770                 list_add_tail(&rq->queuelist, &per_prio->fifo_list[data_dir]);
771         }
772 }
773
774 /*
775  * Called from blk_mq_sched_insert_request() or blk_mq_sched_insert_requests().
776  */
777 static void dd_insert_requests(struct blk_mq_hw_ctx *hctx,
778                                struct list_head *list, bool at_head)
779 {
780         struct request_queue *q = hctx->queue;
781         struct deadline_data *dd = q->elevator->elevator_data;
782
783         spin_lock(&dd->lock);
784         while (!list_empty(list)) {
785                 struct request *rq;
786
787                 rq = list_first_entry(list, struct request, queuelist);
788                 list_del_init(&rq->queuelist);
789                 dd_insert_request(hctx, rq, at_head);
790         }
791         spin_unlock(&dd->lock);
792 }
793
794 /* Callback from inside blk_mq_rq_ctx_init(). */
795 static void dd_prepare_request(struct request *rq)
796 {
797         rq->elv.priv[0] = NULL;
798 }
799
800 /*
801  * Callback from inside blk_mq_free_request().
802  *
803  * For zoned block devices, write unlock the target zone of
804  * completed write requests. Do this while holding the zone lock
805  * spinlock so that the zone is never unlocked while deadline_fifo_request()
806  * or deadline_next_request() are executing. This function is called for
807  * all requests, whether or not these requests complete successfully.
808  *
809  * For a zoned block device, __dd_dispatch_request() may have stopped
810  * dispatching requests if all the queued requests are write requests directed
811  * at zones that are already locked due to on-going write requests. To ensure
812  * write request dispatch progress in this case, mark the queue as needing a
813  * restart to ensure that the queue is run again after completion of the
814  * request and zones being unlocked.
815  */
816 static void dd_finish_request(struct request *rq)
817 {
818         struct request_queue *q = rq->q;
819         struct deadline_data *dd = q->elevator->elevator_data;
820         struct dd_blkcg *blkcg = rq->elv.priv[0];
821         const u8 ioprio_class = dd_rq_ioclass(rq);
822         const enum dd_prio prio = ioprio_class_to_prio[ioprio_class];
823         struct dd_per_prio *per_prio = &dd->per_prio[prio];
824
825         dd_count(dd, completed, prio);
826         ddcg_count(blkcg, completed, ioprio_class);
827
828         if (blk_queue_is_zoned(q)) {
829                 unsigned long flags;
830
831                 spin_lock_irqsave(&dd->zone_lock, flags);
832                 blk_req_zone_write_unlock(rq);
833                 if (!list_empty(&per_prio->fifo_list[DD_WRITE]))
834                         blk_mq_sched_mark_restart_hctx(rq->mq_hctx);
835                 spin_unlock_irqrestore(&dd->zone_lock, flags);
836         }
837 }
838
839 static bool dd_has_work_for_prio(struct dd_per_prio *per_prio)
840 {
841         return !list_empty_careful(&per_prio->dispatch) ||
842                 !list_empty_careful(&per_prio->fifo_list[DD_READ]) ||
843                 !list_empty_careful(&per_prio->fifo_list[DD_WRITE]);
844 }
845
846 static bool dd_has_work(struct blk_mq_hw_ctx *hctx)
847 {
848         struct deadline_data *dd = hctx->queue->elevator->elevator_data;
849         enum dd_prio prio;
850
851         for (prio = 0; prio <= DD_PRIO_MAX; prio++)
852                 if (dd_has_work_for_prio(&dd->per_prio[prio]))
853                         return true;
854
855         return false;
856 }
857
858 /*
859  * sysfs parts below
860  */
861 #define SHOW_INT(__FUNC, __VAR)                                         \
862 static ssize_t __FUNC(struct elevator_queue *e, char *page)             \
863 {                                                                       \
864         struct deadline_data *dd = e->elevator_data;                    \
865                                                                         \
866         return sysfs_emit(page, "%d\n", __VAR);                         \
867 }
868 #define SHOW_JIFFIES(__FUNC, __VAR) SHOW_INT(__FUNC, jiffies_to_msecs(__VAR))
869 SHOW_JIFFIES(deadline_read_expire_show, dd->fifo_expire[DD_READ]);
870 SHOW_JIFFIES(deadline_write_expire_show, dd->fifo_expire[DD_WRITE]);
871 SHOW_JIFFIES(deadline_aging_expire_show, dd->aging_expire);
872 SHOW_INT(deadline_writes_starved_show, dd->writes_starved);
873 SHOW_INT(deadline_front_merges_show, dd->front_merges);
874 SHOW_INT(deadline_async_depth_show, dd->front_merges);
875 SHOW_INT(deadline_fifo_batch_show, dd->fifo_batch);
876 #undef SHOW_INT
877 #undef SHOW_JIFFIES
878
879 #define STORE_FUNCTION(__FUNC, __PTR, MIN, MAX, __CONV)                 \
880 static ssize_t __FUNC(struct elevator_queue *e, const char *page, size_t count) \
881 {                                                                       \
882         struct deadline_data *dd = e->elevator_data;                    \
883         int __data, __ret;                                              \
884                                                                         \
885         __ret = kstrtoint(page, 0, &__data);                            \
886         if (__ret < 0)                                                  \
887                 return __ret;                                           \
888         if (__data < (MIN))                                             \
889                 __data = (MIN);                                         \
890         else if (__data > (MAX))                                        \
891                 __data = (MAX);                                         \
892         *(__PTR) = __CONV(__data);                                      \
893         return count;                                                   \
894 }
895 #define STORE_INT(__FUNC, __PTR, MIN, MAX)                              \
896         STORE_FUNCTION(__FUNC, __PTR, MIN, MAX, )
897 #define STORE_JIFFIES(__FUNC, __PTR, MIN, MAX)                          \
898         STORE_FUNCTION(__FUNC, __PTR, MIN, MAX, msecs_to_jiffies)
899 STORE_JIFFIES(deadline_read_expire_store, &dd->fifo_expire[DD_READ], 0, INT_MAX);
900 STORE_JIFFIES(deadline_write_expire_store, &dd->fifo_expire[DD_WRITE], 0, INT_MAX);
901 STORE_JIFFIES(deadline_aging_expire_store, &dd->aging_expire, 0, INT_MAX);
902 STORE_INT(deadline_writes_starved_store, &dd->writes_starved, INT_MIN, INT_MAX);
903 STORE_INT(deadline_front_merges_store, &dd->front_merges, 0, 1);
904 STORE_INT(deadline_async_depth_store, &dd->front_merges, 1, INT_MAX);
905 STORE_INT(deadline_fifo_batch_store, &dd->fifo_batch, 0, INT_MAX);
906 #undef STORE_FUNCTION
907 #undef STORE_INT
908 #undef STORE_JIFFIES
909
910 #define DD_ATTR(name) \
911         __ATTR(name, 0644, deadline_##name##_show, deadline_##name##_store)
912
913 static struct elv_fs_entry deadline_attrs[] = {
914         DD_ATTR(read_expire),
915         DD_ATTR(write_expire),
916         DD_ATTR(writes_starved),
917         DD_ATTR(front_merges),
918         DD_ATTR(async_depth),
919         DD_ATTR(fifo_batch),
920         DD_ATTR(aging_expire),
921         __ATTR_NULL
922 };
923
924 #ifdef CONFIG_BLK_DEBUG_FS
925 #define DEADLINE_DEBUGFS_DDIR_ATTRS(prio, data_dir, name)               \
926 static void *deadline_##name##_fifo_start(struct seq_file *m,           \
927                                           loff_t *pos)                  \
928         __acquires(&dd->lock)                                           \
929 {                                                                       \
930         struct request_queue *q = m->private;                           \
931         struct deadline_data *dd = q->elevator->elevator_data;          \
932         struct dd_per_prio *per_prio = &dd->per_prio[prio];             \
933                                                                         \
934         spin_lock(&dd->lock);                                           \
935         return seq_list_start(&per_prio->fifo_list[data_dir], *pos);    \
936 }                                                                       \
937                                                                         \
938 static void *deadline_##name##_fifo_next(struct seq_file *m, void *v,   \
939                                          loff_t *pos)                   \
940 {                                                                       \
941         struct request_queue *q = m->private;                           \
942         struct deadline_data *dd = q->elevator->elevator_data;          \
943         struct dd_per_prio *per_prio = &dd->per_prio[prio];             \
944                                                                         \
945         return seq_list_next(v, &per_prio->fifo_list[data_dir], pos);   \
946 }                                                                       \
947                                                                         \
948 static void deadline_##name##_fifo_stop(struct seq_file *m, void *v)    \
949         __releases(&dd->lock)                                           \
950 {                                                                       \
951         struct request_queue *q = m->private;                           \
952         struct deadline_data *dd = q->elevator->elevator_data;          \
953                                                                         \
954         spin_unlock(&dd->lock);                                         \
955 }                                                                       \
956                                                                         \
957 static const struct seq_operations deadline_##name##_fifo_seq_ops = {   \
958         .start  = deadline_##name##_fifo_start,                         \
959         .next   = deadline_##name##_fifo_next,                          \
960         .stop   = deadline_##name##_fifo_stop,                          \
961         .show   = blk_mq_debugfs_rq_show,                               \
962 };                                                                      \
963                                                                         \
964 static int deadline_##name##_next_rq_show(void *data,                   \
965                                           struct seq_file *m)           \
966 {                                                                       \
967         struct request_queue *q = data;                                 \
968         struct deadline_data *dd = q->elevator->elevator_data;          \
969         struct dd_per_prio *per_prio = &dd->per_prio[prio];             \
970         struct request *rq = per_prio->next_rq[data_dir];               \
971                                                                         \
972         if (rq)                                                         \
973                 __blk_mq_debugfs_rq_show(m, rq);                        \
974         return 0;                                                       \
975 }
976
977 DEADLINE_DEBUGFS_DDIR_ATTRS(DD_RT_PRIO, DD_READ, read0);
978 DEADLINE_DEBUGFS_DDIR_ATTRS(DD_RT_PRIO, DD_WRITE, write0);
979 DEADLINE_DEBUGFS_DDIR_ATTRS(DD_BE_PRIO, DD_READ, read1);
980 DEADLINE_DEBUGFS_DDIR_ATTRS(DD_BE_PRIO, DD_WRITE, write1);
981 DEADLINE_DEBUGFS_DDIR_ATTRS(DD_IDLE_PRIO, DD_READ, read2);
982 DEADLINE_DEBUGFS_DDIR_ATTRS(DD_IDLE_PRIO, DD_WRITE, write2);
983 #undef DEADLINE_DEBUGFS_DDIR_ATTRS
984
985 static int deadline_batching_show(void *data, struct seq_file *m)
986 {
987         struct request_queue *q = data;
988         struct deadline_data *dd = q->elevator->elevator_data;
989
990         seq_printf(m, "%u\n", dd->batching);
991         return 0;
992 }
993
994 static int deadline_starved_show(void *data, struct seq_file *m)
995 {
996         struct request_queue *q = data;
997         struct deadline_data *dd = q->elevator->elevator_data;
998
999         seq_printf(m, "%u\n", dd->starved);
1000         return 0;
1001 }
1002
1003 static int dd_async_depth_show(void *data, struct seq_file *m)
1004 {
1005         struct request_queue *q = data;
1006         struct deadline_data *dd = q->elevator->elevator_data;
1007
1008         seq_printf(m, "%u\n", dd->async_depth);
1009         return 0;
1010 }
1011
1012 static int dd_queued_show(void *data, struct seq_file *m)
1013 {
1014         struct request_queue *q = data;
1015         struct deadline_data *dd = q->elevator->elevator_data;
1016
1017         seq_printf(m, "%u %u %u\n", dd_queued(dd, DD_RT_PRIO),
1018                    dd_queued(dd, DD_BE_PRIO),
1019                    dd_queued(dd, DD_IDLE_PRIO));
1020         return 0;
1021 }
1022
1023 /* Number of requests owned by the block driver for a given priority. */
1024 static u32 dd_owned_by_driver(struct deadline_data *dd, enum dd_prio prio)
1025 {
1026         return dd_sum(dd, dispatched, prio) + dd_sum(dd, merged, prio)
1027                 - dd_sum(dd, completed, prio);
1028 }
1029
1030 static int dd_owned_by_driver_show(void *data, struct seq_file *m)
1031 {
1032         struct request_queue *q = data;
1033         struct deadline_data *dd = q->elevator->elevator_data;
1034
1035         seq_printf(m, "%u %u %u\n", dd_owned_by_driver(dd, DD_RT_PRIO),
1036                    dd_owned_by_driver(dd, DD_BE_PRIO),
1037                    dd_owned_by_driver(dd, DD_IDLE_PRIO));
1038         return 0;
1039 }
1040
1041 #define DEADLINE_DISPATCH_ATTR(prio)                                    \
1042 static void *deadline_dispatch##prio##_start(struct seq_file *m,        \
1043                                              loff_t *pos)               \
1044         __acquires(&dd->lock)                                           \
1045 {                                                                       \
1046         struct request_queue *q = m->private;                           \
1047         struct deadline_data *dd = q->elevator->elevator_data;          \
1048         struct dd_per_prio *per_prio = &dd->per_prio[prio];             \
1049                                                                         \
1050         spin_lock(&dd->lock);                                           \
1051         return seq_list_start(&per_prio->dispatch, *pos);               \
1052 }                                                                       \
1053                                                                         \
1054 static void *deadline_dispatch##prio##_next(struct seq_file *m,         \
1055                                             void *v, loff_t *pos)       \
1056 {                                                                       \
1057         struct request_queue *q = m->private;                           \
1058         struct deadline_data *dd = q->elevator->elevator_data;          \
1059         struct dd_per_prio *per_prio = &dd->per_prio[prio];             \
1060                                                                         \
1061         return seq_list_next(v, &per_prio->dispatch, pos);              \
1062 }                                                                       \
1063                                                                         \
1064 static void deadline_dispatch##prio##_stop(struct seq_file *m, void *v) \
1065         __releases(&dd->lock)                                           \
1066 {                                                                       \
1067         struct request_queue *q = m->private;                           \
1068         struct deadline_data *dd = q->elevator->elevator_data;          \
1069                                                                         \
1070         spin_unlock(&dd->lock);                                         \
1071 }                                                                       \
1072                                                                         \
1073 static const struct seq_operations deadline_dispatch##prio##_seq_ops = { \
1074         .start  = deadline_dispatch##prio##_start,                      \
1075         .next   = deadline_dispatch##prio##_next,                       \
1076         .stop   = deadline_dispatch##prio##_stop,                       \
1077         .show   = blk_mq_debugfs_rq_show,                               \
1078 }
1079
1080 DEADLINE_DISPATCH_ATTR(0);
1081 DEADLINE_DISPATCH_ATTR(1);
1082 DEADLINE_DISPATCH_ATTR(2);
1083 #undef DEADLINE_DISPATCH_ATTR
1084
1085 #define DEADLINE_QUEUE_DDIR_ATTRS(name)                                 \
1086         {#name "_fifo_list", 0400,                                      \
1087                         .seq_ops = &deadline_##name##_fifo_seq_ops}
1088 #define DEADLINE_NEXT_RQ_ATTR(name)                                     \
1089         {#name "_next_rq", 0400, deadline_##name##_next_rq_show}
1090 static const struct blk_mq_debugfs_attr deadline_queue_debugfs_attrs[] = {
1091         DEADLINE_QUEUE_DDIR_ATTRS(read0),
1092         DEADLINE_QUEUE_DDIR_ATTRS(write0),
1093         DEADLINE_QUEUE_DDIR_ATTRS(read1),
1094         DEADLINE_QUEUE_DDIR_ATTRS(write1),
1095         DEADLINE_QUEUE_DDIR_ATTRS(read2),
1096         DEADLINE_QUEUE_DDIR_ATTRS(write2),
1097         DEADLINE_NEXT_RQ_ATTR(read0),
1098         DEADLINE_NEXT_RQ_ATTR(write0),
1099         DEADLINE_NEXT_RQ_ATTR(read1),
1100         DEADLINE_NEXT_RQ_ATTR(write1),
1101         DEADLINE_NEXT_RQ_ATTR(read2),
1102         DEADLINE_NEXT_RQ_ATTR(write2),
1103         {"batching", 0400, deadline_batching_show},
1104         {"starved", 0400, deadline_starved_show},
1105         {"async_depth", 0400, dd_async_depth_show},
1106         {"dispatch0", 0400, .seq_ops = &deadline_dispatch0_seq_ops},
1107         {"dispatch1", 0400, .seq_ops = &deadline_dispatch1_seq_ops},
1108         {"dispatch2", 0400, .seq_ops = &deadline_dispatch2_seq_ops},
1109         {"owned_by_driver", 0400, dd_owned_by_driver_show},
1110         {"queued", 0400, dd_queued_show},
1111         {},
1112 };
1113 #undef DEADLINE_QUEUE_DDIR_ATTRS
1114 #endif
1115
1116 static struct elevator_type mq_deadline = {
1117         .ops = {
1118                 .depth_updated          = dd_depth_updated,
1119                 .limit_depth            = dd_limit_depth,
1120                 .insert_requests        = dd_insert_requests,
1121                 .dispatch_request       = dd_dispatch_request,
1122                 .prepare_request        = dd_prepare_request,
1123                 .finish_request         = dd_finish_request,
1124                 .next_request           = elv_rb_latter_request,
1125                 .former_request         = elv_rb_former_request,
1126                 .bio_merge              = dd_bio_merge,
1127                 .request_merge          = dd_request_merge,
1128                 .requests_merged        = dd_merged_requests,
1129                 .request_merged         = dd_request_merged,
1130                 .has_work               = dd_has_work,
1131                 .init_sched             = dd_init_sched,
1132                 .exit_sched             = dd_exit_sched,
1133                 .init_hctx              = dd_init_hctx,
1134         },
1135
1136 #ifdef CONFIG_BLK_DEBUG_FS
1137         .queue_debugfs_attrs = deadline_queue_debugfs_attrs,
1138 #endif
1139         .elevator_attrs = deadline_attrs,
1140         .elevator_name = "mq-deadline",
1141         .elevator_alias = "deadline",
1142         .elevator_features = ELEVATOR_F_ZBD_SEQ_WRITE,
1143         .elevator_owner = THIS_MODULE,
1144 };
1145 MODULE_ALIAS("mq-deadline-iosched");
1146
1147 static int __init deadline_init(void)
1148 {
1149         int ret;
1150
1151         ret = elv_register(&mq_deadline);
1152         if (ret)
1153                 goto out;
1154         ret = dd_blkcg_init();
1155         if (ret)
1156                 goto unreg;
1157
1158 out:
1159         return ret;
1160
1161 unreg:
1162         elv_unregister(&mq_deadline);
1163         goto out;
1164 }
1165
1166 static void __exit deadline_exit(void)
1167 {
1168         dd_blkcg_exit();
1169         elv_unregister(&mq_deadline);
1170 }
1171
1172 module_init(deadline_init);
1173 module_exit(deadline_exit);
1174
1175 MODULE_AUTHOR("Jens Axboe, Damien Le Moal and Bart Van Assche");
1176 MODULE_LICENSE("GPL");
1177 MODULE_DESCRIPTION("MQ deadline IO scheduler");