block: blk-mq: support draining mq queue
[firefly-linux-kernel-4.4.55.git] / block / blk-core.c
1 /*
2  * Copyright (C) 1991, 1992 Linus Torvalds
3  * Copyright (C) 1994,      Karl Keyte: Added support for disk statistics
4  * Elevator latency, (C) 2000  Andrea Arcangeli <andrea@suse.de> SuSE
5  * Queue request tables / lock, selectable elevator, Jens Axboe <axboe@suse.de>
6  * kernel-doc documentation started by NeilBrown <neilb@cse.unsw.edu.au>
7  *      -  July2000
8  * bio rewrite, highmem i/o, etc, Jens Axboe <axboe@suse.de> - may 2001
9  */
10
11 /*
12  * This handles all read/write requests to block devices
13  */
14 #include <linux/kernel.h>
15 #include <linux/module.h>
16 #include <linux/backing-dev.h>
17 #include <linux/bio.h>
18 #include <linux/blkdev.h>
19 #include <linux/blk-mq.h>
20 #include <linux/highmem.h>
21 #include <linux/mm.h>
22 #include <linux/kernel_stat.h>
23 #include <linux/string.h>
24 #include <linux/init.h>
25 #include <linux/completion.h>
26 #include <linux/slab.h>
27 #include <linux/swap.h>
28 #include <linux/writeback.h>
29 #include <linux/task_io_accounting_ops.h>
30 #include <linux/fault-inject.h>
31 #include <linux/list_sort.h>
32 #include <linux/delay.h>
33 #include <linux/ratelimit.h>
34 #include <linux/pm_runtime.h>
35
36 #define CREATE_TRACE_POINTS
37 #include <trace/events/block.h>
38
39 #include "blk.h"
40 #include "blk-cgroup.h"
41 #include "blk-mq.h"
42
43 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_remap);
44 EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_remap);
45 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_complete);
46 EXPORT_TRACEPOINT_SYMBOL_GPL(block_unplug);
47
48 DEFINE_IDA(blk_queue_ida);
49
50 /*
51  * For the allocated request tables
52  */
53 struct kmem_cache *request_cachep = NULL;
54
55 /*
56  * For queue allocation
57  */
58 struct kmem_cache *blk_requestq_cachep;
59
60 /*
61  * Controlling structure to kblockd
62  */
63 static struct workqueue_struct *kblockd_workqueue;
64
65 void blk_queue_congestion_threshold(struct request_queue *q)
66 {
67         int nr;
68
69         nr = q->nr_requests - (q->nr_requests / 8) + 1;
70         if (nr > q->nr_requests)
71                 nr = q->nr_requests;
72         q->nr_congestion_on = nr;
73
74         nr = q->nr_requests - (q->nr_requests / 8) - (q->nr_requests / 16) - 1;
75         if (nr < 1)
76                 nr = 1;
77         q->nr_congestion_off = nr;
78 }
79
80 /**
81  * blk_get_backing_dev_info - get the address of a queue's backing_dev_info
82  * @bdev:       device
83  *
84  * Locates the passed device's request queue and returns the address of its
85  * backing_dev_info
86  *
87  * Will return NULL if the request queue cannot be located.
88  */
89 struct backing_dev_info *blk_get_backing_dev_info(struct block_device *bdev)
90 {
91         struct backing_dev_info *ret = NULL;
92         struct request_queue *q = bdev_get_queue(bdev);
93
94         if (q)
95                 ret = &q->backing_dev_info;
96         return ret;
97 }
98 EXPORT_SYMBOL(blk_get_backing_dev_info);
99
100 void blk_rq_init(struct request_queue *q, struct request *rq)
101 {
102         memset(rq, 0, sizeof(*rq));
103
104         INIT_LIST_HEAD(&rq->queuelist);
105         INIT_LIST_HEAD(&rq->timeout_list);
106         rq->cpu = -1;
107         rq->q = q;
108         rq->__sector = (sector_t) -1;
109         INIT_HLIST_NODE(&rq->hash);
110         RB_CLEAR_NODE(&rq->rb_node);
111         rq->cmd = rq->__cmd;
112         rq->cmd_len = BLK_MAX_CDB;
113         rq->tag = -1;
114         rq->start_time = jiffies;
115         set_start_time_ns(rq);
116         rq->part = NULL;
117 }
118 EXPORT_SYMBOL(blk_rq_init);
119
120 static void req_bio_endio(struct request *rq, struct bio *bio,
121                           unsigned int nbytes, int error)
122 {
123         if (error)
124                 clear_bit(BIO_UPTODATE, &bio->bi_flags);
125         else if (!test_bit(BIO_UPTODATE, &bio->bi_flags))
126                 error = -EIO;
127
128         if (unlikely(rq->cmd_flags & REQ_QUIET))
129                 set_bit(BIO_QUIET, &bio->bi_flags);
130
131         bio_advance(bio, nbytes);
132
133         /* don't actually finish bio if it's part of flush sequence */
134         if (bio->bi_iter.bi_size == 0 && !(rq->cmd_flags & REQ_FLUSH_SEQ))
135                 bio_endio(bio, error);
136 }
137
138 void blk_dump_rq_flags(struct request *rq, char *msg)
139 {
140         int bit;
141
142         printk(KERN_INFO "%s: dev %s: type=%x, flags=%llx\n", msg,
143                 rq->rq_disk ? rq->rq_disk->disk_name : "?", rq->cmd_type,
144                 (unsigned long long) rq->cmd_flags);
145
146         printk(KERN_INFO "  sector %llu, nr/cnr %u/%u\n",
147                (unsigned long long)blk_rq_pos(rq),
148                blk_rq_sectors(rq), blk_rq_cur_sectors(rq));
149         printk(KERN_INFO "  bio %p, biotail %p, buffer %p, len %u\n",
150                rq->bio, rq->biotail, rq->buffer, blk_rq_bytes(rq));
151
152         if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
153                 printk(KERN_INFO "  cdb: ");
154                 for (bit = 0; bit < BLK_MAX_CDB; bit++)
155                         printk("%02x ", rq->cmd[bit]);
156                 printk("\n");
157         }
158 }
159 EXPORT_SYMBOL(blk_dump_rq_flags);
160
161 static void blk_delay_work(struct work_struct *work)
162 {
163         struct request_queue *q;
164
165         q = container_of(work, struct request_queue, delay_work.work);
166         spin_lock_irq(q->queue_lock);
167         __blk_run_queue(q);
168         spin_unlock_irq(q->queue_lock);
169 }
170
171 /**
172  * blk_delay_queue - restart queueing after defined interval
173  * @q:          The &struct request_queue in question
174  * @msecs:      Delay in msecs
175  *
176  * Description:
177  *   Sometimes queueing needs to be postponed for a little while, to allow
178  *   resources to come back. This function will make sure that queueing is
179  *   restarted around the specified time. Queue lock must be held.
180  */
181 void blk_delay_queue(struct request_queue *q, unsigned long msecs)
182 {
183         if (likely(!blk_queue_dead(q)))
184                 queue_delayed_work(kblockd_workqueue, &q->delay_work,
185                                    msecs_to_jiffies(msecs));
186 }
187 EXPORT_SYMBOL(blk_delay_queue);
188
189 /**
190  * blk_start_queue - restart a previously stopped queue
191  * @q:    The &struct request_queue in question
192  *
193  * Description:
194  *   blk_start_queue() will clear the stop flag on the queue, and call
195  *   the request_fn for the queue if it was in a stopped state when
196  *   entered. Also see blk_stop_queue(). Queue lock must be held.
197  **/
198 void blk_start_queue(struct request_queue *q)
199 {
200         WARN_ON(!irqs_disabled());
201
202         queue_flag_clear(QUEUE_FLAG_STOPPED, q);
203         __blk_run_queue(q);
204 }
205 EXPORT_SYMBOL(blk_start_queue);
206
207 /**
208  * blk_stop_queue - stop a queue
209  * @q:    The &struct request_queue in question
210  *
211  * Description:
212  *   The Linux block layer assumes that a block driver will consume all
213  *   entries on the request queue when the request_fn strategy is called.
214  *   Often this will not happen, because of hardware limitations (queue
215  *   depth settings). If a device driver gets a 'queue full' response,
216  *   or if it simply chooses not to queue more I/O at one point, it can
217  *   call this function to prevent the request_fn from being called until
218  *   the driver has signalled it's ready to go again. This happens by calling
219  *   blk_start_queue() to restart queue operations. Queue lock must be held.
220  **/
221 void blk_stop_queue(struct request_queue *q)
222 {
223         cancel_delayed_work(&q->delay_work);
224         queue_flag_set(QUEUE_FLAG_STOPPED, q);
225 }
226 EXPORT_SYMBOL(blk_stop_queue);
227
228 /**
229  * blk_sync_queue - cancel any pending callbacks on a queue
230  * @q: the queue
231  *
232  * Description:
233  *     The block layer may perform asynchronous callback activity
234  *     on a queue, such as calling the unplug function after a timeout.
235  *     A block device may call blk_sync_queue to ensure that any
236  *     such activity is cancelled, thus allowing it to release resources
237  *     that the callbacks might use. The caller must already have made sure
238  *     that its ->make_request_fn will not re-add plugging prior to calling
239  *     this function.
240  *
241  *     This function does not cancel any asynchronous activity arising
242  *     out of elevator or throttling code. That would require elevaotor_exit()
243  *     and blkcg_exit_queue() to be called with queue lock initialized.
244  *
245  */
246 void blk_sync_queue(struct request_queue *q)
247 {
248         del_timer_sync(&q->timeout);
249         cancel_delayed_work_sync(&q->delay_work);
250 }
251 EXPORT_SYMBOL(blk_sync_queue);
252
253 /**
254  * __blk_run_queue_uncond - run a queue whether or not it has been stopped
255  * @q:  The queue to run
256  *
257  * Description:
258  *    Invoke request handling on a queue if there are any pending requests.
259  *    May be used to restart request handling after a request has completed.
260  *    This variant runs the queue whether or not the queue has been
261  *    stopped. Must be called with the queue lock held and interrupts
262  *    disabled. See also @blk_run_queue.
263  */
264 inline void __blk_run_queue_uncond(struct request_queue *q)
265 {
266         if (unlikely(blk_queue_dead(q)))
267                 return;
268
269         /*
270          * Some request_fn implementations, e.g. scsi_request_fn(), unlock
271          * the queue lock internally. As a result multiple threads may be
272          * running such a request function concurrently. Keep track of the
273          * number of active request_fn invocations such that blk_drain_queue()
274          * can wait until all these request_fn calls have finished.
275          */
276         q->request_fn_active++;
277         q->request_fn(q);
278         q->request_fn_active--;
279 }
280
281 /**
282  * __blk_run_queue - run a single device queue
283  * @q:  The queue to run
284  *
285  * Description:
286  *    See @blk_run_queue. This variant must be called with the queue lock
287  *    held and interrupts disabled.
288  */
289 void __blk_run_queue(struct request_queue *q)
290 {
291         if (unlikely(blk_queue_stopped(q)))
292                 return;
293
294         __blk_run_queue_uncond(q);
295 }
296 EXPORT_SYMBOL(__blk_run_queue);
297
298 /**
299  * blk_run_queue_async - run a single device queue in workqueue context
300  * @q:  The queue to run
301  *
302  * Description:
303  *    Tells kblockd to perform the equivalent of @blk_run_queue on behalf
304  *    of us. The caller must hold the queue lock.
305  */
306 void blk_run_queue_async(struct request_queue *q)
307 {
308         if (likely(!blk_queue_stopped(q) && !blk_queue_dead(q)))
309                 mod_delayed_work(kblockd_workqueue, &q->delay_work, 0);
310 }
311 EXPORT_SYMBOL(blk_run_queue_async);
312
313 /**
314  * blk_run_queue - run a single device queue
315  * @q: The queue to run
316  *
317  * Description:
318  *    Invoke request handling on this queue, if it has pending work to do.
319  *    May be used to restart queueing when a request has completed.
320  */
321 void blk_run_queue(struct request_queue *q)
322 {
323         unsigned long flags;
324
325         spin_lock_irqsave(q->queue_lock, flags);
326         __blk_run_queue(q);
327         spin_unlock_irqrestore(q->queue_lock, flags);
328 }
329 EXPORT_SYMBOL(blk_run_queue);
330
331 void blk_put_queue(struct request_queue *q)
332 {
333         kobject_put(&q->kobj);
334 }
335 EXPORT_SYMBOL(blk_put_queue);
336
337 /**
338  * __blk_drain_queue - drain requests from request_queue
339  * @q: queue to drain
340  * @drain_all: whether to drain all requests or only the ones w/ ELVPRIV
341  *
342  * Drain requests from @q.  If @drain_all is set, all requests are drained.
343  * If not, only ELVPRIV requests are drained.  The caller is responsible
344  * for ensuring that no new requests which need to be drained are queued.
345  */
346 static void __blk_drain_queue(struct request_queue *q, bool drain_all)
347         __releases(q->queue_lock)
348         __acquires(q->queue_lock)
349 {
350         int i;
351
352         lockdep_assert_held(q->queue_lock);
353
354         while (true) {
355                 bool drain = false;
356
357                 /*
358                  * The caller might be trying to drain @q before its
359                  * elevator is initialized.
360                  */
361                 if (q->elevator)
362                         elv_drain_elevator(q);
363
364                 blkcg_drain_queue(q);
365
366                 /*
367                  * This function might be called on a queue which failed
368                  * driver init after queue creation or is not yet fully
369                  * active yet.  Some drivers (e.g. fd and loop) get unhappy
370                  * in such cases.  Kick queue iff dispatch queue has
371                  * something on it and @q has request_fn set.
372                  */
373                 if (!list_empty(&q->queue_head) && q->request_fn)
374                         __blk_run_queue(q);
375
376                 drain |= q->nr_rqs_elvpriv;
377                 drain |= q->request_fn_active;
378
379                 /*
380                  * Unfortunately, requests are queued at and tracked from
381                  * multiple places and there's no single counter which can
382                  * be drained.  Check all the queues and counters.
383                  */
384                 if (drain_all) {
385                         drain |= !list_empty(&q->queue_head);
386                         for (i = 0; i < 2; i++) {
387                                 drain |= q->nr_rqs[i];
388                                 drain |= q->in_flight[i];
389                                 drain |= !list_empty(&q->flush_queue[i]);
390                         }
391                 }
392
393                 if (!drain)
394                         break;
395
396                 spin_unlock_irq(q->queue_lock);
397
398                 msleep(10);
399
400                 spin_lock_irq(q->queue_lock);
401         }
402
403         /*
404          * With queue marked dead, any woken up waiter will fail the
405          * allocation path, so the wakeup chaining is lost and we're
406          * left with hung waiters. We need to wake up those waiters.
407          */
408         if (q->request_fn) {
409                 struct request_list *rl;
410
411                 blk_queue_for_each_rl(rl, q)
412                         for (i = 0; i < ARRAY_SIZE(rl->wait); i++)
413                                 wake_up_all(&rl->wait[i]);
414         }
415 }
416
417 /**
418  * blk_queue_bypass_start - enter queue bypass mode
419  * @q: queue of interest
420  *
421  * In bypass mode, only the dispatch FIFO queue of @q is used.  This
422  * function makes @q enter bypass mode and drains all requests which were
423  * throttled or issued before.  On return, it's guaranteed that no request
424  * is being throttled or has ELVPRIV set and blk_queue_bypass() %true
425  * inside queue or RCU read lock.
426  */
427 void blk_queue_bypass_start(struct request_queue *q)
428 {
429         bool drain;
430
431         spin_lock_irq(q->queue_lock);
432         drain = !q->bypass_depth++;
433         queue_flag_set(QUEUE_FLAG_BYPASS, q);
434         spin_unlock_irq(q->queue_lock);
435
436         if (drain) {
437                 spin_lock_irq(q->queue_lock);
438                 __blk_drain_queue(q, false);
439                 spin_unlock_irq(q->queue_lock);
440
441                 /* ensure blk_queue_bypass() is %true inside RCU read lock */
442                 synchronize_rcu();
443         }
444 }
445 EXPORT_SYMBOL_GPL(blk_queue_bypass_start);
446
447 /**
448  * blk_queue_bypass_end - leave queue bypass mode
449  * @q: queue of interest
450  *
451  * Leave bypass mode and restore the normal queueing behavior.
452  */
453 void blk_queue_bypass_end(struct request_queue *q)
454 {
455         spin_lock_irq(q->queue_lock);
456         if (!--q->bypass_depth)
457                 queue_flag_clear(QUEUE_FLAG_BYPASS, q);
458         WARN_ON_ONCE(q->bypass_depth < 0);
459         spin_unlock_irq(q->queue_lock);
460 }
461 EXPORT_SYMBOL_GPL(blk_queue_bypass_end);
462
463 /**
464  * blk_cleanup_queue - shutdown a request queue
465  * @q: request queue to shutdown
466  *
467  * Mark @q DYING, drain all pending requests, mark @q DEAD, destroy and
468  * put it.  All future requests will be failed immediately with -ENODEV.
469  */
470 void blk_cleanup_queue(struct request_queue *q)
471 {
472         spinlock_t *lock = q->queue_lock;
473
474         /* mark @q DYING, no new request or merges will be allowed afterwards */
475         mutex_lock(&q->sysfs_lock);
476         queue_flag_set_unlocked(QUEUE_FLAG_DYING, q);
477         spin_lock_irq(lock);
478
479         /*
480          * A dying queue is permanently in bypass mode till released.  Note
481          * that, unlike blk_queue_bypass_start(), we aren't performing
482          * synchronize_rcu() after entering bypass mode to avoid the delay
483          * as some drivers create and destroy a lot of queues while
484          * probing.  This is still safe because blk_release_queue() will be
485          * called only after the queue refcnt drops to zero and nothing,
486          * RCU or not, would be traversing the queue by then.
487          */
488         q->bypass_depth++;
489         queue_flag_set(QUEUE_FLAG_BYPASS, q);
490
491         queue_flag_set(QUEUE_FLAG_NOMERGES, q);
492         queue_flag_set(QUEUE_FLAG_NOXMERGES, q);
493         queue_flag_set(QUEUE_FLAG_DYING, q);
494         spin_unlock_irq(lock);
495         mutex_unlock(&q->sysfs_lock);
496
497         /*
498          * Drain all requests queued before DYING marking. Set DEAD flag to
499          * prevent that q->request_fn() gets invoked after draining finished.
500          */
501         if (q->mq_ops) {
502                 blk_mq_drain_queue(q);
503                 spin_lock_irq(lock);
504         } else {
505                 spin_lock_irq(lock);
506                 __blk_drain_queue(q, true);
507         }
508         queue_flag_set(QUEUE_FLAG_DEAD, q);
509         spin_unlock_irq(lock);
510
511         /* @q won't process any more request, flush async actions */
512         del_timer_sync(&q->backing_dev_info.laptop_mode_wb_timer);
513         blk_sync_queue(q);
514
515         spin_lock_irq(lock);
516         if (q->queue_lock != &q->__queue_lock)
517                 q->queue_lock = &q->__queue_lock;
518         spin_unlock_irq(lock);
519
520         /* @q is and will stay empty, shutdown and put */
521         blk_put_queue(q);
522 }
523 EXPORT_SYMBOL(blk_cleanup_queue);
524
525 int blk_init_rl(struct request_list *rl, struct request_queue *q,
526                 gfp_t gfp_mask)
527 {
528         if (unlikely(rl->rq_pool))
529                 return 0;
530
531         rl->q = q;
532         rl->count[BLK_RW_SYNC] = rl->count[BLK_RW_ASYNC] = 0;
533         rl->starved[BLK_RW_SYNC] = rl->starved[BLK_RW_ASYNC] = 0;
534         init_waitqueue_head(&rl->wait[BLK_RW_SYNC]);
535         init_waitqueue_head(&rl->wait[BLK_RW_ASYNC]);
536
537         rl->rq_pool = mempool_create_node(BLKDEV_MIN_RQ, mempool_alloc_slab,
538                                           mempool_free_slab, request_cachep,
539                                           gfp_mask, q->node);
540         if (!rl->rq_pool)
541                 return -ENOMEM;
542
543         return 0;
544 }
545
546 void blk_exit_rl(struct request_list *rl)
547 {
548         if (rl->rq_pool)
549                 mempool_destroy(rl->rq_pool);
550 }
551
552 struct request_queue *blk_alloc_queue(gfp_t gfp_mask)
553 {
554         return blk_alloc_queue_node(gfp_mask, NUMA_NO_NODE);
555 }
556 EXPORT_SYMBOL(blk_alloc_queue);
557
558 struct request_queue *blk_alloc_queue_node(gfp_t gfp_mask, int node_id)
559 {
560         struct request_queue *q;
561         int err;
562
563         q = kmem_cache_alloc_node(blk_requestq_cachep,
564                                 gfp_mask | __GFP_ZERO, node_id);
565         if (!q)
566                 return NULL;
567
568         if (percpu_counter_init(&q->mq_usage_counter, 0))
569                 goto fail_q;
570
571         q->id = ida_simple_get(&blk_queue_ida, 0, 0, gfp_mask);
572         if (q->id < 0)
573                 goto fail_c;
574
575         q->backing_dev_info.ra_pages =
576                         (VM_MAX_READAHEAD * 1024) / PAGE_CACHE_SIZE;
577         q->backing_dev_info.state = 0;
578         q->backing_dev_info.capabilities = BDI_CAP_MAP_COPY;
579         q->backing_dev_info.name = "block";
580         q->node = node_id;
581
582         err = bdi_init(&q->backing_dev_info);
583         if (err)
584                 goto fail_id;
585
586         setup_timer(&q->backing_dev_info.laptop_mode_wb_timer,
587                     laptop_mode_timer_fn, (unsigned long) q);
588         setup_timer(&q->timeout, blk_rq_timed_out_timer, (unsigned long) q);
589         INIT_LIST_HEAD(&q->queue_head);
590         INIT_LIST_HEAD(&q->timeout_list);
591         INIT_LIST_HEAD(&q->icq_list);
592 #ifdef CONFIG_BLK_CGROUP
593         INIT_LIST_HEAD(&q->blkg_list);
594 #endif
595         INIT_LIST_HEAD(&q->flush_queue[0]);
596         INIT_LIST_HEAD(&q->flush_queue[1]);
597         INIT_LIST_HEAD(&q->flush_data_in_flight);
598         INIT_DELAYED_WORK(&q->delay_work, blk_delay_work);
599
600         kobject_init(&q->kobj, &blk_queue_ktype);
601
602         mutex_init(&q->sysfs_lock);
603         spin_lock_init(&q->__queue_lock);
604
605         /*
606          * By default initialize queue_lock to internal lock and driver can
607          * override it later if need be.
608          */
609         q->queue_lock = &q->__queue_lock;
610
611         /*
612          * A queue starts its life with bypass turned on to avoid
613          * unnecessary bypass on/off overhead and nasty surprises during
614          * init.  The initial bypass will be finished when the queue is
615          * registered by blk_register_queue().
616          */
617         q->bypass_depth = 1;
618         __set_bit(QUEUE_FLAG_BYPASS, &q->queue_flags);
619
620         init_waitqueue_head(&q->mq_freeze_wq);
621
622         if (blkcg_init_queue(q))
623                 goto fail_bdi;
624
625         return q;
626
627 fail_bdi:
628         bdi_destroy(&q->backing_dev_info);
629 fail_id:
630         ida_simple_remove(&blk_queue_ida, q->id);
631 fail_c:
632         percpu_counter_destroy(&q->mq_usage_counter);
633 fail_q:
634         kmem_cache_free(blk_requestq_cachep, q);
635         return NULL;
636 }
637 EXPORT_SYMBOL(blk_alloc_queue_node);
638
639 /**
640  * blk_init_queue  - prepare a request queue for use with a block device
641  * @rfn:  The function to be called to process requests that have been
642  *        placed on the queue.
643  * @lock: Request queue spin lock
644  *
645  * Description:
646  *    If a block device wishes to use the standard request handling procedures,
647  *    which sorts requests and coalesces adjacent requests, then it must
648  *    call blk_init_queue().  The function @rfn will be called when there
649  *    are requests on the queue that need to be processed.  If the device
650  *    supports plugging, then @rfn may not be called immediately when requests
651  *    are available on the queue, but may be called at some time later instead.
652  *    Plugged queues are generally unplugged when a buffer belonging to one
653  *    of the requests on the queue is needed, or due to memory pressure.
654  *
655  *    @rfn is not required, or even expected, to remove all requests off the
656  *    queue, but only as many as it can handle at a time.  If it does leave
657  *    requests on the queue, it is responsible for arranging that the requests
658  *    get dealt with eventually.
659  *
660  *    The queue spin lock must be held while manipulating the requests on the
661  *    request queue; this lock will be taken also from interrupt context, so irq
662  *    disabling is needed for it.
663  *
664  *    Function returns a pointer to the initialized request queue, or %NULL if
665  *    it didn't succeed.
666  *
667  * Note:
668  *    blk_init_queue() must be paired with a blk_cleanup_queue() call
669  *    when the block device is deactivated (such as at module unload).
670  **/
671
672 struct request_queue *blk_init_queue(request_fn_proc *rfn, spinlock_t *lock)
673 {
674         return blk_init_queue_node(rfn, lock, NUMA_NO_NODE);
675 }
676 EXPORT_SYMBOL(blk_init_queue);
677
678 struct request_queue *
679 blk_init_queue_node(request_fn_proc *rfn, spinlock_t *lock, int node_id)
680 {
681         struct request_queue *uninit_q, *q;
682
683         uninit_q = blk_alloc_queue_node(GFP_KERNEL, node_id);
684         if (!uninit_q)
685                 return NULL;
686
687         q = blk_init_allocated_queue(uninit_q, rfn, lock);
688         if (!q)
689                 blk_cleanup_queue(uninit_q);
690
691         return q;
692 }
693 EXPORT_SYMBOL(blk_init_queue_node);
694
695 struct request_queue *
696 blk_init_allocated_queue(struct request_queue *q, request_fn_proc *rfn,
697                          spinlock_t *lock)
698 {
699         if (!q)
700                 return NULL;
701
702         if (blk_init_rl(&q->root_rl, q, GFP_KERNEL))
703                 return NULL;
704
705         q->request_fn           = rfn;
706         q->prep_rq_fn           = NULL;
707         q->unprep_rq_fn         = NULL;
708         q->queue_flags          |= QUEUE_FLAG_DEFAULT;
709
710         /* Override internal queue lock with supplied lock pointer */
711         if (lock)
712                 q->queue_lock           = lock;
713
714         /*
715          * This also sets hw/phys segments, boundary and size
716          */
717         blk_queue_make_request(q, blk_queue_bio);
718
719         q->sg_reserved_size = INT_MAX;
720
721         /* Protect q->elevator from elevator_change */
722         mutex_lock(&q->sysfs_lock);
723
724         /* init elevator */
725         if (elevator_init(q, NULL)) {
726                 mutex_unlock(&q->sysfs_lock);
727                 return NULL;
728         }
729
730         mutex_unlock(&q->sysfs_lock);
731
732         return q;
733 }
734 EXPORT_SYMBOL(blk_init_allocated_queue);
735
736 bool blk_get_queue(struct request_queue *q)
737 {
738         if (likely(!blk_queue_dying(q))) {
739                 __blk_get_queue(q);
740                 return true;
741         }
742
743         return false;
744 }
745 EXPORT_SYMBOL(blk_get_queue);
746
747 static inline void blk_free_request(struct request_list *rl, struct request *rq)
748 {
749         if (rq->cmd_flags & REQ_ELVPRIV) {
750                 elv_put_request(rl->q, rq);
751                 if (rq->elv.icq)
752                         put_io_context(rq->elv.icq->ioc);
753         }
754
755         mempool_free(rq, rl->rq_pool);
756 }
757
758 /*
759  * ioc_batching returns true if the ioc is a valid batching request and
760  * should be given priority access to a request.
761  */
762 static inline int ioc_batching(struct request_queue *q, struct io_context *ioc)
763 {
764         if (!ioc)
765                 return 0;
766
767         /*
768          * Make sure the process is able to allocate at least 1 request
769          * even if the batch times out, otherwise we could theoretically
770          * lose wakeups.
771          */
772         return ioc->nr_batch_requests == q->nr_batching ||
773                 (ioc->nr_batch_requests > 0
774                 && time_before(jiffies, ioc->last_waited + BLK_BATCH_TIME));
775 }
776
777 /*
778  * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
779  * will cause the process to be a "batcher" on all queues in the system. This
780  * is the behaviour we want though - once it gets a wakeup it should be given
781  * a nice run.
782  */
783 static void ioc_set_batching(struct request_queue *q, struct io_context *ioc)
784 {
785         if (!ioc || ioc_batching(q, ioc))
786                 return;
787
788         ioc->nr_batch_requests = q->nr_batching;
789         ioc->last_waited = jiffies;
790 }
791
792 static void __freed_request(struct request_list *rl, int sync)
793 {
794         struct request_queue *q = rl->q;
795
796         /*
797          * bdi isn't aware of blkcg yet.  As all async IOs end up root
798          * blkcg anyway, just use root blkcg state.
799          */
800         if (rl == &q->root_rl &&
801             rl->count[sync] < queue_congestion_off_threshold(q))
802                 blk_clear_queue_congested(q, sync);
803
804         if (rl->count[sync] + 1 <= q->nr_requests) {
805                 if (waitqueue_active(&rl->wait[sync]))
806                         wake_up(&rl->wait[sync]);
807
808                 blk_clear_rl_full(rl, sync);
809         }
810 }
811
812 /*
813  * A request has just been released.  Account for it, update the full and
814  * congestion status, wake up any waiters.   Called under q->queue_lock.
815  */
816 static void freed_request(struct request_list *rl, unsigned int flags)
817 {
818         struct request_queue *q = rl->q;
819         int sync = rw_is_sync(flags);
820
821         q->nr_rqs[sync]--;
822         rl->count[sync]--;
823         if (flags & REQ_ELVPRIV)
824                 q->nr_rqs_elvpriv--;
825
826         __freed_request(rl, sync);
827
828         if (unlikely(rl->starved[sync ^ 1]))
829                 __freed_request(rl, sync ^ 1);
830 }
831
832 /*
833  * Determine if elevator data should be initialized when allocating the
834  * request associated with @bio.
835  */
836 static bool blk_rq_should_init_elevator(struct bio *bio)
837 {
838         if (!bio)
839                 return true;
840
841         /*
842          * Flush requests do not use the elevator so skip initialization.
843          * This allows a request to share the flush and elevator data.
844          */
845         if (bio->bi_rw & (REQ_FLUSH | REQ_FUA))
846                 return false;
847
848         return true;
849 }
850
851 /**
852  * rq_ioc - determine io_context for request allocation
853  * @bio: request being allocated is for this bio (can be %NULL)
854  *
855  * Determine io_context to use for request allocation for @bio.  May return
856  * %NULL if %current->io_context doesn't exist.
857  */
858 static struct io_context *rq_ioc(struct bio *bio)
859 {
860 #ifdef CONFIG_BLK_CGROUP
861         if (bio && bio->bi_ioc)
862                 return bio->bi_ioc;
863 #endif
864         return current->io_context;
865 }
866
867 /**
868  * __get_request - get a free request
869  * @rl: request list to allocate from
870  * @rw_flags: RW and SYNC flags
871  * @bio: bio to allocate request for (can be %NULL)
872  * @gfp_mask: allocation mask
873  *
874  * Get a free request from @q.  This function may fail under memory
875  * pressure or if @q is dead.
876  *
877  * Must be callled with @q->queue_lock held and,
878  * Returns %NULL on failure, with @q->queue_lock held.
879  * Returns !%NULL on success, with @q->queue_lock *not held*.
880  */
881 static struct request *__get_request(struct request_list *rl, int rw_flags,
882                                      struct bio *bio, gfp_t gfp_mask)
883 {
884         struct request_queue *q = rl->q;
885         struct request *rq;
886         struct elevator_type *et = q->elevator->type;
887         struct io_context *ioc = rq_ioc(bio);
888         struct io_cq *icq = NULL;
889         const bool is_sync = rw_is_sync(rw_flags) != 0;
890         int may_queue;
891
892         if (unlikely(blk_queue_dying(q)))
893                 return NULL;
894
895         may_queue = elv_may_queue(q, rw_flags);
896         if (may_queue == ELV_MQUEUE_NO)
897                 goto rq_starved;
898
899         if (rl->count[is_sync]+1 >= queue_congestion_on_threshold(q)) {
900                 if (rl->count[is_sync]+1 >= q->nr_requests) {
901                         /*
902                          * The queue will fill after this allocation, so set
903                          * it as full, and mark this process as "batching".
904                          * This process will be allowed to complete a batch of
905                          * requests, others will be blocked.
906                          */
907                         if (!blk_rl_full(rl, is_sync)) {
908                                 ioc_set_batching(q, ioc);
909                                 blk_set_rl_full(rl, is_sync);
910                         } else {
911                                 if (may_queue != ELV_MQUEUE_MUST
912                                                 && !ioc_batching(q, ioc)) {
913                                         /*
914                                          * The queue is full and the allocating
915                                          * process is not a "batcher", and not
916                                          * exempted by the IO scheduler
917                                          */
918                                         return NULL;
919                                 }
920                         }
921                 }
922                 /*
923                  * bdi isn't aware of blkcg yet.  As all async IOs end up
924                  * root blkcg anyway, just use root blkcg state.
925                  */
926                 if (rl == &q->root_rl)
927                         blk_set_queue_congested(q, is_sync);
928         }
929
930         /*
931          * Only allow batching queuers to allocate up to 50% over the defined
932          * limit of requests, otherwise we could have thousands of requests
933          * allocated with any setting of ->nr_requests
934          */
935         if (rl->count[is_sync] >= (3 * q->nr_requests / 2))
936                 return NULL;
937
938         q->nr_rqs[is_sync]++;
939         rl->count[is_sync]++;
940         rl->starved[is_sync] = 0;
941
942         /*
943          * Decide whether the new request will be managed by elevator.  If
944          * so, mark @rw_flags and increment elvpriv.  Non-zero elvpriv will
945          * prevent the current elevator from being destroyed until the new
946          * request is freed.  This guarantees icq's won't be destroyed and
947          * makes creating new ones safe.
948          *
949          * Also, lookup icq while holding queue_lock.  If it doesn't exist,
950          * it will be created after releasing queue_lock.
951          */
952         if (blk_rq_should_init_elevator(bio) && !blk_queue_bypass(q)) {
953                 rw_flags |= REQ_ELVPRIV;
954                 q->nr_rqs_elvpriv++;
955                 if (et->icq_cache && ioc)
956                         icq = ioc_lookup_icq(ioc, q);
957         }
958
959         if (blk_queue_io_stat(q))
960                 rw_flags |= REQ_IO_STAT;
961         spin_unlock_irq(q->queue_lock);
962
963         /* allocate and init request */
964         rq = mempool_alloc(rl->rq_pool, gfp_mask);
965         if (!rq)
966                 goto fail_alloc;
967
968         blk_rq_init(q, rq);
969         blk_rq_set_rl(rq, rl);
970         rq->cmd_flags = rw_flags | REQ_ALLOCED;
971
972         /* init elvpriv */
973         if (rw_flags & REQ_ELVPRIV) {
974                 if (unlikely(et->icq_cache && !icq)) {
975                         if (ioc)
976                                 icq = ioc_create_icq(ioc, q, gfp_mask);
977                         if (!icq)
978                                 goto fail_elvpriv;
979                 }
980
981                 rq->elv.icq = icq;
982                 if (unlikely(elv_set_request(q, rq, bio, gfp_mask)))
983                         goto fail_elvpriv;
984
985                 /* @rq->elv.icq holds io_context until @rq is freed */
986                 if (icq)
987                         get_io_context(icq->ioc);
988         }
989 out:
990         /*
991          * ioc may be NULL here, and ioc_batching will be false. That's
992          * OK, if the queue is under the request limit then requests need
993          * not count toward the nr_batch_requests limit. There will always
994          * be some limit enforced by BLK_BATCH_TIME.
995          */
996         if (ioc_batching(q, ioc))
997                 ioc->nr_batch_requests--;
998
999         trace_block_getrq(q, bio, rw_flags & 1);
1000         return rq;
1001
1002 fail_elvpriv:
1003         /*
1004          * elvpriv init failed.  ioc, icq and elvpriv aren't mempool backed
1005          * and may fail indefinitely under memory pressure and thus
1006          * shouldn't stall IO.  Treat this request as !elvpriv.  This will
1007          * disturb iosched and blkcg but weird is bettern than dead.
1008          */
1009         printk_ratelimited(KERN_WARNING "%s: request aux data allocation failed, iosched may be disturbed\n",
1010                            dev_name(q->backing_dev_info.dev));
1011
1012         rq->cmd_flags &= ~REQ_ELVPRIV;
1013         rq->elv.icq = NULL;
1014
1015         spin_lock_irq(q->queue_lock);
1016         q->nr_rqs_elvpriv--;
1017         spin_unlock_irq(q->queue_lock);
1018         goto out;
1019
1020 fail_alloc:
1021         /*
1022          * Allocation failed presumably due to memory. Undo anything we
1023          * might have messed up.
1024          *
1025          * Allocating task should really be put onto the front of the wait
1026          * queue, but this is pretty rare.
1027          */
1028         spin_lock_irq(q->queue_lock);
1029         freed_request(rl, rw_flags);
1030
1031         /*
1032          * in the very unlikely event that allocation failed and no
1033          * requests for this direction was pending, mark us starved so that
1034          * freeing of a request in the other direction will notice
1035          * us. another possible fix would be to split the rq mempool into
1036          * READ and WRITE
1037          */
1038 rq_starved:
1039         if (unlikely(rl->count[is_sync] == 0))
1040                 rl->starved[is_sync] = 1;
1041         return NULL;
1042 }
1043
1044 /**
1045  * get_request - get a free request
1046  * @q: request_queue to allocate request from
1047  * @rw_flags: RW and SYNC flags
1048  * @bio: bio to allocate request for (can be %NULL)
1049  * @gfp_mask: allocation mask
1050  *
1051  * Get a free request from @q.  If %__GFP_WAIT is set in @gfp_mask, this
1052  * function keeps retrying under memory pressure and fails iff @q is dead.
1053  *
1054  * Must be callled with @q->queue_lock held and,
1055  * Returns %NULL on failure, with @q->queue_lock held.
1056  * Returns !%NULL on success, with @q->queue_lock *not held*.
1057  */
1058 static struct request *get_request(struct request_queue *q, int rw_flags,
1059                                    struct bio *bio, gfp_t gfp_mask)
1060 {
1061         const bool is_sync = rw_is_sync(rw_flags) != 0;
1062         DEFINE_WAIT(wait);
1063         struct request_list *rl;
1064         struct request *rq;
1065
1066         rl = blk_get_rl(q, bio);        /* transferred to @rq on success */
1067 retry:
1068         rq = __get_request(rl, rw_flags, bio, gfp_mask);
1069         if (rq)
1070                 return rq;
1071
1072         if (!(gfp_mask & __GFP_WAIT) || unlikely(blk_queue_dying(q))) {
1073                 blk_put_rl(rl);
1074                 return NULL;
1075         }
1076
1077         /* wait on @rl and retry */
1078         prepare_to_wait_exclusive(&rl->wait[is_sync], &wait,
1079                                   TASK_UNINTERRUPTIBLE);
1080
1081         trace_block_sleeprq(q, bio, rw_flags & 1);
1082
1083         spin_unlock_irq(q->queue_lock);
1084         io_schedule();
1085
1086         /*
1087          * After sleeping, we become a "batching" process and will be able
1088          * to allocate at least one request, and up to a big batch of them
1089          * for a small period time.  See ioc_batching, ioc_set_batching
1090          */
1091         ioc_set_batching(q, current->io_context);
1092
1093         spin_lock_irq(q->queue_lock);
1094         finish_wait(&rl->wait[is_sync], &wait);
1095
1096         goto retry;
1097 }
1098
1099 static struct request *blk_old_get_request(struct request_queue *q, int rw,
1100                 gfp_t gfp_mask)
1101 {
1102         struct request *rq;
1103
1104         BUG_ON(rw != READ && rw != WRITE);
1105
1106         /* create ioc upfront */
1107         create_io_context(gfp_mask, q->node);
1108
1109         spin_lock_irq(q->queue_lock);
1110         rq = get_request(q, rw, NULL, gfp_mask);
1111         if (!rq)
1112                 spin_unlock_irq(q->queue_lock);
1113         /* q->queue_lock is unlocked at this point */
1114
1115         return rq;
1116 }
1117
1118 struct request *blk_get_request(struct request_queue *q, int rw, gfp_t gfp_mask)
1119 {
1120         if (q->mq_ops)
1121                 return blk_mq_alloc_request(q, rw, gfp_mask, false);
1122         else
1123                 return blk_old_get_request(q, rw, gfp_mask);
1124 }
1125 EXPORT_SYMBOL(blk_get_request);
1126
1127 /**
1128  * blk_make_request - given a bio, allocate a corresponding struct request.
1129  * @q: target request queue
1130  * @bio:  The bio describing the memory mappings that will be submitted for IO.
1131  *        It may be a chained-bio properly constructed by block/bio layer.
1132  * @gfp_mask: gfp flags to be used for memory allocation
1133  *
1134  * blk_make_request is the parallel of generic_make_request for BLOCK_PC
1135  * type commands. Where the struct request needs to be farther initialized by
1136  * the caller. It is passed a &struct bio, which describes the memory info of
1137  * the I/O transfer.
1138  *
1139  * The caller of blk_make_request must make sure that bi_io_vec
1140  * are set to describe the memory buffers. That bio_data_dir() will return
1141  * the needed direction of the request. (And all bio's in the passed bio-chain
1142  * are properly set accordingly)
1143  *
1144  * If called under none-sleepable conditions, mapped bio buffers must not
1145  * need bouncing, by calling the appropriate masked or flagged allocator,
1146  * suitable for the target device. Otherwise the call to blk_queue_bounce will
1147  * BUG.
1148  *
1149  * WARNING: When allocating/cloning a bio-chain, careful consideration should be
1150  * given to how you allocate bios. In particular, you cannot use __GFP_WAIT for
1151  * anything but the first bio in the chain. Otherwise you risk waiting for IO
1152  * completion of a bio that hasn't been submitted yet, thus resulting in a
1153  * deadlock. Alternatively bios should be allocated using bio_kmalloc() instead
1154  * of bio_alloc(), as that avoids the mempool deadlock.
1155  * If possible a big IO should be split into smaller parts when allocation
1156  * fails. Partial allocation should not be an error, or you risk a live-lock.
1157  */
1158 struct request *blk_make_request(struct request_queue *q, struct bio *bio,
1159                                  gfp_t gfp_mask)
1160 {
1161         struct request *rq = blk_get_request(q, bio_data_dir(bio), gfp_mask);
1162
1163         if (unlikely(!rq))
1164                 return ERR_PTR(-ENOMEM);
1165
1166         for_each_bio(bio) {
1167                 struct bio *bounce_bio = bio;
1168                 int ret;
1169
1170                 blk_queue_bounce(q, &bounce_bio);
1171                 ret = blk_rq_append_bio(q, rq, bounce_bio);
1172                 if (unlikely(ret)) {
1173                         blk_put_request(rq);
1174                         return ERR_PTR(ret);
1175                 }
1176         }
1177
1178         return rq;
1179 }
1180 EXPORT_SYMBOL(blk_make_request);
1181
1182 /**
1183  * blk_requeue_request - put a request back on queue
1184  * @q:          request queue where request should be inserted
1185  * @rq:         request to be inserted
1186  *
1187  * Description:
1188  *    Drivers often keep queueing requests until the hardware cannot accept
1189  *    more, when that condition happens we need to put the request back
1190  *    on the queue. Must be called with queue lock held.
1191  */
1192 void blk_requeue_request(struct request_queue *q, struct request *rq)
1193 {
1194         blk_delete_timer(rq);
1195         blk_clear_rq_complete(rq);
1196         trace_block_rq_requeue(q, rq);
1197
1198         if (blk_rq_tagged(rq))
1199                 blk_queue_end_tag(q, rq);
1200
1201         BUG_ON(blk_queued_rq(rq));
1202
1203         elv_requeue_request(q, rq);
1204 }
1205 EXPORT_SYMBOL(blk_requeue_request);
1206
1207 static void add_acct_request(struct request_queue *q, struct request *rq,
1208                              int where)
1209 {
1210         blk_account_io_start(rq, true);
1211         __elv_add_request(q, rq, where);
1212 }
1213
1214 static void part_round_stats_single(int cpu, struct hd_struct *part,
1215                                     unsigned long now)
1216 {
1217         if (now == part->stamp)
1218                 return;
1219
1220         if (part_in_flight(part)) {
1221                 __part_stat_add(cpu, part, time_in_queue,
1222                                 part_in_flight(part) * (now - part->stamp));
1223                 __part_stat_add(cpu, part, io_ticks, (now - part->stamp));
1224         }
1225         part->stamp = now;
1226 }
1227
1228 /**
1229  * part_round_stats() - Round off the performance stats on a struct disk_stats.
1230  * @cpu: cpu number for stats access
1231  * @part: target partition
1232  *
1233  * The average IO queue length and utilisation statistics are maintained
1234  * by observing the current state of the queue length and the amount of
1235  * time it has been in this state for.
1236  *
1237  * Normally, that accounting is done on IO completion, but that can result
1238  * in more than a second's worth of IO being accounted for within any one
1239  * second, leading to >100% utilisation.  To deal with that, we call this
1240  * function to do a round-off before returning the results when reading
1241  * /proc/diskstats.  This accounts immediately for all queue usage up to
1242  * the current jiffies and restarts the counters again.
1243  */
1244 void part_round_stats(int cpu, struct hd_struct *part)
1245 {
1246         unsigned long now = jiffies;
1247
1248         if (part->partno)
1249                 part_round_stats_single(cpu, &part_to_disk(part)->part0, now);
1250         part_round_stats_single(cpu, part, now);
1251 }
1252 EXPORT_SYMBOL_GPL(part_round_stats);
1253
1254 #ifdef CONFIG_PM_RUNTIME
1255 static void blk_pm_put_request(struct request *rq)
1256 {
1257         if (rq->q->dev && !(rq->cmd_flags & REQ_PM) && !--rq->q->nr_pending)
1258                 pm_runtime_mark_last_busy(rq->q->dev);
1259 }
1260 #else
1261 static inline void blk_pm_put_request(struct request *rq) {}
1262 #endif
1263
1264 /*
1265  * queue lock must be held
1266  */
1267 void __blk_put_request(struct request_queue *q, struct request *req)
1268 {
1269         if (unlikely(!q))
1270                 return;
1271
1272         blk_pm_put_request(req);
1273
1274         elv_completed_request(q, req);
1275
1276         /* this is a bio leak */
1277         WARN_ON(req->bio != NULL);
1278
1279         /*
1280          * Request may not have originated from ll_rw_blk. if not,
1281          * it didn't come out of our reserved rq pools
1282          */
1283         if (req->cmd_flags & REQ_ALLOCED) {
1284                 unsigned int flags = req->cmd_flags;
1285                 struct request_list *rl = blk_rq_rl(req);
1286
1287                 BUG_ON(!list_empty(&req->queuelist));
1288                 BUG_ON(!hlist_unhashed(&req->hash));
1289
1290                 blk_free_request(rl, req);
1291                 freed_request(rl, flags);
1292                 blk_put_rl(rl);
1293         }
1294 }
1295 EXPORT_SYMBOL_GPL(__blk_put_request);
1296
1297 void blk_put_request(struct request *req)
1298 {
1299         struct request_queue *q = req->q;
1300
1301         if (q->mq_ops)
1302                 blk_mq_free_request(req);
1303         else {
1304                 unsigned long flags;
1305
1306                 spin_lock_irqsave(q->queue_lock, flags);
1307                 __blk_put_request(q, req);
1308                 spin_unlock_irqrestore(q->queue_lock, flags);
1309         }
1310 }
1311 EXPORT_SYMBOL(blk_put_request);
1312
1313 /**
1314  * blk_add_request_payload - add a payload to a request
1315  * @rq: request to update
1316  * @page: page backing the payload
1317  * @len: length of the payload.
1318  *
1319  * This allows to later add a payload to an already submitted request by
1320  * a block driver.  The driver needs to take care of freeing the payload
1321  * itself.
1322  *
1323  * Note that this is a quite horrible hack and nothing but handling of
1324  * discard requests should ever use it.
1325  */
1326 void blk_add_request_payload(struct request *rq, struct page *page,
1327                 unsigned int len)
1328 {
1329         struct bio *bio = rq->bio;
1330
1331         bio->bi_io_vec->bv_page = page;
1332         bio->bi_io_vec->bv_offset = 0;
1333         bio->bi_io_vec->bv_len = len;
1334
1335         bio->bi_iter.bi_size = len;
1336         bio->bi_vcnt = 1;
1337         bio->bi_phys_segments = 1;
1338
1339         rq->__data_len = rq->resid_len = len;
1340         rq->nr_phys_segments = 1;
1341         rq->buffer = bio_data(bio);
1342 }
1343 EXPORT_SYMBOL_GPL(blk_add_request_payload);
1344
1345 bool bio_attempt_back_merge(struct request_queue *q, struct request *req,
1346                             struct bio *bio)
1347 {
1348         const int ff = bio->bi_rw & REQ_FAILFAST_MASK;
1349
1350         if (!ll_back_merge_fn(q, req, bio))
1351                 return false;
1352
1353         trace_block_bio_backmerge(q, req, bio);
1354
1355         if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
1356                 blk_rq_set_mixed_merge(req);
1357
1358         req->biotail->bi_next = bio;
1359         req->biotail = bio;
1360         req->__data_len += bio->bi_iter.bi_size;
1361         req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
1362
1363         blk_account_io_start(req, false);
1364         return true;
1365 }
1366
1367 bool bio_attempt_front_merge(struct request_queue *q, struct request *req,
1368                              struct bio *bio)
1369 {
1370         const int ff = bio->bi_rw & REQ_FAILFAST_MASK;
1371
1372         if (!ll_front_merge_fn(q, req, bio))
1373                 return false;
1374
1375         trace_block_bio_frontmerge(q, req, bio);
1376
1377         if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
1378                 blk_rq_set_mixed_merge(req);
1379
1380         bio->bi_next = req->bio;
1381         req->bio = bio;
1382
1383         /*
1384          * may not be valid. if the low level driver said
1385          * it didn't need a bounce buffer then it better
1386          * not touch req->buffer either...
1387          */
1388         req->buffer = bio_data(bio);
1389         req->__sector = bio->bi_iter.bi_sector;
1390         req->__data_len += bio->bi_iter.bi_size;
1391         req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
1392
1393         blk_account_io_start(req, false);
1394         return true;
1395 }
1396
1397 /**
1398  * blk_attempt_plug_merge - try to merge with %current's plugged list
1399  * @q: request_queue new bio is being queued at
1400  * @bio: new bio being queued
1401  * @request_count: out parameter for number of traversed plugged requests
1402  *
1403  * Determine whether @bio being queued on @q can be merged with a request
1404  * on %current's plugged list.  Returns %true if merge was successful,
1405  * otherwise %false.
1406  *
1407  * Plugging coalesces IOs from the same issuer for the same purpose without
1408  * going through @q->queue_lock.  As such it's more of an issuing mechanism
1409  * than scheduling, and the request, while may have elvpriv data, is not
1410  * added on the elevator at this point.  In addition, we don't have
1411  * reliable access to the elevator outside queue lock.  Only check basic
1412  * merging parameters without querying the elevator.
1413  */
1414 bool blk_attempt_plug_merge(struct request_queue *q, struct bio *bio,
1415                             unsigned int *request_count)
1416 {
1417         struct blk_plug *plug;
1418         struct request *rq;
1419         bool ret = false;
1420         struct list_head *plug_list;
1421
1422         if (blk_queue_nomerges(q))
1423                 goto out;
1424
1425         plug = current->plug;
1426         if (!plug)
1427                 goto out;
1428         *request_count = 0;
1429
1430         if (q->mq_ops)
1431                 plug_list = &plug->mq_list;
1432         else
1433                 plug_list = &plug->list;
1434
1435         list_for_each_entry_reverse(rq, plug_list, queuelist) {
1436                 int el_ret;
1437
1438                 if (rq->q == q)
1439                         (*request_count)++;
1440
1441                 if (rq->q != q || !blk_rq_merge_ok(rq, bio))
1442                         continue;
1443
1444                 el_ret = blk_try_merge(rq, bio);
1445                 if (el_ret == ELEVATOR_BACK_MERGE) {
1446                         ret = bio_attempt_back_merge(q, rq, bio);
1447                         if (ret)
1448                                 break;
1449                 } else if (el_ret == ELEVATOR_FRONT_MERGE) {
1450                         ret = bio_attempt_front_merge(q, rq, bio);
1451                         if (ret)
1452                                 break;
1453                 }
1454         }
1455 out:
1456         return ret;
1457 }
1458
1459 void init_request_from_bio(struct request *req, struct bio *bio)
1460 {
1461         req->cmd_type = REQ_TYPE_FS;
1462
1463         req->cmd_flags |= bio->bi_rw & REQ_COMMON_MASK;
1464         if (bio->bi_rw & REQ_RAHEAD)
1465                 req->cmd_flags |= REQ_FAILFAST_MASK;
1466
1467         req->errors = 0;
1468         req->__sector = bio->bi_iter.bi_sector;
1469         req->ioprio = bio_prio(bio);
1470         blk_rq_bio_prep(req->q, req, bio);
1471 }
1472
1473 void blk_queue_bio(struct request_queue *q, struct bio *bio)
1474 {
1475         const bool sync = !!(bio->bi_rw & REQ_SYNC);
1476         struct blk_plug *plug;
1477         int el_ret, rw_flags, where = ELEVATOR_INSERT_SORT;
1478         struct request *req;
1479         unsigned int request_count = 0;
1480
1481         /*
1482          * low level driver can indicate that it wants pages above a
1483          * certain limit bounced to low memory (ie for highmem, or even
1484          * ISA dma in theory)
1485          */
1486         blk_queue_bounce(q, &bio);
1487
1488         if (bio_integrity_enabled(bio) && bio_integrity_prep(bio)) {
1489                 bio_endio(bio, -EIO);
1490                 return;
1491         }
1492
1493         if (bio->bi_rw & (REQ_FLUSH | REQ_FUA)) {
1494                 spin_lock_irq(q->queue_lock);
1495                 where = ELEVATOR_INSERT_FLUSH;
1496                 goto get_rq;
1497         }
1498
1499         /*
1500          * Check if we can merge with the plugged list before grabbing
1501          * any locks.
1502          */
1503         if (blk_attempt_plug_merge(q, bio, &request_count))
1504                 return;
1505
1506         spin_lock_irq(q->queue_lock);
1507
1508         el_ret = elv_merge(q, &req, bio);
1509         if (el_ret == ELEVATOR_BACK_MERGE) {
1510                 if (bio_attempt_back_merge(q, req, bio)) {
1511                         elv_bio_merged(q, req, bio);
1512                         if (!attempt_back_merge(q, req))
1513                                 elv_merged_request(q, req, el_ret);
1514                         goto out_unlock;
1515                 }
1516         } else if (el_ret == ELEVATOR_FRONT_MERGE) {
1517                 if (bio_attempt_front_merge(q, req, bio)) {
1518                         elv_bio_merged(q, req, bio);
1519                         if (!attempt_front_merge(q, req))
1520                                 elv_merged_request(q, req, el_ret);
1521                         goto out_unlock;
1522                 }
1523         }
1524
1525 get_rq:
1526         /*
1527          * This sync check and mask will be re-done in init_request_from_bio(),
1528          * but we need to set it earlier to expose the sync flag to the
1529          * rq allocator and io schedulers.
1530          */
1531         rw_flags = bio_data_dir(bio);
1532         if (sync)
1533                 rw_flags |= REQ_SYNC;
1534
1535         /*
1536          * Grab a free request. This is might sleep but can not fail.
1537          * Returns with the queue unlocked.
1538          */
1539         req = get_request(q, rw_flags, bio, GFP_NOIO);
1540         if (unlikely(!req)) {
1541                 bio_endio(bio, -ENODEV);        /* @q is dead */
1542                 goto out_unlock;
1543         }
1544
1545         /*
1546          * After dropping the lock and possibly sleeping here, our request
1547          * may now be mergeable after it had proven unmergeable (above).
1548          * We don't worry about that case for efficiency. It won't happen
1549          * often, and the elevators are able to handle it.
1550          */
1551         init_request_from_bio(req, bio);
1552
1553         if (test_bit(QUEUE_FLAG_SAME_COMP, &q->queue_flags))
1554                 req->cpu = raw_smp_processor_id();
1555
1556         plug = current->plug;
1557         if (plug) {
1558                 /*
1559                  * If this is the first request added after a plug, fire
1560                  * of a plug trace.
1561                  */
1562                 if (!request_count)
1563                         trace_block_plug(q);
1564                 else {
1565                         if (request_count >= BLK_MAX_REQUEST_COUNT) {
1566                                 blk_flush_plug_list(plug, false);
1567                                 trace_block_plug(q);
1568                         }
1569                 }
1570                 list_add_tail(&req->queuelist, &plug->list);
1571                 blk_account_io_start(req, true);
1572         } else {
1573                 spin_lock_irq(q->queue_lock);
1574                 add_acct_request(q, req, where);
1575                 __blk_run_queue(q);
1576 out_unlock:
1577                 spin_unlock_irq(q->queue_lock);
1578         }
1579 }
1580 EXPORT_SYMBOL_GPL(blk_queue_bio);       /* for device mapper only */
1581
1582 /*
1583  * If bio->bi_dev is a partition, remap the location
1584  */
1585 static inline void blk_partition_remap(struct bio *bio)
1586 {
1587         struct block_device *bdev = bio->bi_bdev;
1588
1589         if (bio_sectors(bio) && bdev != bdev->bd_contains) {
1590                 struct hd_struct *p = bdev->bd_part;
1591
1592                 bio->bi_iter.bi_sector += p->start_sect;
1593                 bio->bi_bdev = bdev->bd_contains;
1594
1595                 trace_block_bio_remap(bdev_get_queue(bio->bi_bdev), bio,
1596                                       bdev->bd_dev,
1597                                       bio->bi_iter.bi_sector - p->start_sect);
1598         }
1599 }
1600
1601 static void handle_bad_sector(struct bio *bio)
1602 {
1603         char b[BDEVNAME_SIZE];
1604
1605         printk(KERN_INFO "attempt to access beyond end of device\n");
1606         printk(KERN_INFO "%s: rw=%ld, want=%Lu, limit=%Lu\n",
1607                         bdevname(bio->bi_bdev, b),
1608                         bio->bi_rw,
1609                         (unsigned long long)bio_end_sector(bio),
1610                         (long long)(i_size_read(bio->bi_bdev->bd_inode) >> 9));
1611
1612         set_bit(BIO_EOF, &bio->bi_flags);
1613 }
1614
1615 #ifdef CONFIG_FAIL_MAKE_REQUEST
1616
1617 static DECLARE_FAULT_ATTR(fail_make_request);
1618
1619 static int __init setup_fail_make_request(char *str)
1620 {
1621         return setup_fault_attr(&fail_make_request, str);
1622 }
1623 __setup("fail_make_request=", setup_fail_make_request);
1624
1625 static bool should_fail_request(struct hd_struct *part, unsigned int bytes)
1626 {
1627         return part->make_it_fail && should_fail(&fail_make_request, bytes);
1628 }
1629
1630 static int __init fail_make_request_debugfs(void)
1631 {
1632         struct dentry *dir = fault_create_debugfs_attr("fail_make_request",
1633                                                 NULL, &fail_make_request);
1634
1635         return IS_ERR(dir) ? PTR_ERR(dir) : 0;
1636 }
1637
1638 late_initcall(fail_make_request_debugfs);
1639
1640 #else /* CONFIG_FAIL_MAKE_REQUEST */
1641
1642 static inline bool should_fail_request(struct hd_struct *part,
1643                                         unsigned int bytes)
1644 {
1645         return false;
1646 }
1647
1648 #endif /* CONFIG_FAIL_MAKE_REQUEST */
1649
1650 /*
1651  * Check whether this bio extends beyond the end of the device.
1652  */
1653 static inline int bio_check_eod(struct bio *bio, unsigned int nr_sectors)
1654 {
1655         sector_t maxsector;
1656
1657         if (!nr_sectors)
1658                 return 0;
1659
1660         /* Test device or partition size, when known. */
1661         maxsector = i_size_read(bio->bi_bdev->bd_inode) >> 9;
1662         if (maxsector) {
1663                 sector_t sector = bio->bi_iter.bi_sector;
1664
1665                 if (maxsector < nr_sectors || maxsector - nr_sectors < sector) {
1666                         /*
1667                          * This may well happen - the kernel calls bread()
1668                          * without checking the size of the device, e.g., when
1669                          * mounting a device.
1670                          */
1671                         handle_bad_sector(bio);
1672                         return 1;
1673                 }
1674         }
1675
1676         return 0;
1677 }
1678
1679 static noinline_for_stack bool
1680 generic_make_request_checks(struct bio *bio)
1681 {
1682         struct request_queue *q;
1683         int nr_sectors = bio_sectors(bio);
1684         int err = -EIO;
1685         char b[BDEVNAME_SIZE];
1686         struct hd_struct *part;
1687
1688         might_sleep();
1689
1690         if (bio_check_eod(bio, nr_sectors))
1691                 goto end_io;
1692
1693         q = bdev_get_queue(bio->bi_bdev);
1694         if (unlikely(!q)) {
1695                 printk(KERN_ERR
1696                        "generic_make_request: Trying to access "
1697                         "nonexistent block-device %s (%Lu)\n",
1698                         bdevname(bio->bi_bdev, b),
1699                         (long long) bio->bi_iter.bi_sector);
1700                 goto end_io;
1701         }
1702
1703         if (likely(bio_is_rw(bio) &&
1704                    nr_sectors > queue_max_hw_sectors(q))) {
1705                 printk(KERN_ERR "bio too big device %s (%u > %u)\n",
1706                        bdevname(bio->bi_bdev, b),
1707                        bio_sectors(bio),
1708                        queue_max_hw_sectors(q));
1709                 goto end_io;
1710         }
1711
1712         part = bio->bi_bdev->bd_part;
1713         if (should_fail_request(part, bio->bi_iter.bi_size) ||
1714             should_fail_request(&part_to_disk(part)->part0,
1715                                 bio->bi_iter.bi_size))
1716                 goto end_io;
1717
1718         /*
1719          * If this device has partitions, remap block n
1720          * of partition p to block n+start(p) of the disk.
1721          */
1722         blk_partition_remap(bio);
1723
1724         if (bio_check_eod(bio, nr_sectors))
1725                 goto end_io;
1726
1727         /*
1728          * Filter flush bio's early so that make_request based
1729          * drivers without flush support don't have to worry
1730          * about them.
1731          */
1732         if ((bio->bi_rw & (REQ_FLUSH | REQ_FUA)) && !q->flush_flags) {
1733                 bio->bi_rw &= ~(REQ_FLUSH | REQ_FUA);
1734                 if (!nr_sectors) {
1735                         err = 0;
1736                         goto end_io;
1737                 }
1738         }
1739
1740         if ((bio->bi_rw & REQ_DISCARD) &&
1741             (!blk_queue_discard(q) ||
1742              ((bio->bi_rw & REQ_SECURE) && !blk_queue_secdiscard(q)))) {
1743                 err = -EOPNOTSUPP;
1744                 goto end_io;
1745         }
1746
1747         if (bio->bi_rw & REQ_WRITE_SAME && !bdev_write_same(bio->bi_bdev)) {
1748                 err = -EOPNOTSUPP;
1749                 goto end_io;
1750         }
1751
1752         /*
1753          * Various block parts want %current->io_context and lazy ioc
1754          * allocation ends up trading a lot of pain for a small amount of
1755          * memory.  Just allocate it upfront.  This may fail and block
1756          * layer knows how to live with it.
1757          */
1758         create_io_context(GFP_ATOMIC, q->node);
1759
1760         if (blk_throtl_bio(q, bio))
1761                 return false;   /* throttled, will be resubmitted later */
1762
1763         trace_block_bio_queue(q, bio);
1764         return true;
1765
1766 end_io:
1767         bio_endio(bio, err);
1768         return false;
1769 }
1770
1771 /**
1772  * generic_make_request - hand a buffer to its device driver for I/O
1773  * @bio:  The bio describing the location in memory and on the device.
1774  *
1775  * generic_make_request() is used to make I/O requests of block
1776  * devices. It is passed a &struct bio, which describes the I/O that needs
1777  * to be done.
1778  *
1779  * generic_make_request() does not return any status.  The
1780  * success/failure status of the request, along with notification of
1781  * completion, is delivered asynchronously through the bio->bi_end_io
1782  * function described (one day) else where.
1783  *
1784  * The caller of generic_make_request must make sure that bi_io_vec
1785  * are set to describe the memory buffer, and that bi_dev and bi_sector are
1786  * set to describe the device address, and the
1787  * bi_end_io and optionally bi_private are set to describe how
1788  * completion notification should be signaled.
1789  *
1790  * generic_make_request and the drivers it calls may use bi_next if this
1791  * bio happens to be merged with someone else, and may resubmit the bio to
1792  * a lower device by calling into generic_make_request recursively, which
1793  * means the bio should NOT be touched after the call to ->make_request_fn.
1794  */
1795 void generic_make_request(struct bio *bio)
1796 {
1797         struct bio_list bio_list_on_stack;
1798
1799         if (!generic_make_request_checks(bio))
1800                 return;
1801
1802         /*
1803          * We only want one ->make_request_fn to be active at a time, else
1804          * stack usage with stacked devices could be a problem.  So use
1805          * current->bio_list to keep a list of requests submited by a
1806          * make_request_fn function.  current->bio_list is also used as a
1807          * flag to say if generic_make_request is currently active in this
1808          * task or not.  If it is NULL, then no make_request is active.  If
1809          * it is non-NULL, then a make_request is active, and new requests
1810          * should be added at the tail
1811          */
1812         if (current->bio_list) {
1813                 bio_list_add(current->bio_list, bio);
1814                 return;
1815         }
1816
1817         /* following loop may be a bit non-obvious, and so deserves some
1818          * explanation.
1819          * Before entering the loop, bio->bi_next is NULL (as all callers
1820          * ensure that) so we have a list with a single bio.
1821          * We pretend that we have just taken it off a longer list, so
1822          * we assign bio_list to a pointer to the bio_list_on_stack,
1823          * thus initialising the bio_list of new bios to be
1824          * added.  ->make_request() may indeed add some more bios
1825          * through a recursive call to generic_make_request.  If it
1826          * did, we find a non-NULL value in bio_list and re-enter the loop
1827          * from the top.  In this case we really did just take the bio
1828          * of the top of the list (no pretending) and so remove it from
1829          * bio_list, and call into ->make_request() again.
1830          */
1831         BUG_ON(bio->bi_next);
1832         bio_list_init(&bio_list_on_stack);
1833         current->bio_list = &bio_list_on_stack;
1834         do {
1835                 struct request_queue *q = bdev_get_queue(bio->bi_bdev);
1836
1837                 q->make_request_fn(q, bio);
1838
1839                 bio = bio_list_pop(current->bio_list);
1840         } while (bio);
1841         current->bio_list = NULL; /* deactivate */
1842 }
1843 EXPORT_SYMBOL(generic_make_request);
1844
1845 /**
1846  * submit_bio - submit a bio to the block device layer for I/O
1847  * @rw: whether to %READ or %WRITE, or maybe to %READA (read ahead)
1848  * @bio: The &struct bio which describes the I/O
1849  *
1850  * submit_bio() is very similar in purpose to generic_make_request(), and
1851  * uses that function to do most of the work. Both are fairly rough
1852  * interfaces; @bio must be presetup and ready for I/O.
1853  *
1854  */
1855 void submit_bio(int rw, struct bio *bio)
1856 {
1857         bio->bi_rw |= rw;
1858
1859         /*
1860          * If it's a regular read/write or a barrier with data attached,
1861          * go through the normal accounting stuff before submission.
1862          */
1863         if (bio_has_data(bio)) {
1864                 unsigned int count;
1865
1866                 if (unlikely(rw & REQ_WRITE_SAME))
1867                         count = bdev_logical_block_size(bio->bi_bdev) >> 9;
1868                 else
1869                         count = bio_sectors(bio);
1870
1871                 if (rw & WRITE) {
1872                         count_vm_events(PGPGOUT, count);
1873                 } else {
1874                         task_io_account_read(bio->bi_iter.bi_size);
1875                         count_vm_events(PGPGIN, count);
1876                 }
1877
1878                 if (unlikely(block_dump)) {
1879                         char b[BDEVNAME_SIZE];
1880                         printk(KERN_DEBUG "%s(%d): %s block %Lu on %s (%u sectors)\n",
1881                         current->comm, task_pid_nr(current),
1882                                 (rw & WRITE) ? "WRITE" : "READ",
1883                                 (unsigned long long)bio->bi_iter.bi_sector,
1884                                 bdevname(bio->bi_bdev, b),
1885                                 count);
1886                 }
1887         }
1888
1889         generic_make_request(bio);
1890 }
1891 EXPORT_SYMBOL(submit_bio);
1892
1893 /**
1894  * blk_rq_check_limits - Helper function to check a request for the queue limit
1895  * @q:  the queue
1896  * @rq: the request being checked
1897  *
1898  * Description:
1899  *    @rq may have been made based on weaker limitations of upper-level queues
1900  *    in request stacking drivers, and it may violate the limitation of @q.
1901  *    Since the block layer and the underlying device driver trust @rq
1902  *    after it is inserted to @q, it should be checked against @q before
1903  *    the insertion using this generic function.
1904  *
1905  *    This function should also be useful for request stacking drivers
1906  *    in some cases below, so export this function.
1907  *    Request stacking drivers like request-based dm may change the queue
1908  *    limits while requests are in the queue (e.g. dm's table swapping).
1909  *    Such request stacking drivers should check those requests agaist
1910  *    the new queue limits again when they dispatch those requests,
1911  *    although such checkings are also done against the old queue limits
1912  *    when submitting requests.
1913  */
1914 int blk_rq_check_limits(struct request_queue *q, struct request *rq)
1915 {
1916         if (!rq_mergeable(rq))
1917                 return 0;
1918
1919         if (blk_rq_sectors(rq) > blk_queue_get_max_sectors(q, rq->cmd_flags)) {
1920                 printk(KERN_ERR "%s: over max size limit.\n", __func__);
1921                 return -EIO;
1922         }
1923
1924         /*
1925          * queue's settings related to segment counting like q->bounce_pfn
1926          * may differ from that of other stacking queues.
1927          * Recalculate it to check the request correctly on this queue's
1928          * limitation.
1929          */
1930         blk_recalc_rq_segments(rq);
1931         if (rq->nr_phys_segments > queue_max_segments(q)) {
1932                 printk(KERN_ERR "%s: over max segments limit.\n", __func__);
1933                 return -EIO;
1934         }
1935
1936         return 0;
1937 }
1938 EXPORT_SYMBOL_GPL(blk_rq_check_limits);
1939
1940 /**
1941  * blk_insert_cloned_request - Helper for stacking drivers to submit a request
1942  * @q:  the queue to submit the request
1943  * @rq: the request being queued
1944  */
1945 int blk_insert_cloned_request(struct request_queue *q, struct request *rq)
1946 {
1947         unsigned long flags;
1948         int where = ELEVATOR_INSERT_BACK;
1949
1950         if (blk_rq_check_limits(q, rq))
1951                 return -EIO;
1952
1953         if (rq->rq_disk &&
1954             should_fail_request(&rq->rq_disk->part0, blk_rq_bytes(rq)))
1955                 return -EIO;
1956
1957         spin_lock_irqsave(q->queue_lock, flags);
1958         if (unlikely(blk_queue_dying(q))) {
1959                 spin_unlock_irqrestore(q->queue_lock, flags);
1960                 return -ENODEV;
1961         }
1962
1963         /*
1964          * Submitting request must be dequeued before calling this function
1965          * because it will be linked to another request_queue
1966          */
1967         BUG_ON(blk_queued_rq(rq));
1968
1969         if (rq->cmd_flags & (REQ_FLUSH|REQ_FUA))
1970                 where = ELEVATOR_INSERT_FLUSH;
1971
1972         add_acct_request(q, rq, where);
1973         if (where == ELEVATOR_INSERT_FLUSH)
1974                 __blk_run_queue(q);
1975         spin_unlock_irqrestore(q->queue_lock, flags);
1976
1977         return 0;
1978 }
1979 EXPORT_SYMBOL_GPL(blk_insert_cloned_request);
1980
1981 /**
1982  * blk_rq_err_bytes - determine number of bytes till the next failure boundary
1983  * @rq: request to examine
1984  *
1985  * Description:
1986  *     A request could be merge of IOs which require different failure
1987  *     handling.  This function determines the number of bytes which
1988  *     can be failed from the beginning of the request without
1989  *     crossing into area which need to be retried further.
1990  *
1991  * Return:
1992  *     The number of bytes to fail.
1993  *
1994  * Context:
1995  *     queue_lock must be held.
1996  */
1997 unsigned int blk_rq_err_bytes(const struct request *rq)
1998 {
1999         unsigned int ff = rq->cmd_flags & REQ_FAILFAST_MASK;
2000         unsigned int bytes = 0;
2001         struct bio *bio;
2002
2003         if (!(rq->cmd_flags & REQ_MIXED_MERGE))
2004                 return blk_rq_bytes(rq);
2005
2006         /*
2007          * Currently the only 'mixing' which can happen is between
2008          * different fastfail types.  We can safely fail portions
2009          * which have all the failfast bits that the first one has -
2010          * the ones which are at least as eager to fail as the first
2011          * one.
2012          */
2013         for (bio = rq->bio; bio; bio = bio->bi_next) {
2014                 if ((bio->bi_rw & ff) != ff)
2015                         break;
2016                 bytes += bio->bi_iter.bi_size;
2017         }
2018
2019         /* this could lead to infinite loop */
2020         BUG_ON(blk_rq_bytes(rq) && !bytes);
2021         return bytes;
2022 }
2023 EXPORT_SYMBOL_GPL(blk_rq_err_bytes);
2024
2025 void blk_account_io_completion(struct request *req, unsigned int bytes)
2026 {
2027         if (blk_do_io_stat(req)) {
2028                 const int rw = rq_data_dir(req);
2029                 struct hd_struct *part;
2030                 int cpu;
2031
2032                 cpu = part_stat_lock();
2033                 part = req->part;
2034                 part_stat_add(cpu, part, sectors[rw], bytes >> 9);
2035                 part_stat_unlock();
2036         }
2037 }
2038
2039 void blk_account_io_done(struct request *req)
2040 {
2041         /*
2042          * Account IO completion.  flush_rq isn't accounted as a
2043          * normal IO on queueing nor completion.  Accounting the
2044          * containing request is enough.
2045          */
2046         if (blk_do_io_stat(req) && !(req->cmd_flags & REQ_FLUSH_SEQ)) {
2047                 unsigned long duration = jiffies - req->start_time;
2048                 const int rw = rq_data_dir(req);
2049                 struct hd_struct *part;
2050                 int cpu;
2051
2052                 cpu = part_stat_lock();
2053                 part = req->part;
2054
2055                 part_stat_inc(cpu, part, ios[rw]);
2056                 part_stat_add(cpu, part, ticks[rw], duration);
2057                 part_round_stats(cpu, part);
2058                 part_dec_in_flight(part, rw);
2059
2060                 hd_struct_put(part);
2061                 part_stat_unlock();
2062         }
2063 }
2064
2065 #ifdef CONFIG_PM_RUNTIME
2066 /*
2067  * Don't process normal requests when queue is suspended
2068  * or in the process of suspending/resuming
2069  */
2070 static struct request *blk_pm_peek_request(struct request_queue *q,
2071                                            struct request *rq)
2072 {
2073         if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
2074             (q->rpm_status != RPM_ACTIVE && !(rq->cmd_flags & REQ_PM))))
2075                 return NULL;
2076         else
2077                 return rq;
2078 }
2079 #else
2080 static inline struct request *blk_pm_peek_request(struct request_queue *q,
2081                                                   struct request *rq)
2082 {
2083         return rq;
2084 }
2085 #endif
2086
2087 void blk_account_io_start(struct request *rq, bool new_io)
2088 {
2089         struct hd_struct *part;
2090         int rw = rq_data_dir(rq);
2091         int cpu;
2092
2093         if (!blk_do_io_stat(rq))
2094                 return;
2095
2096         cpu = part_stat_lock();
2097
2098         if (!new_io) {
2099                 part = rq->part;
2100                 part_stat_inc(cpu, part, merges[rw]);
2101         } else {
2102                 part = disk_map_sector_rcu(rq->rq_disk, blk_rq_pos(rq));
2103                 if (!hd_struct_try_get(part)) {
2104                         /*
2105                          * The partition is already being removed,
2106                          * the request will be accounted on the disk only
2107                          *
2108                          * We take a reference on disk->part0 although that
2109                          * partition will never be deleted, so we can treat
2110                          * it as any other partition.
2111                          */
2112                         part = &rq->rq_disk->part0;
2113                         hd_struct_get(part);
2114                 }
2115                 part_round_stats(cpu, part);
2116                 part_inc_in_flight(part, rw);
2117                 rq->part = part;
2118         }
2119
2120         part_stat_unlock();
2121 }
2122
2123 /**
2124  * blk_peek_request - peek at the top of a request queue
2125  * @q: request queue to peek at
2126  *
2127  * Description:
2128  *     Return the request at the top of @q.  The returned request
2129  *     should be started using blk_start_request() before LLD starts
2130  *     processing it.
2131  *
2132  * Return:
2133  *     Pointer to the request at the top of @q if available.  Null
2134  *     otherwise.
2135  *
2136  * Context:
2137  *     queue_lock must be held.
2138  */
2139 struct request *blk_peek_request(struct request_queue *q)
2140 {
2141         struct request *rq;
2142         int ret;
2143
2144         while ((rq = __elv_next_request(q)) != NULL) {
2145
2146                 rq = blk_pm_peek_request(q, rq);
2147                 if (!rq)
2148                         break;
2149
2150                 if (!(rq->cmd_flags & REQ_STARTED)) {
2151                         /*
2152                          * This is the first time the device driver
2153                          * sees this request (possibly after
2154                          * requeueing).  Notify IO scheduler.
2155                          */
2156                         if (rq->cmd_flags & REQ_SORTED)
2157                                 elv_activate_rq(q, rq);
2158
2159                         /*
2160                          * just mark as started even if we don't start
2161                          * it, a request that has been delayed should
2162                          * not be passed by new incoming requests
2163                          */
2164                         rq->cmd_flags |= REQ_STARTED;
2165                         trace_block_rq_issue(q, rq);
2166                 }
2167
2168                 if (!q->boundary_rq || q->boundary_rq == rq) {
2169                         q->end_sector = rq_end_sector(rq);
2170                         q->boundary_rq = NULL;
2171                 }
2172
2173                 if (rq->cmd_flags & REQ_DONTPREP)
2174                         break;
2175
2176                 if (q->dma_drain_size && blk_rq_bytes(rq)) {
2177                         /*
2178                          * make sure space for the drain appears we
2179                          * know we can do this because max_hw_segments
2180                          * has been adjusted to be one fewer than the
2181                          * device can handle
2182                          */
2183                         rq->nr_phys_segments++;
2184                 }
2185
2186                 if (!q->prep_rq_fn)
2187                         break;
2188
2189                 ret = q->prep_rq_fn(q, rq);
2190                 if (ret == BLKPREP_OK) {
2191                         break;
2192                 } else if (ret == BLKPREP_DEFER) {
2193                         /*
2194                          * the request may have been (partially) prepped.
2195                          * we need to keep this request in the front to
2196                          * avoid resource deadlock.  REQ_STARTED will
2197                          * prevent other fs requests from passing this one.
2198                          */
2199                         if (q->dma_drain_size && blk_rq_bytes(rq) &&
2200                             !(rq->cmd_flags & REQ_DONTPREP)) {
2201                                 /*
2202                                  * remove the space for the drain we added
2203                                  * so that we don't add it again
2204                                  */
2205                                 --rq->nr_phys_segments;
2206                         }
2207
2208                         rq = NULL;
2209                         break;
2210                 } else if (ret == BLKPREP_KILL) {
2211                         rq->cmd_flags |= REQ_QUIET;
2212                         /*
2213                          * Mark this request as started so we don't trigger
2214                          * any debug logic in the end I/O path.
2215                          */
2216                         blk_start_request(rq);
2217                         __blk_end_request_all(rq, -EIO);
2218                 } else {
2219                         printk(KERN_ERR "%s: bad return=%d\n", __func__, ret);
2220                         break;
2221                 }
2222         }
2223
2224         return rq;
2225 }
2226 EXPORT_SYMBOL(blk_peek_request);
2227
2228 void blk_dequeue_request(struct request *rq)
2229 {
2230         struct request_queue *q = rq->q;
2231
2232         BUG_ON(list_empty(&rq->queuelist));
2233         BUG_ON(ELV_ON_HASH(rq));
2234
2235         list_del_init(&rq->queuelist);
2236
2237         /*
2238          * the time frame between a request being removed from the lists
2239          * and to it is freed is accounted as io that is in progress at
2240          * the driver side.
2241          */
2242         if (blk_account_rq(rq)) {
2243                 q->in_flight[rq_is_sync(rq)]++;
2244                 set_io_start_time_ns(rq);
2245         }
2246 }
2247
2248 /**
2249  * blk_start_request - start request processing on the driver
2250  * @req: request to dequeue
2251  *
2252  * Description:
2253  *     Dequeue @req and start timeout timer on it.  This hands off the
2254  *     request to the driver.
2255  *
2256  *     Block internal functions which don't want to start timer should
2257  *     call blk_dequeue_request().
2258  *
2259  * Context:
2260  *     queue_lock must be held.
2261  */
2262 void blk_start_request(struct request *req)
2263 {
2264         blk_dequeue_request(req);
2265
2266         /*
2267          * We are now handing the request to the hardware, initialize
2268          * resid_len to full count and add the timeout handler.
2269          */
2270         req->resid_len = blk_rq_bytes(req);
2271         if (unlikely(blk_bidi_rq(req)))
2272                 req->next_rq->resid_len = blk_rq_bytes(req->next_rq);
2273
2274         BUG_ON(test_bit(REQ_ATOM_COMPLETE, &req->atomic_flags));
2275         blk_add_timer(req);
2276 }
2277 EXPORT_SYMBOL(blk_start_request);
2278
2279 /**
2280  * blk_fetch_request - fetch a request from a request queue
2281  * @q: request queue to fetch a request from
2282  *
2283  * Description:
2284  *     Return the request at the top of @q.  The request is started on
2285  *     return and LLD can start processing it immediately.
2286  *
2287  * Return:
2288  *     Pointer to the request at the top of @q if available.  Null
2289  *     otherwise.
2290  *
2291  * Context:
2292  *     queue_lock must be held.
2293  */
2294 struct request *blk_fetch_request(struct request_queue *q)
2295 {
2296         struct request *rq;
2297
2298         rq = blk_peek_request(q);
2299         if (rq)
2300                 blk_start_request(rq);
2301         return rq;
2302 }
2303 EXPORT_SYMBOL(blk_fetch_request);
2304
2305 /**
2306  * blk_update_request - Special helper function for request stacking drivers
2307  * @req:      the request being processed
2308  * @error:    %0 for success, < %0 for error
2309  * @nr_bytes: number of bytes to complete @req
2310  *
2311  * Description:
2312  *     Ends I/O on a number of bytes attached to @req, but doesn't complete
2313  *     the request structure even if @req doesn't have leftover.
2314  *     If @req has leftover, sets it up for the next range of segments.
2315  *
2316  *     This special helper function is only for request stacking drivers
2317  *     (e.g. request-based dm) so that they can handle partial completion.
2318  *     Actual device drivers should use blk_end_request instead.
2319  *
2320  *     Passing the result of blk_rq_bytes() as @nr_bytes guarantees
2321  *     %false return from this function.
2322  *
2323  * Return:
2324  *     %false - this request doesn't have any more data
2325  *     %true  - this request has more data
2326  **/
2327 bool blk_update_request(struct request *req, int error, unsigned int nr_bytes)
2328 {
2329         int total_bytes;
2330
2331         if (!req->bio)
2332                 return false;
2333
2334         trace_block_rq_complete(req->q, req);
2335
2336         /*
2337          * For fs requests, rq is just carrier of independent bio's
2338          * and each partial completion should be handled separately.
2339          * Reset per-request error on each partial completion.
2340          *
2341          * TODO: tj: This is too subtle.  It would be better to let
2342          * low level drivers do what they see fit.
2343          */
2344         if (req->cmd_type == REQ_TYPE_FS)
2345                 req->errors = 0;
2346
2347         if (error && req->cmd_type == REQ_TYPE_FS &&
2348             !(req->cmd_flags & REQ_QUIET)) {
2349                 char *error_type;
2350
2351                 switch (error) {
2352                 case -ENOLINK:
2353                         error_type = "recoverable transport";
2354                         break;
2355                 case -EREMOTEIO:
2356                         error_type = "critical target";
2357                         break;
2358                 case -EBADE:
2359                         error_type = "critical nexus";
2360                         break;
2361                 case -ETIMEDOUT:
2362                         error_type = "timeout";
2363                         break;
2364                 case -ENOSPC:
2365                         error_type = "critical space allocation";
2366                         break;
2367                 case -ENODATA:
2368                         error_type = "critical medium";
2369                         break;
2370                 case -EIO:
2371                 default:
2372                         error_type = "I/O";
2373                         break;
2374                 }
2375                 printk_ratelimited(KERN_ERR "end_request: %s error, dev %s, sector %llu\n",
2376                                    error_type, req->rq_disk ?
2377                                    req->rq_disk->disk_name : "?",
2378                                    (unsigned long long)blk_rq_pos(req));
2379
2380         }
2381
2382         blk_account_io_completion(req, nr_bytes);
2383
2384         total_bytes = 0;
2385         while (req->bio) {
2386                 struct bio *bio = req->bio;
2387                 unsigned bio_bytes = min(bio->bi_iter.bi_size, nr_bytes);
2388
2389                 if (bio_bytes == bio->bi_iter.bi_size)
2390                         req->bio = bio->bi_next;
2391
2392                 req_bio_endio(req, bio, bio_bytes, error);
2393
2394                 total_bytes += bio_bytes;
2395                 nr_bytes -= bio_bytes;
2396
2397                 if (!nr_bytes)
2398                         break;
2399         }
2400
2401         /*
2402          * completely done
2403          */
2404         if (!req->bio) {
2405                 /*
2406                  * Reset counters so that the request stacking driver
2407                  * can find how many bytes remain in the request
2408                  * later.
2409                  */
2410                 req->__data_len = 0;
2411                 return false;
2412         }
2413
2414         req->__data_len -= total_bytes;
2415         req->buffer = bio_data(req->bio);
2416
2417         /* update sector only for requests with clear definition of sector */
2418         if (req->cmd_type == REQ_TYPE_FS)
2419                 req->__sector += total_bytes >> 9;
2420
2421         /* mixed attributes always follow the first bio */
2422         if (req->cmd_flags & REQ_MIXED_MERGE) {
2423                 req->cmd_flags &= ~REQ_FAILFAST_MASK;
2424                 req->cmd_flags |= req->bio->bi_rw & REQ_FAILFAST_MASK;
2425         }
2426
2427         /*
2428          * If total number of sectors is less than the first segment
2429          * size, something has gone terribly wrong.
2430          */
2431         if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {
2432                 blk_dump_rq_flags(req, "request botched");
2433                 req->__data_len = blk_rq_cur_bytes(req);
2434         }
2435
2436         /* recalculate the number of segments */
2437         blk_recalc_rq_segments(req);
2438
2439         return true;
2440 }
2441 EXPORT_SYMBOL_GPL(blk_update_request);
2442
2443 static bool blk_update_bidi_request(struct request *rq, int error,
2444                                     unsigned int nr_bytes,
2445                                     unsigned int bidi_bytes)
2446 {
2447         if (blk_update_request(rq, error, nr_bytes))
2448                 return true;
2449
2450         /* Bidi request must be completed as a whole */
2451         if (unlikely(blk_bidi_rq(rq)) &&
2452             blk_update_request(rq->next_rq, error, bidi_bytes))
2453                 return true;
2454
2455         if (blk_queue_add_random(rq->q))
2456                 add_disk_randomness(rq->rq_disk);
2457
2458         return false;
2459 }
2460
2461 /**
2462  * blk_unprep_request - unprepare a request
2463  * @req:        the request
2464  *
2465  * This function makes a request ready for complete resubmission (or
2466  * completion).  It happens only after all error handling is complete,
2467  * so represents the appropriate moment to deallocate any resources
2468  * that were allocated to the request in the prep_rq_fn.  The queue
2469  * lock is held when calling this.
2470  */
2471 void blk_unprep_request(struct request *req)
2472 {
2473         struct request_queue *q = req->q;
2474
2475         req->cmd_flags &= ~REQ_DONTPREP;
2476         if (q->unprep_rq_fn)
2477                 q->unprep_rq_fn(q, req);
2478 }
2479 EXPORT_SYMBOL_GPL(blk_unprep_request);
2480
2481 /*
2482  * queue lock must be held
2483  */
2484 static void blk_finish_request(struct request *req, int error)
2485 {
2486         if (blk_rq_tagged(req))
2487                 blk_queue_end_tag(req->q, req);
2488
2489         BUG_ON(blk_queued_rq(req));
2490
2491         if (unlikely(laptop_mode) && req->cmd_type == REQ_TYPE_FS)
2492                 laptop_io_completion(&req->q->backing_dev_info);
2493
2494         blk_delete_timer(req);
2495
2496         if (req->cmd_flags & REQ_DONTPREP)
2497                 blk_unprep_request(req);
2498
2499         blk_account_io_done(req);
2500
2501         if (req->end_io)
2502                 req->end_io(req, error);
2503         else {
2504                 if (blk_bidi_rq(req))
2505                         __blk_put_request(req->next_rq->q, req->next_rq);
2506
2507                 __blk_put_request(req->q, req);
2508         }
2509 }
2510
2511 /**
2512  * blk_end_bidi_request - Complete a bidi request
2513  * @rq:         the request to complete
2514  * @error:      %0 for success, < %0 for error
2515  * @nr_bytes:   number of bytes to complete @rq
2516  * @bidi_bytes: number of bytes to complete @rq->next_rq
2517  *
2518  * Description:
2519  *     Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
2520  *     Drivers that supports bidi can safely call this member for any
2521  *     type of request, bidi or uni.  In the later case @bidi_bytes is
2522  *     just ignored.
2523  *
2524  * Return:
2525  *     %false - we are done with this request
2526  *     %true  - still buffers pending for this request
2527  **/
2528 static bool blk_end_bidi_request(struct request *rq, int error,
2529                                  unsigned int nr_bytes, unsigned int bidi_bytes)
2530 {
2531         struct request_queue *q = rq->q;
2532         unsigned long flags;
2533
2534         if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2535                 return true;
2536
2537         spin_lock_irqsave(q->queue_lock, flags);
2538         blk_finish_request(rq, error);
2539         spin_unlock_irqrestore(q->queue_lock, flags);
2540
2541         return false;
2542 }
2543
2544 /**
2545  * __blk_end_bidi_request - Complete a bidi request with queue lock held
2546  * @rq:         the request to complete
2547  * @error:      %0 for success, < %0 for error
2548  * @nr_bytes:   number of bytes to complete @rq
2549  * @bidi_bytes: number of bytes to complete @rq->next_rq
2550  *
2551  * Description:
2552  *     Identical to blk_end_bidi_request() except that queue lock is
2553  *     assumed to be locked on entry and remains so on return.
2554  *
2555  * Return:
2556  *     %false - we are done with this request
2557  *     %true  - still buffers pending for this request
2558  **/
2559 bool __blk_end_bidi_request(struct request *rq, int error,
2560                                    unsigned int nr_bytes, unsigned int bidi_bytes)
2561 {
2562         if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2563                 return true;
2564
2565         blk_finish_request(rq, error);
2566
2567         return false;
2568 }
2569
2570 /**
2571  * blk_end_request - Helper function for drivers to complete the request.
2572  * @rq:       the request being processed
2573  * @error:    %0 for success, < %0 for error
2574  * @nr_bytes: number of bytes to complete
2575  *
2576  * Description:
2577  *     Ends I/O on a number of bytes attached to @rq.
2578  *     If @rq has leftover, sets it up for the next range of segments.
2579  *
2580  * Return:
2581  *     %false - we are done with this request
2582  *     %true  - still buffers pending for this request
2583  **/
2584 bool blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
2585 {
2586         return blk_end_bidi_request(rq, error, nr_bytes, 0);
2587 }
2588 EXPORT_SYMBOL(blk_end_request);
2589
2590 /**
2591  * blk_end_request_all - Helper function for drives to finish the request.
2592  * @rq: the request to finish
2593  * @error: %0 for success, < %0 for error
2594  *
2595  * Description:
2596  *     Completely finish @rq.
2597  */
2598 void blk_end_request_all(struct request *rq, int error)
2599 {
2600         bool pending;
2601         unsigned int bidi_bytes = 0;
2602
2603         if (unlikely(blk_bidi_rq(rq)))
2604                 bidi_bytes = blk_rq_bytes(rq->next_rq);
2605
2606         pending = blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2607         BUG_ON(pending);
2608 }
2609 EXPORT_SYMBOL(blk_end_request_all);
2610
2611 /**
2612  * blk_end_request_cur - Helper function to finish the current request chunk.
2613  * @rq: the request to finish the current chunk for
2614  * @error: %0 for success, < %0 for error
2615  *
2616  * Description:
2617  *     Complete the current consecutively mapped chunk from @rq.
2618  *
2619  * Return:
2620  *     %false - we are done with this request
2621  *     %true  - still buffers pending for this request
2622  */
2623 bool blk_end_request_cur(struct request *rq, int error)
2624 {
2625         return blk_end_request(rq, error, blk_rq_cur_bytes(rq));
2626 }
2627 EXPORT_SYMBOL(blk_end_request_cur);
2628
2629 /**
2630  * blk_end_request_err - Finish a request till the next failure boundary.
2631  * @rq: the request to finish till the next failure boundary for
2632  * @error: must be negative errno
2633  *
2634  * Description:
2635  *     Complete @rq till the next failure boundary.
2636  *
2637  * Return:
2638  *     %false - we are done with this request
2639  *     %true  - still buffers pending for this request
2640  */
2641 bool blk_end_request_err(struct request *rq, int error)
2642 {
2643         WARN_ON(error >= 0);
2644         return blk_end_request(rq, error, blk_rq_err_bytes(rq));
2645 }
2646 EXPORT_SYMBOL_GPL(blk_end_request_err);
2647
2648 /**
2649  * __blk_end_request - Helper function for drivers to complete the request.
2650  * @rq:       the request being processed
2651  * @error:    %0 for success, < %0 for error
2652  * @nr_bytes: number of bytes to complete
2653  *
2654  * Description:
2655  *     Must be called with queue lock held unlike blk_end_request().
2656  *
2657  * Return:
2658  *     %false - we are done with this request
2659  *     %true  - still buffers pending for this request
2660  **/
2661 bool __blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
2662 {
2663         return __blk_end_bidi_request(rq, error, nr_bytes, 0);
2664 }
2665 EXPORT_SYMBOL(__blk_end_request);
2666
2667 /**
2668  * __blk_end_request_all - Helper function for drives to finish the request.
2669  * @rq: the request to finish
2670  * @error: %0 for success, < %0 for error
2671  *
2672  * Description:
2673  *     Completely finish @rq.  Must be called with queue lock held.
2674  */
2675 void __blk_end_request_all(struct request *rq, int error)
2676 {
2677         bool pending;
2678         unsigned int bidi_bytes = 0;
2679
2680         if (unlikely(blk_bidi_rq(rq)))
2681                 bidi_bytes = blk_rq_bytes(rq->next_rq);
2682
2683         pending = __blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2684         BUG_ON(pending);
2685 }
2686 EXPORT_SYMBOL(__blk_end_request_all);
2687
2688 /**
2689  * __blk_end_request_cur - Helper function to finish the current request chunk.
2690  * @rq: the request to finish the current chunk for
2691  * @error: %0 for success, < %0 for error
2692  *
2693  * Description:
2694  *     Complete the current consecutively mapped chunk from @rq.  Must
2695  *     be called with queue lock held.
2696  *
2697  * Return:
2698  *     %false - we are done with this request
2699  *     %true  - still buffers pending for this request
2700  */
2701 bool __blk_end_request_cur(struct request *rq, int error)
2702 {
2703         return __blk_end_request(rq, error, blk_rq_cur_bytes(rq));
2704 }
2705 EXPORT_SYMBOL(__blk_end_request_cur);
2706
2707 /**
2708  * __blk_end_request_err - Finish a request till the next failure boundary.
2709  * @rq: the request to finish till the next failure boundary for
2710  * @error: must be negative errno
2711  *
2712  * Description:
2713  *     Complete @rq till the next failure boundary.  Must be called
2714  *     with queue lock held.
2715  *
2716  * Return:
2717  *     %false - we are done with this request
2718  *     %true  - still buffers pending for this request
2719  */
2720 bool __blk_end_request_err(struct request *rq, int error)
2721 {
2722         WARN_ON(error >= 0);
2723         return __blk_end_request(rq, error, blk_rq_err_bytes(rq));
2724 }
2725 EXPORT_SYMBOL_GPL(__blk_end_request_err);
2726
2727 void blk_rq_bio_prep(struct request_queue *q, struct request *rq,
2728                      struct bio *bio)
2729 {
2730         /* Bit 0 (R/W) is identical in rq->cmd_flags and bio->bi_rw */
2731         rq->cmd_flags |= bio->bi_rw & REQ_WRITE;
2732
2733         if (bio_has_data(bio)) {
2734                 rq->nr_phys_segments = bio_phys_segments(q, bio);
2735                 rq->buffer = bio_data(bio);
2736         }
2737         rq->__data_len = bio->bi_iter.bi_size;
2738         rq->bio = rq->biotail = bio;
2739
2740         if (bio->bi_bdev)
2741                 rq->rq_disk = bio->bi_bdev->bd_disk;
2742 }
2743
2744 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE
2745 /**
2746  * rq_flush_dcache_pages - Helper function to flush all pages in a request
2747  * @rq: the request to be flushed
2748  *
2749  * Description:
2750  *     Flush all pages in @rq.
2751  */
2752 void rq_flush_dcache_pages(struct request *rq)
2753 {
2754         struct req_iterator iter;
2755         struct bio_vec bvec;
2756
2757         rq_for_each_segment(bvec, rq, iter)
2758                 flush_dcache_page(bvec.bv_page);
2759 }
2760 EXPORT_SYMBOL_GPL(rq_flush_dcache_pages);
2761 #endif
2762
2763 /**
2764  * blk_lld_busy - Check if underlying low-level drivers of a device are busy
2765  * @q : the queue of the device being checked
2766  *
2767  * Description:
2768  *    Check if underlying low-level drivers of a device are busy.
2769  *    If the drivers want to export their busy state, they must set own
2770  *    exporting function using blk_queue_lld_busy() first.
2771  *
2772  *    Basically, this function is used only by request stacking drivers
2773  *    to stop dispatching requests to underlying devices when underlying
2774  *    devices are busy.  This behavior helps more I/O merging on the queue
2775  *    of the request stacking driver and prevents I/O throughput regression
2776  *    on burst I/O load.
2777  *
2778  * Return:
2779  *    0 - Not busy (The request stacking driver should dispatch request)
2780  *    1 - Busy (The request stacking driver should stop dispatching request)
2781  */
2782 int blk_lld_busy(struct request_queue *q)
2783 {
2784         if (q->lld_busy_fn)
2785                 return q->lld_busy_fn(q);
2786
2787         return 0;
2788 }
2789 EXPORT_SYMBOL_GPL(blk_lld_busy);
2790
2791 /**
2792  * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
2793  * @rq: the clone request to be cleaned up
2794  *
2795  * Description:
2796  *     Free all bios in @rq for a cloned request.
2797  */
2798 void blk_rq_unprep_clone(struct request *rq)
2799 {
2800         struct bio *bio;
2801
2802         while ((bio = rq->bio) != NULL) {
2803                 rq->bio = bio->bi_next;
2804
2805                 bio_put(bio);
2806         }
2807 }
2808 EXPORT_SYMBOL_GPL(blk_rq_unprep_clone);
2809
2810 /*
2811  * Copy attributes of the original request to the clone request.
2812  * The actual data parts (e.g. ->cmd, ->buffer, ->sense) are not copied.
2813  */
2814 static void __blk_rq_prep_clone(struct request *dst, struct request *src)
2815 {
2816         dst->cpu = src->cpu;
2817         dst->cmd_flags = (src->cmd_flags & REQ_CLONE_MASK) | REQ_NOMERGE;
2818         dst->cmd_type = src->cmd_type;
2819         dst->__sector = blk_rq_pos(src);
2820         dst->__data_len = blk_rq_bytes(src);
2821         dst->nr_phys_segments = src->nr_phys_segments;
2822         dst->ioprio = src->ioprio;
2823         dst->extra_len = src->extra_len;
2824 }
2825
2826 /**
2827  * blk_rq_prep_clone - Helper function to setup clone request
2828  * @rq: the request to be setup
2829  * @rq_src: original request to be cloned
2830  * @bs: bio_set that bios for clone are allocated from
2831  * @gfp_mask: memory allocation mask for bio
2832  * @bio_ctr: setup function to be called for each clone bio.
2833  *           Returns %0 for success, non %0 for failure.
2834  * @data: private data to be passed to @bio_ctr
2835  *
2836  * Description:
2837  *     Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
2838  *     The actual data parts of @rq_src (e.g. ->cmd, ->buffer, ->sense)
2839  *     are not copied, and copying such parts is the caller's responsibility.
2840  *     Also, pages which the original bios are pointing to are not copied
2841  *     and the cloned bios just point same pages.
2842  *     So cloned bios must be completed before original bios, which means
2843  *     the caller must complete @rq before @rq_src.
2844  */
2845 int blk_rq_prep_clone(struct request *rq, struct request *rq_src,
2846                       struct bio_set *bs, gfp_t gfp_mask,
2847                       int (*bio_ctr)(struct bio *, struct bio *, void *),
2848                       void *data)
2849 {
2850         struct bio *bio, *bio_src;
2851
2852         if (!bs)
2853                 bs = fs_bio_set;
2854
2855         blk_rq_init(NULL, rq);
2856
2857         __rq_for_each_bio(bio_src, rq_src) {
2858                 bio = bio_clone_bioset(bio_src, gfp_mask, bs);
2859                 if (!bio)
2860                         goto free_and_out;
2861
2862                 if (bio_ctr && bio_ctr(bio, bio_src, data))
2863                         goto free_and_out;
2864
2865                 if (rq->bio) {
2866                         rq->biotail->bi_next = bio;
2867                         rq->biotail = bio;
2868                 } else
2869                         rq->bio = rq->biotail = bio;
2870         }
2871
2872         __blk_rq_prep_clone(rq, rq_src);
2873
2874         return 0;
2875
2876 free_and_out:
2877         if (bio)
2878                 bio_put(bio);
2879         blk_rq_unprep_clone(rq);
2880
2881         return -ENOMEM;
2882 }
2883 EXPORT_SYMBOL_GPL(blk_rq_prep_clone);
2884
2885 int kblockd_schedule_work(struct request_queue *q, struct work_struct *work)
2886 {
2887         return queue_work(kblockd_workqueue, work);
2888 }
2889 EXPORT_SYMBOL(kblockd_schedule_work);
2890
2891 int kblockd_schedule_delayed_work(struct request_queue *q,
2892                         struct delayed_work *dwork, unsigned long delay)
2893 {
2894         return queue_delayed_work(kblockd_workqueue, dwork, delay);
2895 }
2896 EXPORT_SYMBOL(kblockd_schedule_delayed_work);
2897
2898 #define PLUG_MAGIC      0x91827364
2899
2900 /**
2901  * blk_start_plug - initialize blk_plug and track it inside the task_struct
2902  * @plug:       The &struct blk_plug that needs to be initialized
2903  *
2904  * Description:
2905  *   Tracking blk_plug inside the task_struct will help with auto-flushing the
2906  *   pending I/O should the task end up blocking between blk_start_plug() and
2907  *   blk_finish_plug(). This is important from a performance perspective, but
2908  *   also ensures that we don't deadlock. For instance, if the task is blocking
2909  *   for a memory allocation, memory reclaim could end up wanting to free a
2910  *   page belonging to that request that is currently residing in our private
2911  *   plug. By flushing the pending I/O when the process goes to sleep, we avoid
2912  *   this kind of deadlock.
2913  */
2914 void blk_start_plug(struct blk_plug *plug)
2915 {
2916         struct task_struct *tsk = current;
2917
2918         plug->magic = PLUG_MAGIC;
2919         INIT_LIST_HEAD(&plug->list);
2920         INIT_LIST_HEAD(&plug->mq_list);
2921         INIT_LIST_HEAD(&plug->cb_list);
2922
2923         /*
2924          * If this is a nested plug, don't actually assign it. It will be
2925          * flushed on its own.
2926          */
2927         if (!tsk->plug) {
2928                 /*
2929                  * Store ordering should not be needed here, since a potential
2930                  * preempt will imply a full memory barrier
2931                  */
2932                 tsk->plug = plug;
2933         }
2934 }
2935 EXPORT_SYMBOL(blk_start_plug);
2936
2937 static int plug_rq_cmp(void *priv, struct list_head *a, struct list_head *b)
2938 {
2939         struct request *rqa = container_of(a, struct request, queuelist);
2940         struct request *rqb = container_of(b, struct request, queuelist);
2941
2942         return !(rqa->q < rqb->q ||
2943                 (rqa->q == rqb->q && blk_rq_pos(rqa) < blk_rq_pos(rqb)));
2944 }
2945
2946 /*
2947  * If 'from_schedule' is true, then postpone the dispatch of requests
2948  * until a safe kblockd context. We due this to avoid accidental big
2949  * additional stack usage in driver dispatch, in places where the originally
2950  * plugger did not intend it.
2951  */
2952 static void queue_unplugged(struct request_queue *q, unsigned int depth,
2953                             bool from_schedule)
2954         __releases(q->queue_lock)
2955 {
2956         trace_block_unplug(q, depth, !from_schedule);
2957
2958         if (from_schedule)
2959                 blk_run_queue_async(q);
2960         else
2961                 __blk_run_queue(q);
2962         spin_unlock(q->queue_lock);
2963 }
2964
2965 static void flush_plug_callbacks(struct blk_plug *plug, bool from_schedule)
2966 {
2967         LIST_HEAD(callbacks);
2968
2969         while (!list_empty(&plug->cb_list)) {
2970                 list_splice_init(&plug->cb_list, &callbacks);
2971
2972                 while (!list_empty(&callbacks)) {
2973                         struct blk_plug_cb *cb = list_first_entry(&callbacks,
2974                                                           struct blk_plug_cb,
2975                                                           list);
2976                         list_del(&cb->list);
2977                         cb->callback(cb, from_schedule);
2978                 }
2979         }
2980 }
2981
2982 struct blk_plug_cb *blk_check_plugged(blk_plug_cb_fn unplug, void *data,
2983                                       int size)
2984 {
2985         struct blk_plug *plug = current->plug;
2986         struct blk_plug_cb *cb;
2987
2988         if (!plug)
2989                 return NULL;
2990
2991         list_for_each_entry(cb, &plug->cb_list, list)
2992                 if (cb->callback == unplug && cb->data == data)
2993                         return cb;
2994
2995         /* Not currently on the callback list */
2996         BUG_ON(size < sizeof(*cb));
2997         cb = kzalloc(size, GFP_ATOMIC);
2998         if (cb) {
2999                 cb->data = data;
3000                 cb->callback = unplug;
3001                 list_add(&cb->list, &plug->cb_list);
3002         }
3003         return cb;
3004 }
3005 EXPORT_SYMBOL(blk_check_plugged);
3006
3007 void blk_flush_plug_list(struct blk_plug *plug, bool from_schedule)
3008 {
3009         struct request_queue *q;
3010         unsigned long flags;
3011         struct request *rq;
3012         LIST_HEAD(list);
3013         unsigned int depth;
3014
3015         BUG_ON(plug->magic != PLUG_MAGIC);
3016
3017         flush_plug_callbacks(plug, from_schedule);
3018
3019         if (!list_empty(&plug->mq_list))
3020                 blk_mq_flush_plug_list(plug, from_schedule);
3021
3022         if (list_empty(&plug->list))
3023                 return;
3024
3025         list_splice_init(&plug->list, &list);
3026
3027         list_sort(NULL, &list, plug_rq_cmp);
3028
3029         q = NULL;
3030         depth = 0;
3031
3032         /*
3033          * Save and disable interrupts here, to avoid doing it for every
3034          * queue lock we have to take.
3035          */
3036         local_irq_save(flags);
3037         while (!list_empty(&list)) {
3038                 rq = list_entry_rq(list.next);
3039                 list_del_init(&rq->queuelist);
3040                 BUG_ON(!rq->q);
3041                 if (rq->q != q) {
3042                         /*
3043                          * This drops the queue lock
3044                          */
3045                         if (q)
3046                                 queue_unplugged(q, depth, from_schedule);
3047                         q = rq->q;
3048                         depth = 0;
3049                         spin_lock(q->queue_lock);
3050                 }
3051
3052                 /*
3053                  * Short-circuit if @q is dead
3054                  */
3055                 if (unlikely(blk_queue_dying(q))) {
3056                         __blk_end_request_all(rq, -ENODEV);
3057                         continue;
3058                 }
3059
3060                 /*
3061                  * rq is already accounted, so use raw insert
3062                  */
3063                 if (rq->cmd_flags & (REQ_FLUSH | REQ_FUA))
3064                         __elv_add_request(q, rq, ELEVATOR_INSERT_FLUSH);
3065                 else
3066                         __elv_add_request(q, rq, ELEVATOR_INSERT_SORT_MERGE);
3067
3068                 depth++;
3069         }
3070
3071         /*
3072          * This drops the queue lock
3073          */
3074         if (q)
3075                 queue_unplugged(q, depth, from_schedule);
3076
3077         local_irq_restore(flags);
3078 }
3079
3080 void blk_finish_plug(struct blk_plug *plug)
3081 {
3082         blk_flush_plug_list(plug, false);
3083
3084         if (plug == current->plug)
3085                 current->plug = NULL;
3086 }
3087 EXPORT_SYMBOL(blk_finish_plug);
3088
3089 #ifdef CONFIG_PM_RUNTIME
3090 /**
3091  * blk_pm_runtime_init - Block layer runtime PM initialization routine
3092  * @q: the queue of the device
3093  * @dev: the device the queue belongs to
3094  *
3095  * Description:
3096  *    Initialize runtime-PM-related fields for @q and start auto suspend for
3097  *    @dev. Drivers that want to take advantage of request-based runtime PM
3098  *    should call this function after @dev has been initialized, and its
3099  *    request queue @q has been allocated, and runtime PM for it can not happen
3100  *    yet(either due to disabled/forbidden or its usage_count > 0). In most
3101  *    cases, driver should call this function before any I/O has taken place.
3102  *
3103  *    This function takes care of setting up using auto suspend for the device,
3104  *    the autosuspend delay is set to -1 to make runtime suspend impossible
3105  *    until an updated value is either set by user or by driver. Drivers do
3106  *    not need to touch other autosuspend settings.
3107  *
3108  *    The block layer runtime PM is request based, so only works for drivers
3109  *    that use request as their IO unit instead of those directly use bio's.
3110  */
3111 void blk_pm_runtime_init(struct request_queue *q, struct device *dev)
3112 {
3113         q->dev = dev;
3114         q->rpm_status = RPM_ACTIVE;
3115         pm_runtime_set_autosuspend_delay(q->dev, -1);
3116         pm_runtime_use_autosuspend(q->dev);
3117 }
3118 EXPORT_SYMBOL(blk_pm_runtime_init);
3119
3120 /**
3121  * blk_pre_runtime_suspend - Pre runtime suspend check
3122  * @q: the queue of the device
3123  *
3124  * Description:
3125  *    This function will check if runtime suspend is allowed for the device
3126  *    by examining if there are any requests pending in the queue. If there
3127  *    are requests pending, the device can not be runtime suspended; otherwise,
3128  *    the queue's status will be updated to SUSPENDING and the driver can
3129  *    proceed to suspend the device.
3130  *
3131  *    For the not allowed case, we mark last busy for the device so that
3132  *    runtime PM core will try to autosuspend it some time later.
3133  *
3134  *    This function should be called near the start of the device's
3135  *    runtime_suspend callback.
3136  *
3137  * Return:
3138  *    0         - OK to runtime suspend the device
3139  *    -EBUSY    - Device should not be runtime suspended
3140  */
3141 int blk_pre_runtime_suspend(struct request_queue *q)
3142 {
3143         int ret = 0;
3144
3145         spin_lock_irq(q->queue_lock);
3146         if (q->nr_pending) {
3147                 ret = -EBUSY;
3148                 pm_runtime_mark_last_busy(q->dev);
3149         } else {
3150                 q->rpm_status = RPM_SUSPENDING;
3151         }
3152         spin_unlock_irq(q->queue_lock);
3153         return ret;
3154 }
3155 EXPORT_SYMBOL(blk_pre_runtime_suspend);
3156
3157 /**
3158  * blk_post_runtime_suspend - Post runtime suspend processing
3159  * @q: the queue of the device
3160  * @err: return value of the device's runtime_suspend function
3161  *
3162  * Description:
3163  *    Update the queue's runtime status according to the return value of the
3164  *    device's runtime suspend function and mark last busy for the device so
3165  *    that PM core will try to auto suspend the device at a later time.
3166  *
3167  *    This function should be called near the end of the device's
3168  *    runtime_suspend callback.
3169  */
3170 void blk_post_runtime_suspend(struct request_queue *q, int err)
3171 {
3172         spin_lock_irq(q->queue_lock);
3173         if (!err) {
3174                 q->rpm_status = RPM_SUSPENDED;
3175         } else {
3176                 q->rpm_status = RPM_ACTIVE;
3177                 pm_runtime_mark_last_busy(q->dev);
3178         }
3179         spin_unlock_irq(q->queue_lock);
3180 }
3181 EXPORT_SYMBOL(blk_post_runtime_suspend);
3182
3183 /**
3184  * blk_pre_runtime_resume - Pre runtime resume processing
3185  * @q: the queue of the device
3186  *
3187  * Description:
3188  *    Update the queue's runtime status to RESUMING in preparation for the
3189  *    runtime resume of the device.
3190  *
3191  *    This function should be called near the start of the device's
3192  *    runtime_resume callback.
3193  */
3194 void blk_pre_runtime_resume(struct request_queue *q)
3195 {
3196         spin_lock_irq(q->queue_lock);
3197         q->rpm_status = RPM_RESUMING;
3198         spin_unlock_irq(q->queue_lock);
3199 }
3200 EXPORT_SYMBOL(blk_pre_runtime_resume);
3201
3202 /**
3203  * blk_post_runtime_resume - Post runtime resume processing
3204  * @q: the queue of the device
3205  * @err: return value of the device's runtime_resume function
3206  *
3207  * Description:
3208  *    Update the queue's runtime status according to the return value of the
3209  *    device's runtime_resume function. If it is successfully resumed, process
3210  *    the requests that are queued into the device's queue when it is resuming
3211  *    and then mark last busy and initiate autosuspend for it.
3212  *
3213  *    This function should be called near the end of the device's
3214  *    runtime_resume callback.
3215  */
3216 void blk_post_runtime_resume(struct request_queue *q, int err)
3217 {
3218         spin_lock_irq(q->queue_lock);
3219         if (!err) {
3220                 q->rpm_status = RPM_ACTIVE;
3221                 __blk_run_queue(q);
3222                 pm_runtime_mark_last_busy(q->dev);
3223                 pm_request_autosuspend(q->dev);
3224         } else {
3225                 q->rpm_status = RPM_SUSPENDED;
3226         }
3227         spin_unlock_irq(q->queue_lock);
3228 }
3229 EXPORT_SYMBOL(blk_post_runtime_resume);
3230 #endif
3231
3232 int __init blk_dev_init(void)
3233 {
3234         BUILD_BUG_ON(__REQ_NR_BITS > 8 *
3235                         sizeof(((struct request *)0)->cmd_flags));
3236
3237         /* used for unplugging and affects IO latency/throughput - HIGHPRI */
3238         kblockd_workqueue = alloc_workqueue("kblockd",
3239                                             WQ_MEM_RECLAIM | WQ_HIGHPRI |
3240                                             WQ_POWER_EFFICIENT, 0);
3241         if (!kblockd_workqueue)
3242                 panic("Failed to create kblockd\n");
3243
3244         request_cachep = kmem_cache_create("blkdev_requests",
3245                         sizeof(struct request), 0, SLAB_PANIC, NULL);
3246
3247         blk_requestq_cachep = kmem_cache_create("blkdev_queue",
3248                         sizeof(struct request_queue), 0, SLAB_PANIC, NULL);
3249
3250         return 0;
3251 }