OSDN Git Service

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