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