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