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