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