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