block: Remove the control of complete cpu from bio.
[firefly-linux-kernel-4.4.55.git] / block / blk-core.c
1 /*
2  * Copyright (C) 1991, 1992 Linus Torvalds
3  * Copyright (C) 1994,      Karl Keyte: Added support for disk statistics
4  * Elevator latency, (C) 2000  Andrea Arcangeli <andrea@suse.de> SuSE
5  * Queue request tables / lock, selectable elevator, Jens Axboe <axboe@suse.de>
6  * kernel-doc documentation started by NeilBrown <neilb@cse.unsw.edu.au>
7  *      -  July2000
8  * bio rewrite, highmem i/o, etc, Jens Axboe <axboe@suse.de> - may 2001
9  */
10
11 /*
12  * This handles all read/write requests to block devices
13  */
14 #include <linux/kernel.h>
15 #include <linux/module.h>
16 #include <linux/backing-dev.h>
17 #include <linux/bio.h>
18 #include <linux/blkdev.h>
19 #include <linux/highmem.h>
20 #include <linux/mm.h>
21 #include <linux/kernel_stat.h>
22 #include <linux/string.h>
23 #include <linux/init.h>
24 #include <linux/completion.h>
25 #include <linux/slab.h>
26 #include <linux/swap.h>
27 #include <linux/writeback.h>
28 #include <linux/task_io_accounting_ops.h>
29 #include <linux/fault-inject.h>
30 #include <linux/list_sort.h>
31 #include <linux/delay.h>
32
33 #define CREATE_TRACE_POINTS
34 #include <trace/events/block.h>
35
36 #include "blk.h"
37
38 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_remap);
39 EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_remap);
40 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_complete);
41
42 /*
43  * For the allocated request tables
44  */
45 static struct kmem_cache *request_cachep;
46
47 /*
48  * For queue allocation
49  */
50 struct kmem_cache *blk_requestq_cachep;
51
52 /*
53  * Controlling structure to kblockd
54  */
55 static struct workqueue_struct *kblockd_workqueue;
56
57 static void drive_stat_acct(struct request *rq, int new_io)
58 {
59         struct hd_struct *part;
60         int rw = rq_data_dir(rq);
61         int cpu;
62
63         if (!blk_do_io_stat(rq))
64                 return;
65
66         cpu = part_stat_lock();
67
68         if (!new_io) {
69                 part = rq->part;
70                 part_stat_inc(cpu, part, merges[rw]);
71         } else {
72                 part = disk_map_sector_rcu(rq->rq_disk, blk_rq_pos(rq));
73                 if (!hd_struct_try_get(part)) {
74                         /*
75                          * The partition is already being removed,
76                          * the request will be accounted on the disk only
77                          *
78                          * We take a reference on disk->part0 although that
79                          * partition will never be deleted, so we can treat
80                          * it as any other partition.
81                          */
82                         part = &rq->rq_disk->part0;
83                         hd_struct_get(part);
84                 }
85                 part_round_stats(cpu, part);
86                 part_inc_in_flight(part, rw);
87                 rq->part = part;
88         }
89
90         part_stat_unlock();
91 }
92
93 void blk_queue_congestion_threshold(struct request_queue *q)
94 {
95         int nr;
96
97         nr = q->nr_requests - (q->nr_requests / 8) + 1;
98         if (nr > q->nr_requests)
99                 nr = q->nr_requests;
100         q->nr_congestion_on = nr;
101
102         nr = q->nr_requests - (q->nr_requests / 8) - (q->nr_requests / 16) - 1;
103         if (nr < 1)
104                 nr = 1;
105         q->nr_congestion_off = nr;
106 }
107
108 /**
109  * blk_get_backing_dev_info - get the address of a queue's backing_dev_info
110  * @bdev:       device
111  *
112  * Locates the passed device's request queue and returns the address of its
113  * backing_dev_info
114  *
115  * Will return NULL if the request queue cannot be located.
116  */
117 struct backing_dev_info *blk_get_backing_dev_info(struct block_device *bdev)
118 {
119         struct backing_dev_info *ret = NULL;
120         struct request_queue *q = bdev_get_queue(bdev);
121
122         if (q)
123                 ret = &q->backing_dev_info;
124         return ret;
125 }
126 EXPORT_SYMBOL(blk_get_backing_dev_info);
127
128 void blk_rq_init(struct request_queue *q, struct request *rq)
129 {
130         memset(rq, 0, sizeof(*rq));
131
132         INIT_LIST_HEAD(&rq->queuelist);
133         INIT_LIST_HEAD(&rq->timeout_list);
134         rq->cpu = -1;
135         rq->q = q;
136         rq->__sector = (sector_t) -1;
137         INIT_HLIST_NODE(&rq->hash);
138         RB_CLEAR_NODE(&rq->rb_node);
139         rq->cmd = rq->__cmd;
140         rq->cmd_len = BLK_MAX_CDB;
141         rq->tag = -1;
142         rq->ref_count = 1;
143         rq->start_time = jiffies;
144         set_start_time_ns(rq);
145         rq->part = NULL;
146 }
147 EXPORT_SYMBOL(blk_rq_init);
148
149 static void req_bio_endio(struct request *rq, struct bio *bio,
150                           unsigned int nbytes, int error)
151 {
152         if (error)
153                 clear_bit(BIO_UPTODATE, &bio->bi_flags);
154         else if (!test_bit(BIO_UPTODATE, &bio->bi_flags))
155                 error = -EIO;
156
157         if (unlikely(nbytes > bio->bi_size)) {
158                 printk(KERN_ERR "%s: want %u bytes done, %u left\n",
159                        __func__, nbytes, bio->bi_size);
160                 nbytes = bio->bi_size;
161         }
162
163         if (unlikely(rq->cmd_flags & REQ_QUIET))
164                 set_bit(BIO_QUIET, &bio->bi_flags);
165
166         bio->bi_size -= nbytes;
167         bio->bi_sector += (nbytes >> 9);
168
169         if (bio_integrity(bio))
170                 bio_integrity_advance(bio, nbytes);
171
172         /* don't actually finish bio if it's part of flush sequence */
173         if (bio->bi_size == 0 && !(rq->cmd_flags & REQ_FLUSH_SEQ))
174                 bio_endio(bio, error);
175 }
176
177 void blk_dump_rq_flags(struct request *rq, char *msg)
178 {
179         int bit;
180
181         printk(KERN_INFO "%s: dev %s: type=%x, flags=%x\n", msg,
182                 rq->rq_disk ? rq->rq_disk->disk_name : "?", rq->cmd_type,
183                 rq->cmd_flags);
184
185         printk(KERN_INFO "  sector %llu, nr/cnr %u/%u\n",
186                (unsigned long long)blk_rq_pos(rq),
187                blk_rq_sectors(rq), blk_rq_cur_sectors(rq));
188         printk(KERN_INFO "  bio %p, biotail %p, buffer %p, len %u\n",
189                rq->bio, rq->biotail, rq->buffer, blk_rq_bytes(rq));
190
191         if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
192                 printk(KERN_INFO "  cdb: ");
193                 for (bit = 0; bit < BLK_MAX_CDB; bit++)
194                         printk("%02x ", rq->cmd[bit]);
195                 printk("\n");
196         }
197 }
198 EXPORT_SYMBOL(blk_dump_rq_flags);
199
200 static void blk_delay_work(struct work_struct *work)
201 {
202         struct request_queue *q;
203
204         q = container_of(work, struct request_queue, delay_work.work);
205         spin_lock_irq(q->queue_lock);
206         __blk_run_queue(q);
207         spin_unlock_irq(q->queue_lock);
208 }
209
210 /**
211  * blk_delay_queue - restart queueing after defined interval
212  * @q:          The &struct request_queue in question
213  * @msecs:      Delay in msecs
214  *
215  * Description:
216  *   Sometimes queueing needs to be postponed for a little while, to allow
217  *   resources to come back. This function will make sure that queueing is
218  *   restarted around the specified time.
219  */
220 void blk_delay_queue(struct request_queue *q, unsigned long msecs)
221 {
222         queue_delayed_work(kblockd_workqueue, &q->delay_work,
223                                 msecs_to_jiffies(msecs));
224 }
225 EXPORT_SYMBOL(blk_delay_queue);
226
227 /**
228  * blk_start_queue - restart a previously stopped queue
229  * @q:    The &struct request_queue in question
230  *
231  * Description:
232  *   blk_start_queue() will clear the stop flag on the queue, and call
233  *   the request_fn for the queue if it was in a stopped state when
234  *   entered. Also see blk_stop_queue(). Queue lock must be held.
235  **/
236 void blk_start_queue(struct request_queue *q)
237 {
238         WARN_ON(!irqs_disabled());
239
240         queue_flag_clear(QUEUE_FLAG_STOPPED, q);
241         __blk_run_queue(q);
242 }
243 EXPORT_SYMBOL(blk_start_queue);
244
245 /**
246  * blk_stop_queue - stop a queue
247  * @q:    The &struct request_queue in question
248  *
249  * Description:
250  *   The Linux block layer assumes that a block driver will consume all
251  *   entries on the request queue when the request_fn strategy is called.
252  *   Often this will not happen, because of hardware limitations (queue
253  *   depth settings). If a device driver gets a 'queue full' response,
254  *   or if it simply chooses not to queue more I/O at one point, it can
255  *   call this function to prevent the request_fn from being called until
256  *   the driver has signalled it's ready to go again. This happens by calling
257  *   blk_start_queue() to restart queue operations. Queue lock must be held.
258  **/
259 void blk_stop_queue(struct request_queue *q)
260 {
261         __cancel_delayed_work(&q->delay_work);
262         queue_flag_set(QUEUE_FLAG_STOPPED, q);
263 }
264 EXPORT_SYMBOL(blk_stop_queue);
265
266 /**
267  * blk_sync_queue - cancel any pending callbacks on a queue
268  * @q: the queue
269  *
270  * Description:
271  *     The block layer may perform asynchronous callback activity
272  *     on a queue, such as calling the unplug function after a timeout.
273  *     A block device may call blk_sync_queue to ensure that any
274  *     such activity is cancelled, thus allowing it to release resources
275  *     that the callbacks might use. The caller must already have made sure
276  *     that its ->make_request_fn will not re-add plugging prior to calling
277  *     this function.
278  *
279  *     This function does not cancel any asynchronous activity arising
280  *     out of elevator or throttling code. That would require elevaotor_exit()
281  *     and blk_throtl_exit() to be called with queue lock initialized.
282  *
283  */
284 void blk_sync_queue(struct request_queue *q)
285 {
286         del_timer_sync(&q->timeout);
287         cancel_delayed_work_sync(&q->delay_work);
288 }
289 EXPORT_SYMBOL(blk_sync_queue);
290
291 /**
292  * __blk_run_queue - run a single device queue
293  * @q:  The queue to run
294  *
295  * Description:
296  *    See @blk_run_queue. This variant must be called with the queue lock
297  *    held and interrupts disabled.
298  */
299 void __blk_run_queue(struct request_queue *q)
300 {
301         if (unlikely(blk_queue_stopped(q)))
302                 return;
303
304         q->request_fn(q);
305 }
306 EXPORT_SYMBOL(__blk_run_queue);
307
308 /**
309  * blk_run_queue_async - run a single device queue in workqueue context
310  * @q:  The queue to run
311  *
312  * Description:
313  *    Tells kblockd to perform the equivalent of @blk_run_queue on behalf
314  *    of us.
315  */
316 void blk_run_queue_async(struct request_queue *q)
317 {
318         if (likely(!blk_queue_stopped(q))) {
319                 __cancel_delayed_work(&q->delay_work);
320                 queue_delayed_work(kblockd_workqueue, &q->delay_work, 0);
321         }
322 }
323 EXPORT_SYMBOL(blk_run_queue_async);
324
325 /**
326  * blk_run_queue - run a single device queue
327  * @q: The queue to run
328  *
329  * Description:
330  *    Invoke request handling on this queue, if it has pending work to do.
331  *    May be used to restart queueing when a request has completed.
332  */
333 void blk_run_queue(struct request_queue *q)
334 {
335         unsigned long flags;
336
337         spin_lock_irqsave(q->queue_lock, flags);
338         __blk_run_queue(q);
339         spin_unlock_irqrestore(q->queue_lock, flags);
340 }
341 EXPORT_SYMBOL(blk_run_queue);
342
343 void blk_put_queue(struct request_queue *q)
344 {
345         kobject_put(&q->kobj);
346 }
347 EXPORT_SYMBOL(blk_put_queue);
348
349 /**
350  * blk_drain_queue - drain requests from request_queue
351  * @q: queue to drain
352  * @drain_all: whether to drain all requests or only the ones w/ ELVPRIV
353  *
354  * Drain requests from @q.  If @drain_all is set, all requests are drained.
355  * If not, only ELVPRIV requests are drained.  The caller is responsible
356  * for ensuring that no new requests which need to be drained are queued.
357  */
358 void blk_drain_queue(struct request_queue *q, bool drain_all)
359 {
360         while (true) {
361                 int nr_rqs;
362
363                 spin_lock_irq(q->queue_lock);
364
365                 elv_drain_elevator(q);
366                 if (drain_all)
367                         blk_throtl_drain(q);
368
369                 __blk_run_queue(q);
370
371                 if (drain_all)
372                         nr_rqs = q->rq.count[0] + q->rq.count[1];
373                 else
374                         nr_rqs = q->rq.elvpriv;
375
376                 spin_unlock_irq(q->queue_lock);
377
378                 if (!nr_rqs)
379                         break;
380                 msleep(10);
381         }
382 }
383
384 /**
385  * blk_cleanup_queue - shutdown a request queue
386  * @q: request queue to shutdown
387  *
388  * Mark @q DEAD, drain all pending requests, destroy and put it.  All
389  * future requests will be failed immediately with -ENODEV.
390  */
391 void blk_cleanup_queue(struct request_queue *q)
392 {
393         spinlock_t *lock = q->queue_lock;
394
395         /* mark @q DEAD, no new request or merges will be allowed afterwards */
396         mutex_lock(&q->sysfs_lock);
397         queue_flag_set_unlocked(QUEUE_FLAG_DEAD, q);
398
399         spin_lock_irq(lock);
400         queue_flag_set(QUEUE_FLAG_NOMERGES, q);
401         queue_flag_set(QUEUE_FLAG_NOXMERGES, q);
402         queue_flag_set(QUEUE_FLAG_DEAD, q);
403
404         if (q->queue_lock != &q->__queue_lock)
405                 q->queue_lock = &q->__queue_lock;
406
407         spin_unlock_irq(lock);
408         mutex_unlock(&q->sysfs_lock);
409
410         /* drain all requests queued before DEAD marking */
411         blk_drain_queue(q, true);
412
413         /* @q won't process any more request, flush async actions */
414         del_timer_sync(&q->backing_dev_info.laptop_mode_wb_timer);
415         blk_sync_queue(q);
416
417         /* @q is and will stay empty, shutdown and put */
418         blk_put_queue(q);
419 }
420 EXPORT_SYMBOL(blk_cleanup_queue);
421
422 static int blk_init_free_list(struct request_queue *q)
423 {
424         struct request_list *rl = &q->rq;
425
426         if (unlikely(rl->rq_pool))
427                 return 0;
428
429         rl->count[BLK_RW_SYNC] = rl->count[BLK_RW_ASYNC] = 0;
430         rl->starved[BLK_RW_SYNC] = rl->starved[BLK_RW_ASYNC] = 0;
431         rl->elvpriv = 0;
432         init_waitqueue_head(&rl->wait[BLK_RW_SYNC]);
433         init_waitqueue_head(&rl->wait[BLK_RW_ASYNC]);
434
435         rl->rq_pool = mempool_create_node(BLKDEV_MIN_RQ, mempool_alloc_slab,
436                                 mempool_free_slab, request_cachep, q->node);
437
438         if (!rl->rq_pool)
439                 return -ENOMEM;
440
441         return 0;
442 }
443
444 struct request_queue *blk_alloc_queue(gfp_t gfp_mask)
445 {
446         return blk_alloc_queue_node(gfp_mask, -1);
447 }
448 EXPORT_SYMBOL(blk_alloc_queue);
449
450 struct request_queue *blk_alloc_queue_node(gfp_t gfp_mask, int node_id)
451 {
452         struct request_queue *q;
453         int err;
454
455         q = kmem_cache_alloc_node(blk_requestq_cachep,
456                                 gfp_mask | __GFP_ZERO, node_id);
457         if (!q)
458                 return NULL;
459
460         q->backing_dev_info.ra_pages =
461                         (VM_MAX_READAHEAD * 1024) / PAGE_CACHE_SIZE;
462         q->backing_dev_info.state = 0;
463         q->backing_dev_info.capabilities = BDI_CAP_MAP_COPY;
464         q->backing_dev_info.name = "block";
465
466         err = bdi_init(&q->backing_dev_info);
467         if (err) {
468                 kmem_cache_free(blk_requestq_cachep, q);
469                 return NULL;
470         }
471
472         if (blk_throtl_init(q)) {
473                 kmem_cache_free(blk_requestq_cachep, q);
474                 return NULL;
475         }
476
477         setup_timer(&q->backing_dev_info.laptop_mode_wb_timer,
478                     laptop_mode_timer_fn, (unsigned long) q);
479         setup_timer(&q->timeout, blk_rq_timed_out_timer, (unsigned long) q);
480         INIT_LIST_HEAD(&q->timeout_list);
481         INIT_LIST_HEAD(&q->flush_queue[0]);
482         INIT_LIST_HEAD(&q->flush_queue[1]);
483         INIT_LIST_HEAD(&q->flush_data_in_flight);
484         INIT_DELAYED_WORK(&q->delay_work, blk_delay_work);
485
486         kobject_init(&q->kobj, &blk_queue_ktype);
487
488         mutex_init(&q->sysfs_lock);
489         spin_lock_init(&q->__queue_lock);
490
491         /*
492          * By default initialize queue_lock to internal lock and driver can
493          * override it later if need be.
494          */
495         q->queue_lock = &q->__queue_lock;
496
497         return q;
498 }
499 EXPORT_SYMBOL(blk_alloc_queue_node);
500
501 /**
502  * blk_init_queue  - prepare a request queue for use with a block device
503  * @rfn:  The function to be called to process requests that have been
504  *        placed on the queue.
505  * @lock: Request queue spin lock
506  *
507  * Description:
508  *    If a block device wishes to use the standard request handling procedures,
509  *    which sorts requests and coalesces adjacent requests, then it must
510  *    call blk_init_queue().  The function @rfn will be called when there
511  *    are requests on the queue that need to be processed.  If the device
512  *    supports plugging, then @rfn may not be called immediately when requests
513  *    are available on the queue, but may be called at some time later instead.
514  *    Plugged queues are generally unplugged when a buffer belonging to one
515  *    of the requests on the queue is needed, or due to memory pressure.
516  *
517  *    @rfn is not required, or even expected, to remove all requests off the
518  *    queue, but only as many as it can handle at a time.  If it does leave
519  *    requests on the queue, it is responsible for arranging that the requests
520  *    get dealt with eventually.
521  *
522  *    The queue spin lock must be held while manipulating the requests on the
523  *    request queue; this lock will be taken also from interrupt context, so irq
524  *    disabling is needed for it.
525  *
526  *    Function returns a pointer to the initialized request queue, or %NULL if
527  *    it didn't succeed.
528  *
529  * Note:
530  *    blk_init_queue() must be paired with a blk_cleanup_queue() call
531  *    when the block device is deactivated (such as at module unload).
532  **/
533
534 struct request_queue *blk_init_queue(request_fn_proc *rfn, spinlock_t *lock)
535 {
536         return blk_init_queue_node(rfn, lock, -1);
537 }
538 EXPORT_SYMBOL(blk_init_queue);
539
540 struct request_queue *
541 blk_init_queue_node(request_fn_proc *rfn, spinlock_t *lock, int node_id)
542 {
543         struct request_queue *uninit_q, *q;
544
545         uninit_q = blk_alloc_queue_node(GFP_KERNEL, node_id);
546         if (!uninit_q)
547                 return NULL;
548
549         q = blk_init_allocated_queue_node(uninit_q, rfn, lock, node_id);
550         if (!q)
551                 blk_cleanup_queue(uninit_q);
552
553         return q;
554 }
555 EXPORT_SYMBOL(blk_init_queue_node);
556
557 struct request_queue *
558 blk_init_allocated_queue(struct request_queue *q, request_fn_proc *rfn,
559                          spinlock_t *lock)
560 {
561         return blk_init_allocated_queue_node(q, rfn, lock, -1);
562 }
563 EXPORT_SYMBOL(blk_init_allocated_queue);
564
565 struct request_queue *
566 blk_init_allocated_queue_node(struct request_queue *q, request_fn_proc *rfn,
567                               spinlock_t *lock, int node_id)
568 {
569         if (!q)
570                 return NULL;
571
572         q->node = node_id;
573         if (blk_init_free_list(q))
574                 return NULL;
575
576         q->request_fn           = rfn;
577         q->prep_rq_fn           = NULL;
578         q->unprep_rq_fn         = NULL;
579         q->queue_flags          = QUEUE_FLAG_DEFAULT;
580
581         /* Override internal queue lock with supplied lock pointer */
582         if (lock)
583                 q->queue_lock           = lock;
584
585         /*
586          * This also sets hw/phys segments, boundary and size
587          */
588         blk_queue_make_request(q, blk_queue_bio);
589
590         q->sg_reserved_size = INT_MAX;
591
592         /*
593          * all done
594          */
595         if (!elevator_init(q, NULL)) {
596                 blk_queue_congestion_threshold(q);
597                 return q;
598         }
599
600         return NULL;
601 }
602 EXPORT_SYMBOL(blk_init_allocated_queue_node);
603
604 int blk_get_queue(struct request_queue *q)
605 {
606         if (likely(!test_bit(QUEUE_FLAG_DEAD, &q->queue_flags))) {
607                 kobject_get(&q->kobj);
608                 return 0;
609         }
610
611         return 1;
612 }
613 EXPORT_SYMBOL(blk_get_queue);
614
615 static inline void blk_free_request(struct request_queue *q, struct request *rq)
616 {
617         if (rq->cmd_flags & REQ_ELVPRIV)
618                 elv_put_request(q, rq);
619         mempool_free(rq, q->rq.rq_pool);
620 }
621
622 static struct request *
623 blk_alloc_request(struct request_queue *q, unsigned int flags, gfp_t gfp_mask)
624 {
625         struct request *rq = mempool_alloc(q->rq.rq_pool, gfp_mask);
626
627         if (!rq)
628                 return NULL;
629
630         blk_rq_init(q, rq);
631
632         rq->cmd_flags = flags | REQ_ALLOCED;
633
634         if ((flags & REQ_ELVPRIV) &&
635             unlikely(elv_set_request(q, rq, gfp_mask))) {
636                 mempool_free(rq, q->rq.rq_pool);
637                 return NULL;
638         }
639
640         return rq;
641 }
642
643 /*
644  * ioc_batching returns true if the ioc is a valid batching request and
645  * should be given priority access to a request.
646  */
647 static inline int ioc_batching(struct request_queue *q, struct io_context *ioc)
648 {
649         if (!ioc)
650                 return 0;
651
652         /*
653          * Make sure the process is able to allocate at least 1 request
654          * even if the batch times out, otherwise we could theoretically
655          * lose wakeups.
656          */
657         return ioc->nr_batch_requests == q->nr_batching ||
658                 (ioc->nr_batch_requests > 0
659                 && time_before(jiffies, ioc->last_waited + BLK_BATCH_TIME));
660 }
661
662 /*
663  * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
664  * will cause the process to be a "batcher" on all queues in the system. This
665  * is the behaviour we want though - once it gets a wakeup it should be given
666  * a nice run.
667  */
668 static void ioc_set_batching(struct request_queue *q, struct io_context *ioc)
669 {
670         if (!ioc || ioc_batching(q, ioc))
671                 return;
672
673         ioc->nr_batch_requests = q->nr_batching;
674         ioc->last_waited = jiffies;
675 }
676
677 static void __freed_request(struct request_queue *q, int sync)
678 {
679         struct request_list *rl = &q->rq;
680
681         if (rl->count[sync] < queue_congestion_off_threshold(q))
682                 blk_clear_queue_congested(q, sync);
683
684         if (rl->count[sync] + 1 <= q->nr_requests) {
685                 if (waitqueue_active(&rl->wait[sync]))
686                         wake_up(&rl->wait[sync]);
687
688                 blk_clear_queue_full(q, sync);
689         }
690 }
691
692 /*
693  * A request has just been released.  Account for it, update the full and
694  * congestion status, wake up any waiters.   Called under q->queue_lock.
695  */
696 static void freed_request(struct request_queue *q, unsigned int flags)
697 {
698         struct request_list *rl = &q->rq;
699         int sync = rw_is_sync(flags);
700
701         rl->count[sync]--;
702         if (flags & REQ_ELVPRIV)
703                 rl->elvpriv--;
704
705         __freed_request(q, sync);
706
707         if (unlikely(rl->starved[sync ^ 1]))
708                 __freed_request(q, sync ^ 1);
709 }
710
711 /*
712  * Determine if elevator data should be initialized when allocating the
713  * request associated with @bio.
714  */
715 static bool blk_rq_should_init_elevator(struct bio *bio)
716 {
717         if (!bio)
718                 return true;
719
720         /*
721          * Flush requests do not use the elevator so skip initialization.
722          * This allows a request to share the flush and elevator data.
723          */
724         if (bio->bi_rw & (REQ_FLUSH | REQ_FUA))
725                 return false;
726
727         return true;
728 }
729
730 /**
731  * get_request - get a free request
732  * @q: request_queue to allocate request from
733  * @rw_flags: RW and SYNC flags
734  * @bio: bio to allocate request for (can be %NULL)
735  * @gfp_mask: allocation mask
736  *
737  * Get a free request from @q.  This function may fail under memory
738  * pressure or if @q is dead.
739  *
740  * Must be callled with @q->queue_lock held and,
741  * Returns %NULL on failure, with @q->queue_lock held.
742  * Returns !%NULL on success, with @q->queue_lock *not held*.
743  */
744 static struct request *get_request(struct request_queue *q, int rw_flags,
745                                    struct bio *bio, gfp_t gfp_mask)
746 {
747         struct request *rq = NULL;
748         struct request_list *rl = &q->rq;
749         struct io_context *ioc = NULL;
750         const bool is_sync = rw_is_sync(rw_flags) != 0;
751         int may_queue;
752
753         if (unlikely(test_bit(QUEUE_FLAG_DEAD, &q->queue_flags)))
754                 return NULL;
755
756         may_queue = elv_may_queue(q, rw_flags);
757         if (may_queue == ELV_MQUEUE_NO)
758                 goto rq_starved;
759
760         if (rl->count[is_sync]+1 >= queue_congestion_on_threshold(q)) {
761                 if (rl->count[is_sync]+1 >= q->nr_requests) {
762                         ioc = current_io_context(GFP_ATOMIC, q->node);
763                         /*
764                          * The queue will fill after this allocation, so set
765                          * it as full, and mark this process as "batching".
766                          * This process will be allowed to complete a batch of
767                          * requests, others will be blocked.
768                          */
769                         if (!blk_queue_full(q, is_sync)) {
770                                 ioc_set_batching(q, ioc);
771                                 blk_set_queue_full(q, is_sync);
772                         } else {
773                                 if (may_queue != ELV_MQUEUE_MUST
774                                                 && !ioc_batching(q, ioc)) {
775                                         /*
776                                          * The queue is full and the allocating
777                                          * process is not a "batcher", and not
778                                          * exempted by the IO scheduler
779                                          */
780                                         goto out;
781                                 }
782                         }
783                 }
784                 blk_set_queue_congested(q, is_sync);
785         }
786
787         /*
788          * Only allow batching queuers to allocate up to 50% over the defined
789          * limit of requests, otherwise we could have thousands of requests
790          * allocated with any setting of ->nr_requests
791          */
792         if (rl->count[is_sync] >= (3 * q->nr_requests / 2))
793                 goto out;
794
795         rl->count[is_sync]++;
796         rl->starved[is_sync] = 0;
797
798         if (blk_rq_should_init_elevator(bio) &&
799             !test_bit(QUEUE_FLAG_ELVSWITCH, &q->queue_flags)) {
800                 rw_flags |= REQ_ELVPRIV;
801                 rl->elvpriv++;
802         }
803
804         if (blk_queue_io_stat(q))
805                 rw_flags |= REQ_IO_STAT;
806         spin_unlock_irq(q->queue_lock);
807
808         rq = blk_alloc_request(q, rw_flags, gfp_mask);
809         if (unlikely(!rq)) {
810                 /*
811                  * Allocation failed presumably due to memory. Undo anything
812                  * we might have messed up.
813                  *
814                  * Allocating task should really be put onto the front of the
815                  * wait queue, but this is pretty rare.
816                  */
817                 spin_lock_irq(q->queue_lock);
818                 freed_request(q, rw_flags);
819
820                 /*
821                  * in the very unlikely event that allocation failed and no
822                  * requests for this direction was pending, mark us starved
823                  * so that freeing of a request in the other direction will
824                  * notice us. another possible fix would be to split the
825                  * rq mempool into READ and WRITE
826                  */
827 rq_starved:
828                 if (unlikely(rl->count[is_sync] == 0))
829                         rl->starved[is_sync] = 1;
830
831                 goto out;
832         }
833
834         /*
835          * ioc may be NULL here, and ioc_batching will be false. That's
836          * OK, if the queue is under the request limit then requests need
837          * not count toward the nr_batch_requests limit. There will always
838          * be some limit enforced by BLK_BATCH_TIME.
839          */
840         if (ioc_batching(q, ioc))
841                 ioc->nr_batch_requests--;
842
843         trace_block_getrq(q, bio, rw_flags & 1);
844 out:
845         return rq;
846 }
847
848 /**
849  * get_request_wait - get a free request with retry
850  * @q: request_queue to allocate request from
851  * @rw_flags: RW and SYNC flags
852  * @bio: bio to allocate request for (can be %NULL)
853  *
854  * Get a free request from @q.  This function keeps retrying under memory
855  * pressure and fails iff @q is dead.
856  *
857  * Must be callled with @q->queue_lock held and,
858  * Returns %NULL on failure, with @q->queue_lock held.
859  * Returns !%NULL on success, with @q->queue_lock *not held*.
860  */
861 static struct request *get_request_wait(struct request_queue *q, int rw_flags,
862                                         struct bio *bio)
863 {
864         const bool is_sync = rw_is_sync(rw_flags) != 0;
865         struct request *rq;
866
867         rq = get_request(q, rw_flags, bio, GFP_NOIO);
868         while (!rq) {
869                 DEFINE_WAIT(wait);
870                 struct io_context *ioc;
871                 struct request_list *rl = &q->rq;
872
873                 if (unlikely(test_bit(QUEUE_FLAG_DEAD, &q->queue_flags)))
874                         return NULL;
875
876                 prepare_to_wait_exclusive(&rl->wait[is_sync], &wait,
877                                 TASK_UNINTERRUPTIBLE);
878
879                 trace_block_sleeprq(q, bio, rw_flags & 1);
880
881                 spin_unlock_irq(q->queue_lock);
882                 io_schedule();
883
884                 /*
885                  * After sleeping, we become a "batching" process and
886                  * will be able to allocate at least one request, and
887                  * up to a big batch of them for a small period time.
888                  * See ioc_batching, ioc_set_batching
889                  */
890                 ioc = current_io_context(GFP_NOIO, q->node);
891                 ioc_set_batching(q, ioc);
892
893                 spin_lock_irq(q->queue_lock);
894                 finish_wait(&rl->wait[is_sync], &wait);
895
896                 rq = get_request(q, rw_flags, bio, GFP_NOIO);
897         };
898
899         return rq;
900 }
901
902 struct request *blk_get_request(struct request_queue *q, int rw, gfp_t gfp_mask)
903 {
904         struct request *rq;
905
906         BUG_ON(rw != READ && rw != WRITE);
907
908         spin_lock_irq(q->queue_lock);
909         if (gfp_mask & __GFP_WAIT)
910                 rq = get_request_wait(q, rw, NULL);
911         else
912                 rq = get_request(q, rw, NULL, gfp_mask);
913         if (!rq)
914                 spin_unlock_irq(q->queue_lock);
915         /* q->queue_lock is unlocked at this point */
916
917         return rq;
918 }
919 EXPORT_SYMBOL(blk_get_request);
920
921 /**
922  * blk_make_request - given a bio, allocate a corresponding struct request.
923  * @q: target request queue
924  * @bio:  The bio describing the memory mappings that will be submitted for IO.
925  *        It may be a chained-bio properly constructed by block/bio layer.
926  * @gfp_mask: gfp flags to be used for memory allocation
927  *
928  * blk_make_request is the parallel of generic_make_request for BLOCK_PC
929  * type commands. Where the struct request needs to be farther initialized by
930  * the caller. It is passed a &struct bio, which describes the memory info of
931  * the I/O transfer.
932  *
933  * The caller of blk_make_request must make sure that bi_io_vec
934  * are set to describe the memory buffers. That bio_data_dir() will return
935  * the needed direction of the request. (And all bio's in the passed bio-chain
936  * are properly set accordingly)
937  *
938  * If called under none-sleepable conditions, mapped bio buffers must not
939  * need bouncing, by calling the appropriate masked or flagged allocator,
940  * suitable for the target device. Otherwise the call to blk_queue_bounce will
941  * BUG.
942  *
943  * WARNING: When allocating/cloning a bio-chain, careful consideration should be
944  * given to how you allocate bios. In particular, you cannot use __GFP_WAIT for
945  * anything but the first bio in the chain. Otherwise you risk waiting for IO
946  * completion of a bio that hasn't been submitted yet, thus resulting in a
947  * deadlock. Alternatively bios should be allocated using bio_kmalloc() instead
948  * of bio_alloc(), as that avoids the mempool deadlock.
949  * If possible a big IO should be split into smaller parts when allocation
950  * fails. Partial allocation should not be an error, or you risk a live-lock.
951  */
952 struct request *blk_make_request(struct request_queue *q, struct bio *bio,
953                                  gfp_t gfp_mask)
954 {
955         struct request *rq = blk_get_request(q, bio_data_dir(bio), gfp_mask);
956
957         if (unlikely(!rq))
958                 return ERR_PTR(-ENOMEM);
959
960         for_each_bio(bio) {
961                 struct bio *bounce_bio = bio;
962                 int ret;
963
964                 blk_queue_bounce(q, &bounce_bio);
965                 ret = blk_rq_append_bio(q, rq, bounce_bio);
966                 if (unlikely(ret)) {
967                         blk_put_request(rq);
968                         return ERR_PTR(ret);
969                 }
970         }
971
972         return rq;
973 }
974 EXPORT_SYMBOL(blk_make_request);
975
976 /**
977  * blk_requeue_request - put a request back on queue
978  * @q:          request queue where request should be inserted
979  * @rq:         request to be inserted
980  *
981  * Description:
982  *    Drivers often keep queueing requests until the hardware cannot accept
983  *    more, when that condition happens we need to put the request back
984  *    on the queue. Must be called with queue lock held.
985  */
986 void blk_requeue_request(struct request_queue *q, struct request *rq)
987 {
988         blk_delete_timer(rq);
989         blk_clear_rq_complete(rq);
990         trace_block_rq_requeue(q, rq);
991
992         if (blk_rq_tagged(rq))
993                 blk_queue_end_tag(q, rq);
994
995         BUG_ON(blk_queued_rq(rq));
996
997         elv_requeue_request(q, rq);
998 }
999 EXPORT_SYMBOL(blk_requeue_request);
1000
1001 static void add_acct_request(struct request_queue *q, struct request *rq,
1002                              int where)
1003 {
1004         drive_stat_acct(rq, 1);
1005         __elv_add_request(q, rq, where);
1006 }
1007
1008 /**
1009  * blk_insert_request - insert a special request into a request queue
1010  * @q:          request queue where request should be inserted
1011  * @rq:         request to be inserted
1012  * @at_head:    insert request at head or tail of queue
1013  * @data:       private data
1014  *
1015  * Description:
1016  *    Many block devices need to execute commands asynchronously, so they don't
1017  *    block the whole kernel from preemption during request execution.  This is
1018  *    accomplished normally by inserting aritficial requests tagged as
1019  *    REQ_TYPE_SPECIAL in to the corresponding request queue, and letting them
1020  *    be scheduled for actual execution by the request queue.
1021  *
1022  *    We have the option of inserting the head or the tail of the queue.
1023  *    Typically we use the tail for new ioctls and so forth.  We use the head
1024  *    of the queue for things like a QUEUE_FULL message from a device, or a
1025  *    host that is unable to accept a particular command.
1026  */
1027 void blk_insert_request(struct request_queue *q, struct request *rq,
1028                         int at_head, void *data)
1029 {
1030         int where = at_head ? ELEVATOR_INSERT_FRONT : ELEVATOR_INSERT_BACK;
1031         unsigned long flags;
1032
1033         /*
1034          * tell I/O scheduler that this isn't a regular read/write (ie it
1035          * must not attempt merges on this) and that it acts as a soft
1036          * barrier
1037          */
1038         rq->cmd_type = REQ_TYPE_SPECIAL;
1039
1040         rq->special = data;
1041
1042         spin_lock_irqsave(q->queue_lock, flags);
1043
1044         /*
1045          * If command is tagged, release the tag
1046          */
1047         if (blk_rq_tagged(rq))
1048                 blk_queue_end_tag(q, rq);
1049
1050         add_acct_request(q, rq, where);
1051         __blk_run_queue(q);
1052         spin_unlock_irqrestore(q->queue_lock, flags);
1053 }
1054 EXPORT_SYMBOL(blk_insert_request);
1055
1056 static void part_round_stats_single(int cpu, struct hd_struct *part,
1057                                     unsigned long now)
1058 {
1059         if (now == part->stamp)
1060                 return;
1061
1062         if (part_in_flight(part)) {
1063                 __part_stat_add(cpu, part, time_in_queue,
1064                                 part_in_flight(part) * (now - part->stamp));
1065                 __part_stat_add(cpu, part, io_ticks, (now - part->stamp));
1066         }
1067         part->stamp = now;
1068 }
1069
1070 /**
1071  * part_round_stats() - Round off the performance stats on a struct disk_stats.
1072  * @cpu: cpu number for stats access
1073  * @part: target partition
1074  *
1075  * The average IO queue length and utilisation statistics are maintained
1076  * by observing the current state of the queue length and the amount of
1077  * time it has been in this state for.
1078  *
1079  * Normally, that accounting is done on IO completion, but that can result
1080  * in more than a second's worth of IO being accounted for within any one
1081  * second, leading to >100% utilisation.  To deal with that, we call this
1082  * function to do a round-off before returning the results when reading
1083  * /proc/diskstats.  This accounts immediately for all queue usage up to
1084  * the current jiffies and restarts the counters again.
1085  */
1086 void part_round_stats(int cpu, struct hd_struct *part)
1087 {
1088         unsigned long now = jiffies;
1089
1090         if (part->partno)
1091                 part_round_stats_single(cpu, &part_to_disk(part)->part0, now);
1092         part_round_stats_single(cpu, part, now);
1093 }
1094 EXPORT_SYMBOL_GPL(part_round_stats);
1095
1096 /*
1097  * queue lock must be held
1098  */
1099 void __blk_put_request(struct request_queue *q, struct request *req)
1100 {
1101         if (unlikely(!q))
1102                 return;
1103         if (unlikely(--req->ref_count))
1104                 return;
1105
1106         elv_completed_request(q, req);
1107
1108         /* this is a bio leak */
1109         WARN_ON(req->bio != NULL);
1110
1111         /*
1112          * Request may not have originated from ll_rw_blk. if not,
1113          * it didn't come out of our reserved rq pools
1114          */
1115         if (req->cmd_flags & REQ_ALLOCED) {
1116                 unsigned int flags = req->cmd_flags;
1117
1118                 BUG_ON(!list_empty(&req->queuelist));
1119                 BUG_ON(!hlist_unhashed(&req->hash));
1120
1121                 blk_free_request(q, req);
1122                 freed_request(q, flags);
1123         }
1124 }
1125 EXPORT_SYMBOL_GPL(__blk_put_request);
1126
1127 void blk_put_request(struct request *req)
1128 {
1129         unsigned long flags;
1130         struct request_queue *q = req->q;
1131
1132         spin_lock_irqsave(q->queue_lock, flags);
1133         __blk_put_request(q, req);
1134         spin_unlock_irqrestore(q->queue_lock, flags);
1135 }
1136 EXPORT_SYMBOL(blk_put_request);
1137
1138 /**
1139  * blk_add_request_payload - add a payload to a request
1140  * @rq: request to update
1141  * @page: page backing the payload
1142  * @len: length of the payload.
1143  *
1144  * This allows to later add a payload to an already submitted request by
1145  * a block driver.  The driver needs to take care of freeing the payload
1146  * itself.
1147  *
1148  * Note that this is a quite horrible hack and nothing but handling of
1149  * discard requests should ever use it.
1150  */
1151 void blk_add_request_payload(struct request *rq, struct page *page,
1152                 unsigned int len)
1153 {
1154         struct bio *bio = rq->bio;
1155
1156         bio->bi_io_vec->bv_page = page;
1157         bio->bi_io_vec->bv_offset = 0;
1158         bio->bi_io_vec->bv_len = len;
1159
1160         bio->bi_size = len;
1161         bio->bi_vcnt = 1;
1162         bio->bi_phys_segments = 1;
1163
1164         rq->__data_len = rq->resid_len = len;
1165         rq->nr_phys_segments = 1;
1166         rq->buffer = bio_data(bio);
1167 }
1168 EXPORT_SYMBOL_GPL(blk_add_request_payload);
1169
1170 static bool bio_attempt_back_merge(struct request_queue *q, struct request *req,
1171                                    struct bio *bio)
1172 {
1173         const int ff = bio->bi_rw & REQ_FAILFAST_MASK;
1174
1175         if (!ll_back_merge_fn(q, req, bio))
1176                 return false;
1177
1178         trace_block_bio_backmerge(q, bio);
1179
1180         if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
1181                 blk_rq_set_mixed_merge(req);
1182
1183         req->biotail->bi_next = bio;
1184         req->biotail = bio;
1185         req->__data_len += bio->bi_size;
1186         req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
1187
1188         drive_stat_acct(req, 0);
1189         elv_bio_merged(q, req, bio);
1190         return true;
1191 }
1192
1193 static bool bio_attempt_front_merge(struct request_queue *q,
1194                                     struct request *req, struct bio *bio)
1195 {
1196         const int ff = bio->bi_rw & REQ_FAILFAST_MASK;
1197
1198         if (!ll_front_merge_fn(q, req, bio))
1199                 return false;
1200
1201         trace_block_bio_frontmerge(q, bio);
1202
1203         if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
1204                 blk_rq_set_mixed_merge(req);
1205
1206         bio->bi_next = req->bio;
1207         req->bio = bio;
1208
1209         /*
1210          * may not be valid. if the low level driver said
1211          * it didn't need a bounce buffer then it better
1212          * not touch req->buffer either...
1213          */
1214         req->buffer = bio_data(bio);
1215         req->__sector = bio->bi_sector;
1216         req->__data_len += bio->bi_size;
1217         req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
1218
1219         drive_stat_acct(req, 0);
1220         elv_bio_merged(q, req, bio);
1221         return true;
1222 }
1223
1224 /**
1225  * attempt_plug_merge - try to merge with %current's plugged list
1226  * @q: request_queue new bio is being queued at
1227  * @bio: new bio being queued
1228  * @request_count: out parameter for number of traversed plugged requests
1229  *
1230  * Determine whether @bio being queued on @q can be merged with a request
1231  * on %current's plugged list.  Returns %true if merge was successful,
1232  * otherwise %false.
1233  *
1234  * This function is called without @q->queue_lock; however, elevator is
1235  * accessed iff there already are requests on the plugged list which in
1236  * turn guarantees validity of the elevator.
1237  *
1238  * Note that, on successful merge, elevator operation
1239  * elevator_bio_merged_fn() will be called without queue lock.  Elevator
1240  * must be ready for this.
1241  */
1242 static bool attempt_plug_merge(struct request_queue *q, struct bio *bio,
1243                                unsigned int *request_count)
1244 {
1245         struct blk_plug *plug;
1246         struct request *rq;
1247         bool ret = false;
1248
1249         plug = current->plug;
1250         if (!plug)
1251                 goto out;
1252         *request_count = 0;
1253
1254         list_for_each_entry_reverse(rq, &plug->list, queuelist) {
1255                 int el_ret;
1256
1257                 (*request_count)++;
1258
1259                 if (rq->q != q)
1260                         continue;
1261
1262                 el_ret = elv_try_merge(rq, bio);
1263                 if (el_ret == ELEVATOR_BACK_MERGE) {
1264                         ret = bio_attempt_back_merge(q, rq, bio);
1265                         if (ret)
1266                                 break;
1267                 } else if (el_ret == ELEVATOR_FRONT_MERGE) {
1268                         ret = bio_attempt_front_merge(q, rq, bio);
1269                         if (ret)
1270                                 break;
1271                 }
1272         }
1273 out:
1274         return ret;
1275 }
1276
1277 void init_request_from_bio(struct request *req, struct bio *bio)
1278 {
1279         req->cmd_type = REQ_TYPE_FS;
1280
1281         req->cmd_flags |= bio->bi_rw & REQ_COMMON_MASK;
1282         if (bio->bi_rw & REQ_RAHEAD)
1283                 req->cmd_flags |= REQ_FAILFAST_MASK;
1284
1285         req->errors = 0;
1286         req->__sector = bio->bi_sector;
1287         req->ioprio = bio_prio(bio);
1288         blk_rq_bio_prep(req->q, req, bio);
1289 }
1290
1291 void blk_queue_bio(struct request_queue *q, struct bio *bio)
1292 {
1293         const bool sync = !!(bio->bi_rw & REQ_SYNC);
1294         struct blk_plug *plug;
1295         int el_ret, rw_flags, where = ELEVATOR_INSERT_SORT;
1296         struct request *req;
1297         unsigned int request_count = 0;
1298
1299         /*
1300          * low level driver can indicate that it wants pages above a
1301          * certain limit bounced to low memory (ie for highmem, or even
1302          * ISA dma in theory)
1303          */
1304         blk_queue_bounce(q, &bio);
1305
1306         if (bio->bi_rw & (REQ_FLUSH | REQ_FUA)) {
1307                 spin_lock_irq(q->queue_lock);
1308                 where = ELEVATOR_INSERT_FLUSH;
1309                 goto get_rq;
1310         }
1311
1312         /*
1313          * Check if we can merge with the plugged list before grabbing
1314          * any locks.
1315          */
1316         if (attempt_plug_merge(q, bio, &request_count))
1317                 return;
1318
1319         spin_lock_irq(q->queue_lock);
1320
1321         el_ret = elv_merge(q, &req, bio);
1322         if (el_ret == ELEVATOR_BACK_MERGE) {
1323                 if (bio_attempt_back_merge(q, req, bio)) {
1324                         if (!attempt_back_merge(q, req))
1325                                 elv_merged_request(q, req, el_ret);
1326                         goto out_unlock;
1327                 }
1328         } else if (el_ret == ELEVATOR_FRONT_MERGE) {
1329                 if (bio_attempt_front_merge(q, req, bio)) {
1330                         if (!attempt_front_merge(q, req))
1331                                 elv_merged_request(q, req, el_ret);
1332                         goto out_unlock;
1333                 }
1334         }
1335
1336 get_rq:
1337         /*
1338          * This sync check and mask will be re-done in init_request_from_bio(),
1339          * but we need to set it earlier to expose the sync flag to the
1340          * rq allocator and io schedulers.
1341          */
1342         rw_flags = bio_data_dir(bio);
1343         if (sync)
1344                 rw_flags |= REQ_SYNC;
1345
1346         /*
1347          * Grab a free request. This is might sleep but can not fail.
1348          * Returns with the queue unlocked.
1349          */
1350         req = get_request_wait(q, rw_flags, bio);
1351         if (unlikely(!req)) {
1352                 bio_endio(bio, -ENODEV);        /* @q is dead */
1353                 goto out_unlock;
1354         }
1355
1356         /*
1357          * After dropping the lock and possibly sleeping here, our request
1358          * may now be mergeable after it had proven unmergeable (above).
1359          * We don't worry about that case for efficiency. It won't happen
1360          * often, and the elevators are able to handle it.
1361          */
1362         init_request_from_bio(req, bio);
1363
1364         if (test_bit(QUEUE_FLAG_SAME_COMP, &q->queue_flags))
1365                 req->cpu = raw_smp_processor_id();
1366
1367         plug = current->plug;
1368         if (plug) {
1369                 /*
1370                  * If this is the first request added after a plug, fire
1371                  * of a plug trace. If others have been added before, check
1372                  * if we have multiple devices in this plug. If so, make a
1373                  * note to sort the list before dispatch.
1374                  */
1375                 if (list_empty(&plug->list))
1376                         trace_block_plug(q);
1377                 else if (!plug->should_sort) {
1378                         struct request *__rq;
1379
1380                         __rq = list_entry_rq(plug->list.prev);
1381                         if (__rq->q != q)
1382                                 plug->should_sort = 1;
1383                 }
1384                 if (request_count >= BLK_MAX_REQUEST_COUNT)
1385                         blk_flush_plug_list(plug, false);
1386                 list_add_tail(&req->queuelist, &plug->list);
1387                 drive_stat_acct(req, 1);
1388         } else {
1389                 spin_lock_irq(q->queue_lock);
1390                 add_acct_request(q, req, where);
1391                 __blk_run_queue(q);
1392 out_unlock:
1393                 spin_unlock_irq(q->queue_lock);
1394         }
1395 }
1396 EXPORT_SYMBOL_GPL(blk_queue_bio);       /* for device mapper only */
1397
1398 /*
1399  * If bio->bi_dev is a partition, remap the location
1400  */
1401 static inline void blk_partition_remap(struct bio *bio)
1402 {
1403         struct block_device *bdev = bio->bi_bdev;
1404
1405         if (bio_sectors(bio) && bdev != bdev->bd_contains) {
1406                 struct hd_struct *p = bdev->bd_part;
1407
1408                 bio->bi_sector += p->start_sect;
1409                 bio->bi_bdev = bdev->bd_contains;
1410
1411                 trace_block_bio_remap(bdev_get_queue(bio->bi_bdev), bio,
1412                                       bdev->bd_dev,
1413                                       bio->bi_sector - p->start_sect);
1414         }
1415 }
1416
1417 static void handle_bad_sector(struct bio *bio)
1418 {
1419         char b[BDEVNAME_SIZE];
1420
1421         printk(KERN_INFO "attempt to access beyond end of device\n");
1422         printk(KERN_INFO "%s: rw=%ld, want=%Lu, limit=%Lu\n",
1423                         bdevname(bio->bi_bdev, b),
1424                         bio->bi_rw,
1425                         (unsigned long long)bio->bi_sector + bio_sectors(bio),
1426                         (long long)(i_size_read(bio->bi_bdev->bd_inode) >> 9));
1427
1428         set_bit(BIO_EOF, &bio->bi_flags);
1429 }
1430
1431 #ifdef CONFIG_FAIL_MAKE_REQUEST
1432
1433 static DECLARE_FAULT_ATTR(fail_make_request);
1434
1435 static int __init setup_fail_make_request(char *str)
1436 {
1437         return setup_fault_attr(&fail_make_request, str);
1438 }
1439 __setup("fail_make_request=", setup_fail_make_request);
1440
1441 static bool should_fail_request(struct hd_struct *part, unsigned int bytes)
1442 {
1443         return part->make_it_fail && should_fail(&fail_make_request, bytes);
1444 }
1445
1446 static int __init fail_make_request_debugfs(void)
1447 {
1448         struct dentry *dir = fault_create_debugfs_attr("fail_make_request",
1449                                                 NULL, &fail_make_request);
1450
1451         return IS_ERR(dir) ? PTR_ERR(dir) : 0;
1452 }
1453
1454 late_initcall(fail_make_request_debugfs);
1455
1456 #else /* CONFIG_FAIL_MAKE_REQUEST */
1457
1458 static inline bool should_fail_request(struct hd_struct *part,
1459                                         unsigned int bytes)
1460 {
1461         return false;
1462 }
1463
1464 #endif /* CONFIG_FAIL_MAKE_REQUEST */
1465
1466 /*
1467  * Check whether this bio extends beyond the end of the device.
1468  */
1469 static inline int bio_check_eod(struct bio *bio, unsigned int nr_sectors)
1470 {
1471         sector_t maxsector;
1472
1473         if (!nr_sectors)
1474                 return 0;
1475
1476         /* Test device or partition size, when known. */
1477         maxsector = i_size_read(bio->bi_bdev->bd_inode) >> 9;
1478         if (maxsector) {
1479                 sector_t sector = bio->bi_sector;
1480
1481                 if (maxsector < nr_sectors || maxsector - nr_sectors < sector) {
1482                         /*
1483                          * This may well happen - the kernel calls bread()
1484                          * without checking the size of the device, e.g., when
1485                          * mounting a device.
1486                          */
1487                         handle_bad_sector(bio);
1488                         return 1;
1489                 }
1490         }
1491
1492         return 0;
1493 }
1494
1495 static noinline_for_stack bool
1496 generic_make_request_checks(struct bio *bio)
1497 {
1498         struct request_queue *q;
1499         int nr_sectors = bio_sectors(bio);
1500         int err = -EIO;
1501         char b[BDEVNAME_SIZE];
1502         struct hd_struct *part;
1503
1504         might_sleep();
1505
1506         if (bio_check_eod(bio, nr_sectors))
1507                 goto end_io;
1508
1509         q = bdev_get_queue(bio->bi_bdev);
1510         if (unlikely(!q)) {
1511                 printk(KERN_ERR
1512                        "generic_make_request: Trying to access "
1513                         "nonexistent block-device %s (%Lu)\n",
1514                         bdevname(bio->bi_bdev, b),
1515                         (long long) bio->bi_sector);
1516                 goto end_io;
1517         }
1518
1519         if (unlikely(!(bio->bi_rw & REQ_DISCARD) &&
1520                      nr_sectors > queue_max_hw_sectors(q))) {
1521                 printk(KERN_ERR "bio too big device %s (%u > %u)\n",
1522                        bdevname(bio->bi_bdev, b),
1523                        bio_sectors(bio),
1524                        queue_max_hw_sectors(q));
1525                 goto end_io;
1526         }
1527
1528         part = bio->bi_bdev->bd_part;
1529         if (should_fail_request(part, bio->bi_size) ||
1530             should_fail_request(&part_to_disk(part)->part0,
1531                                 bio->bi_size))
1532                 goto end_io;
1533
1534         /*
1535          * If this device has partitions, remap block n
1536          * of partition p to block n+start(p) of the disk.
1537          */
1538         blk_partition_remap(bio);
1539
1540         if (bio_integrity_enabled(bio) && bio_integrity_prep(bio))
1541                 goto end_io;
1542
1543         if (bio_check_eod(bio, nr_sectors))
1544                 goto end_io;
1545
1546         /*
1547          * Filter flush bio's early so that make_request based
1548          * drivers without flush support don't have to worry
1549          * about them.
1550          */
1551         if ((bio->bi_rw & (REQ_FLUSH | REQ_FUA)) && !q->flush_flags) {
1552                 bio->bi_rw &= ~(REQ_FLUSH | REQ_FUA);
1553                 if (!nr_sectors) {
1554                         err = 0;
1555                         goto end_io;
1556                 }
1557         }
1558
1559         if ((bio->bi_rw & REQ_DISCARD) &&
1560             (!blk_queue_discard(q) ||
1561              ((bio->bi_rw & REQ_SECURE) &&
1562               !blk_queue_secdiscard(q)))) {
1563                 err = -EOPNOTSUPP;
1564                 goto end_io;
1565         }
1566
1567         if (blk_throtl_bio(q, bio))
1568                 return false;   /* throttled, will be resubmitted later */
1569
1570         trace_block_bio_queue(q, bio);
1571         return true;
1572
1573 end_io:
1574         bio_endio(bio, err);
1575         return false;
1576 }
1577
1578 /**
1579  * generic_make_request - hand a buffer to its device driver for I/O
1580  * @bio:  The bio describing the location in memory and on the device.
1581  *
1582  * generic_make_request() is used to make I/O requests of block
1583  * devices. It is passed a &struct bio, which describes the I/O that needs
1584  * to be done.
1585  *
1586  * generic_make_request() does not return any status.  The
1587  * success/failure status of the request, along with notification of
1588  * completion, is delivered asynchronously through the bio->bi_end_io
1589  * function described (one day) else where.
1590  *
1591  * The caller of generic_make_request must make sure that bi_io_vec
1592  * are set to describe the memory buffer, and that bi_dev and bi_sector are
1593  * set to describe the device address, and the
1594  * bi_end_io and optionally bi_private are set to describe how
1595  * completion notification should be signaled.
1596  *
1597  * generic_make_request and the drivers it calls may use bi_next if this
1598  * bio happens to be merged with someone else, and may resubmit the bio to
1599  * a lower device by calling into generic_make_request recursively, which
1600  * means the bio should NOT be touched after the call to ->make_request_fn.
1601  */
1602 void generic_make_request(struct bio *bio)
1603 {
1604         struct bio_list bio_list_on_stack;
1605
1606         if (!generic_make_request_checks(bio))
1607                 return;
1608
1609         /*
1610          * We only want one ->make_request_fn to be active at a time, else
1611          * stack usage with stacked devices could be a problem.  So use
1612          * current->bio_list to keep a list of requests submited by a
1613          * make_request_fn function.  current->bio_list is also used as a
1614          * flag to say if generic_make_request is currently active in this
1615          * task or not.  If it is NULL, then no make_request is active.  If
1616          * it is non-NULL, then a make_request is active, and new requests
1617          * should be added at the tail
1618          */
1619         if (current->bio_list) {
1620                 bio_list_add(current->bio_list, bio);
1621                 return;
1622         }
1623
1624         /* following loop may be a bit non-obvious, and so deserves some
1625          * explanation.
1626          * Before entering the loop, bio->bi_next is NULL (as all callers
1627          * ensure that) so we have a list with a single bio.
1628          * We pretend that we have just taken it off a longer list, so
1629          * we assign bio_list to a pointer to the bio_list_on_stack,
1630          * thus initialising the bio_list of new bios to be
1631          * added.  ->make_request() may indeed add some more bios
1632          * through a recursive call to generic_make_request.  If it
1633          * did, we find a non-NULL value in bio_list and re-enter the loop
1634          * from the top.  In this case we really did just take the bio
1635          * of the top of the list (no pretending) and so remove it from
1636          * bio_list, and call into ->make_request() again.
1637          */
1638         BUG_ON(bio->bi_next);
1639         bio_list_init(&bio_list_on_stack);
1640         current->bio_list = &bio_list_on_stack;
1641         do {
1642                 struct request_queue *q = bdev_get_queue(bio->bi_bdev);
1643
1644                 q->make_request_fn(q, bio);
1645
1646                 bio = bio_list_pop(current->bio_list);
1647         } while (bio);
1648         current->bio_list = NULL; /* deactivate */
1649 }
1650 EXPORT_SYMBOL(generic_make_request);
1651
1652 /**
1653  * submit_bio - submit a bio to the block device layer for I/O
1654  * @rw: whether to %READ or %WRITE, or maybe to %READA (read ahead)
1655  * @bio: The &struct bio which describes the I/O
1656  *
1657  * submit_bio() is very similar in purpose to generic_make_request(), and
1658  * uses that function to do most of the work. Both are fairly rough
1659  * interfaces; @bio must be presetup and ready for I/O.
1660  *
1661  */
1662 void submit_bio(int rw, struct bio *bio)
1663 {
1664         int count = bio_sectors(bio);
1665
1666         bio->bi_rw |= rw;
1667
1668         /*
1669          * If it's a regular read/write or a barrier with data attached,
1670          * go through the normal accounting stuff before submission.
1671          */
1672         if (bio_has_data(bio) && !(rw & REQ_DISCARD)) {
1673                 if (rw & WRITE) {
1674                         count_vm_events(PGPGOUT, count);
1675                 } else {
1676                         task_io_account_read(bio->bi_size);
1677                         count_vm_events(PGPGIN, count);
1678                 }
1679
1680                 if (unlikely(block_dump)) {
1681                         char b[BDEVNAME_SIZE];
1682                         printk(KERN_DEBUG "%s(%d): %s block %Lu on %s (%u sectors)\n",
1683                         current->comm, task_pid_nr(current),
1684                                 (rw & WRITE) ? "WRITE" : "READ",
1685                                 (unsigned long long)bio->bi_sector,
1686                                 bdevname(bio->bi_bdev, b),
1687                                 count);
1688                 }
1689         }
1690
1691         generic_make_request(bio);
1692 }
1693 EXPORT_SYMBOL(submit_bio);
1694
1695 /**
1696  * blk_rq_check_limits - Helper function to check a request for the queue limit
1697  * @q:  the queue
1698  * @rq: the request being checked
1699  *
1700  * Description:
1701  *    @rq may have been made based on weaker limitations of upper-level queues
1702  *    in request stacking drivers, and it may violate the limitation of @q.
1703  *    Since the block layer and the underlying device driver trust @rq
1704  *    after it is inserted to @q, it should be checked against @q before
1705  *    the insertion using this generic function.
1706  *
1707  *    This function should also be useful for request stacking drivers
1708  *    in some cases below, so export this function.
1709  *    Request stacking drivers like request-based dm may change the queue
1710  *    limits while requests are in the queue (e.g. dm's table swapping).
1711  *    Such request stacking drivers should check those requests agaist
1712  *    the new queue limits again when they dispatch those requests,
1713  *    although such checkings are also done against the old queue limits
1714  *    when submitting requests.
1715  */
1716 int blk_rq_check_limits(struct request_queue *q, struct request *rq)
1717 {
1718         if (rq->cmd_flags & REQ_DISCARD)
1719                 return 0;
1720
1721         if (blk_rq_sectors(rq) > queue_max_sectors(q) ||
1722             blk_rq_bytes(rq) > queue_max_hw_sectors(q) << 9) {
1723                 printk(KERN_ERR "%s: over max size limit.\n", __func__);
1724                 return -EIO;
1725         }
1726
1727         /*
1728          * queue's settings related to segment counting like q->bounce_pfn
1729          * may differ from that of other stacking queues.
1730          * Recalculate it to check the request correctly on this queue's
1731          * limitation.
1732          */
1733         blk_recalc_rq_segments(rq);
1734         if (rq->nr_phys_segments > queue_max_segments(q)) {
1735                 printk(KERN_ERR "%s: over max segments limit.\n", __func__);
1736                 return -EIO;
1737         }
1738
1739         return 0;
1740 }
1741 EXPORT_SYMBOL_GPL(blk_rq_check_limits);
1742
1743 /**
1744  * blk_insert_cloned_request - Helper for stacking drivers to submit a request
1745  * @q:  the queue to submit the request
1746  * @rq: the request being queued
1747  */
1748 int blk_insert_cloned_request(struct request_queue *q, struct request *rq)
1749 {
1750         unsigned long flags;
1751         int where = ELEVATOR_INSERT_BACK;
1752
1753         if (blk_rq_check_limits(q, rq))
1754                 return -EIO;
1755
1756         if (rq->rq_disk &&
1757             should_fail_request(&rq->rq_disk->part0, blk_rq_bytes(rq)))
1758                 return -EIO;
1759
1760         spin_lock_irqsave(q->queue_lock, flags);
1761
1762         /*
1763          * Submitting request must be dequeued before calling this function
1764          * because it will be linked to another request_queue
1765          */
1766         BUG_ON(blk_queued_rq(rq));
1767
1768         if (rq->cmd_flags & (REQ_FLUSH|REQ_FUA))
1769                 where = ELEVATOR_INSERT_FLUSH;
1770
1771         add_acct_request(q, rq, where);
1772         spin_unlock_irqrestore(q->queue_lock, flags);
1773
1774         return 0;
1775 }
1776 EXPORT_SYMBOL_GPL(blk_insert_cloned_request);
1777
1778 /**
1779  * blk_rq_err_bytes - determine number of bytes till the next failure boundary
1780  * @rq: request to examine
1781  *
1782  * Description:
1783  *     A request could be merge of IOs which require different failure
1784  *     handling.  This function determines the number of bytes which
1785  *     can be failed from the beginning of the request without
1786  *     crossing into area which need to be retried further.
1787  *
1788  * Return:
1789  *     The number of bytes to fail.
1790  *
1791  * Context:
1792  *     queue_lock must be held.
1793  */
1794 unsigned int blk_rq_err_bytes(const struct request *rq)
1795 {
1796         unsigned int ff = rq->cmd_flags & REQ_FAILFAST_MASK;
1797         unsigned int bytes = 0;
1798         struct bio *bio;
1799
1800         if (!(rq->cmd_flags & REQ_MIXED_MERGE))
1801                 return blk_rq_bytes(rq);
1802
1803         /*
1804          * Currently the only 'mixing' which can happen is between
1805          * different fastfail types.  We can safely fail portions
1806          * which have all the failfast bits that the first one has -
1807          * the ones which are at least as eager to fail as the first
1808          * one.
1809          */
1810         for (bio = rq->bio; bio; bio = bio->bi_next) {
1811                 if ((bio->bi_rw & ff) != ff)
1812                         break;
1813                 bytes += bio->bi_size;
1814         }
1815
1816         /* this could lead to infinite loop */
1817         BUG_ON(blk_rq_bytes(rq) && !bytes);
1818         return bytes;
1819 }
1820 EXPORT_SYMBOL_GPL(blk_rq_err_bytes);
1821
1822 static void blk_account_io_completion(struct request *req, unsigned int bytes)
1823 {
1824         if (blk_do_io_stat(req)) {
1825                 const int rw = rq_data_dir(req);
1826                 struct hd_struct *part;
1827                 int cpu;
1828
1829                 cpu = part_stat_lock();
1830                 part = req->part;
1831                 part_stat_add(cpu, part, sectors[rw], bytes >> 9);
1832                 part_stat_unlock();
1833         }
1834 }
1835
1836 static void blk_account_io_done(struct request *req)
1837 {
1838         /*
1839          * Account IO completion.  flush_rq isn't accounted as a
1840          * normal IO on queueing nor completion.  Accounting the
1841          * containing request is enough.
1842          */
1843         if (blk_do_io_stat(req) && !(req->cmd_flags & REQ_FLUSH_SEQ)) {
1844                 unsigned long duration = jiffies - req->start_time;
1845                 const int rw = rq_data_dir(req);
1846                 struct hd_struct *part;
1847                 int cpu;
1848
1849                 cpu = part_stat_lock();
1850                 part = req->part;
1851
1852                 part_stat_inc(cpu, part, ios[rw]);
1853                 part_stat_add(cpu, part, ticks[rw], duration);
1854                 part_round_stats(cpu, part);
1855                 part_dec_in_flight(part, rw);
1856
1857                 hd_struct_put(part);
1858                 part_stat_unlock();
1859         }
1860 }
1861
1862 /**
1863  * blk_peek_request - peek at the top of a request queue
1864  * @q: request queue to peek at
1865  *
1866  * Description:
1867  *     Return the request at the top of @q.  The returned request
1868  *     should be started using blk_start_request() before LLD starts
1869  *     processing it.
1870  *
1871  * Return:
1872  *     Pointer to the request at the top of @q if available.  Null
1873  *     otherwise.
1874  *
1875  * Context:
1876  *     queue_lock must be held.
1877  */
1878 struct request *blk_peek_request(struct request_queue *q)
1879 {
1880         struct request *rq;
1881         int ret;
1882
1883         while ((rq = __elv_next_request(q)) != NULL) {
1884                 if (!(rq->cmd_flags & REQ_STARTED)) {
1885                         /*
1886                          * This is the first time the device driver
1887                          * sees this request (possibly after
1888                          * requeueing).  Notify IO scheduler.
1889                          */
1890                         if (rq->cmd_flags & REQ_SORTED)
1891                                 elv_activate_rq(q, rq);
1892
1893                         /*
1894                          * just mark as started even if we don't start
1895                          * it, a request that has been delayed should
1896                          * not be passed by new incoming requests
1897                          */
1898                         rq->cmd_flags |= REQ_STARTED;
1899                         trace_block_rq_issue(q, rq);
1900                 }
1901
1902                 if (!q->boundary_rq || q->boundary_rq == rq) {
1903                         q->end_sector = rq_end_sector(rq);
1904                         q->boundary_rq = NULL;
1905                 }
1906
1907                 if (rq->cmd_flags & REQ_DONTPREP)
1908                         break;
1909
1910                 if (q->dma_drain_size && blk_rq_bytes(rq)) {
1911                         /*
1912                          * make sure space for the drain appears we
1913                          * know we can do this because max_hw_segments
1914                          * has been adjusted to be one fewer than the
1915                          * device can handle
1916                          */
1917                         rq->nr_phys_segments++;
1918                 }
1919
1920                 if (!q->prep_rq_fn)
1921                         break;
1922
1923                 ret = q->prep_rq_fn(q, rq);
1924                 if (ret == BLKPREP_OK) {
1925                         break;
1926                 } else if (ret == BLKPREP_DEFER) {
1927                         /*
1928                          * the request may have been (partially) prepped.
1929                          * we need to keep this request in the front to
1930                          * avoid resource deadlock.  REQ_STARTED will
1931                          * prevent other fs requests from passing this one.
1932                          */
1933                         if (q->dma_drain_size && blk_rq_bytes(rq) &&
1934                             !(rq->cmd_flags & REQ_DONTPREP)) {
1935                                 /*
1936                                  * remove the space for the drain we added
1937                                  * so that we don't add it again
1938                                  */
1939                                 --rq->nr_phys_segments;
1940                         }
1941
1942                         rq = NULL;
1943                         break;
1944                 } else if (ret == BLKPREP_KILL) {
1945                         rq->cmd_flags |= REQ_QUIET;
1946                         /*
1947                          * Mark this request as started so we don't trigger
1948                          * any debug logic in the end I/O path.
1949                          */
1950                         blk_start_request(rq);
1951                         __blk_end_request_all(rq, -EIO);
1952                 } else {
1953                         printk(KERN_ERR "%s: bad return=%d\n", __func__, ret);
1954                         break;
1955                 }
1956         }
1957
1958         return rq;
1959 }
1960 EXPORT_SYMBOL(blk_peek_request);
1961
1962 void blk_dequeue_request(struct request *rq)
1963 {
1964         struct request_queue *q = rq->q;
1965
1966         BUG_ON(list_empty(&rq->queuelist));
1967         BUG_ON(ELV_ON_HASH(rq));
1968
1969         list_del_init(&rq->queuelist);
1970
1971         /*
1972          * the time frame between a request being removed from the lists
1973          * and to it is freed is accounted as io that is in progress at
1974          * the driver side.
1975          */
1976         if (blk_account_rq(rq)) {
1977                 q->in_flight[rq_is_sync(rq)]++;
1978                 set_io_start_time_ns(rq);
1979         }
1980 }
1981
1982 /**
1983  * blk_start_request - start request processing on the driver
1984  * @req: request to dequeue
1985  *
1986  * Description:
1987  *     Dequeue @req and start timeout timer on it.  This hands off the
1988  *     request to the driver.
1989  *
1990  *     Block internal functions which don't want to start timer should
1991  *     call blk_dequeue_request().
1992  *
1993  * Context:
1994  *     queue_lock must be held.
1995  */
1996 void blk_start_request(struct request *req)
1997 {
1998         blk_dequeue_request(req);
1999
2000         /*
2001          * We are now handing the request to the hardware, initialize
2002          * resid_len to full count and add the timeout handler.
2003          */
2004         req->resid_len = blk_rq_bytes(req);
2005         if (unlikely(blk_bidi_rq(req)))
2006                 req->next_rq->resid_len = blk_rq_bytes(req->next_rq);
2007
2008         blk_add_timer(req);
2009 }
2010 EXPORT_SYMBOL(blk_start_request);
2011
2012 /**
2013  * blk_fetch_request - fetch a request from a request queue
2014  * @q: request queue to fetch a request from
2015  *
2016  * Description:
2017  *     Return the request at the top of @q.  The request is started on
2018  *     return and LLD can start processing it immediately.
2019  *
2020  * Return:
2021  *     Pointer to the request at the top of @q if available.  Null
2022  *     otherwise.
2023  *
2024  * Context:
2025  *     queue_lock must be held.
2026  */
2027 struct request *blk_fetch_request(struct request_queue *q)
2028 {
2029         struct request *rq;
2030
2031         rq = blk_peek_request(q);
2032         if (rq)
2033                 blk_start_request(rq);
2034         return rq;
2035 }
2036 EXPORT_SYMBOL(blk_fetch_request);
2037
2038 /**
2039  * blk_update_request - Special helper function for request stacking drivers
2040  * @req:      the request being processed
2041  * @error:    %0 for success, < %0 for error
2042  * @nr_bytes: number of bytes to complete @req
2043  *
2044  * Description:
2045  *     Ends I/O on a number of bytes attached to @req, but doesn't complete
2046  *     the request structure even if @req doesn't have leftover.
2047  *     If @req has leftover, sets it up for the next range of segments.
2048  *
2049  *     This special helper function is only for request stacking drivers
2050  *     (e.g. request-based dm) so that they can handle partial completion.
2051  *     Actual device drivers should use blk_end_request instead.
2052  *
2053  *     Passing the result of blk_rq_bytes() as @nr_bytes guarantees
2054  *     %false return from this function.
2055  *
2056  * Return:
2057  *     %false - this request doesn't have any more data
2058  *     %true  - this request has more data
2059  **/
2060 bool blk_update_request(struct request *req, int error, unsigned int nr_bytes)
2061 {
2062         int total_bytes, bio_nbytes, next_idx = 0;
2063         struct bio *bio;
2064
2065         if (!req->bio)
2066                 return false;
2067
2068         trace_block_rq_complete(req->q, req);
2069
2070         /*
2071          * For fs requests, rq is just carrier of independent bio's
2072          * and each partial completion should be handled separately.
2073          * Reset per-request error on each partial completion.
2074          *
2075          * TODO: tj: This is too subtle.  It would be better to let
2076          * low level drivers do what they see fit.
2077          */
2078         if (req->cmd_type == REQ_TYPE_FS)
2079                 req->errors = 0;
2080
2081         if (error && req->cmd_type == REQ_TYPE_FS &&
2082             !(req->cmd_flags & REQ_QUIET)) {
2083                 char *error_type;
2084
2085                 switch (error) {
2086                 case -ENOLINK:
2087                         error_type = "recoverable transport";
2088                         break;
2089                 case -EREMOTEIO:
2090                         error_type = "critical target";
2091                         break;
2092                 case -EBADE:
2093                         error_type = "critical nexus";
2094                         break;
2095                 case -EIO:
2096                 default:
2097                         error_type = "I/O";
2098                         break;
2099                 }
2100                 printk(KERN_ERR "end_request: %s error, dev %s, sector %llu\n",
2101                        error_type, req->rq_disk ? req->rq_disk->disk_name : "?",
2102                        (unsigned long long)blk_rq_pos(req));
2103         }
2104
2105         blk_account_io_completion(req, nr_bytes);
2106
2107         total_bytes = bio_nbytes = 0;
2108         while ((bio = req->bio) != NULL) {
2109                 int nbytes;
2110
2111                 if (nr_bytes >= bio->bi_size) {
2112                         req->bio = bio->bi_next;
2113                         nbytes = bio->bi_size;
2114                         req_bio_endio(req, bio, nbytes, error);
2115                         next_idx = 0;
2116                         bio_nbytes = 0;
2117                 } else {
2118                         int idx = bio->bi_idx + next_idx;
2119
2120                         if (unlikely(idx >= bio->bi_vcnt)) {
2121                                 blk_dump_rq_flags(req, "__end_that");
2122                                 printk(KERN_ERR "%s: bio idx %d >= vcnt %d\n",
2123                                        __func__, idx, bio->bi_vcnt);
2124                                 break;
2125                         }
2126
2127                         nbytes = bio_iovec_idx(bio, idx)->bv_len;
2128                         BIO_BUG_ON(nbytes > bio->bi_size);
2129
2130                         /*
2131                          * not a complete bvec done
2132                          */
2133                         if (unlikely(nbytes > nr_bytes)) {
2134                                 bio_nbytes += nr_bytes;
2135                                 total_bytes += nr_bytes;
2136                                 break;
2137                         }
2138
2139                         /*
2140                          * advance to the next vector
2141                          */
2142                         next_idx++;
2143                         bio_nbytes += nbytes;
2144                 }
2145
2146                 total_bytes += nbytes;
2147                 nr_bytes -= nbytes;
2148
2149                 bio = req->bio;
2150                 if (bio) {
2151                         /*
2152                          * end more in this run, or just return 'not-done'
2153                          */
2154                         if (unlikely(nr_bytes <= 0))
2155                                 break;
2156                 }
2157         }
2158
2159         /*
2160          * completely done
2161          */
2162         if (!req->bio) {
2163                 /*
2164                  * Reset counters so that the request stacking driver
2165                  * can find how many bytes remain in the request
2166                  * later.
2167                  */
2168                 req->__data_len = 0;
2169                 return false;
2170         }
2171
2172         /*
2173          * if the request wasn't completed, update state
2174          */
2175         if (bio_nbytes) {
2176                 req_bio_endio(req, bio, bio_nbytes, error);
2177                 bio->bi_idx += next_idx;
2178                 bio_iovec(bio)->bv_offset += nr_bytes;
2179                 bio_iovec(bio)->bv_len -= nr_bytes;
2180         }
2181
2182         req->__data_len -= total_bytes;
2183         req->buffer = bio_data(req->bio);
2184
2185         /* update sector only for requests with clear definition of sector */
2186         if (req->cmd_type == REQ_TYPE_FS || (req->cmd_flags & REQ_DISCARD))
2187                 req->__sector += total_bytes >> 9;
2188
2189         /* mixed attributes always follow the first bio */
2190         if (req->cmd_flags & REQ_MIXED_MERGE) {
2191                 req->cmd_flags &= ~REQ_FAILFAST_MASK;
2192                 req->cmd_flags |= req->bio->bi_rw & REQ_FAILFAST_MASK;
2193         }
2194
2195         /*
2196          * If total number of sectors is less than the first segment
2197          * size, something has gone terribly wrong.
2198          */
2199         if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {
2200                 blk_dump_rq_flags(req, "request botched");
2201                 req->__data_len = blk_rq_cur_bytes(req);
2202         }
2203
2204         /* recalculate the number of segments */
2205         blk_recalc_rq_segments(req);
2206
2207         return true;
2208 }
2209 EXPORT_SYMBOL_GPL(blk_update_request);
2210
2211 static bool blk_update_bidi_request(struct request *rq, int error,
2212                                     unsigned int nr_bytes,
2213                                     unsigned int bidi_bytes)
2214 {
2215         if (blk_update_request(rq, error, nr_bytes))
2216                 return true;
2217
2218         /* Bidi request must be completed as a whole */
2219         if (unlikely(blk_bidi_rq(rq)) &&
2220             blk_update_request(rq->next_rq, error, bidi_bytes))
2221                 return true;
2222
2223         if (blk_queue_add_random(rq->q))
2224                 add_disk_randomness(rq->rq_disk);
2225
2226         return false;
2227 }
2228
2229 /**
2230  * blk_unprep_request - unprepare a request
2231  * @req:        the request
2232  *
2233  * This function makes a request ready for complete resubmission (or
2234  * completion).  It happens only after all error handling is complete,
2235  * so represents the appropriate moment to deallocate any resources
2236  * that were allocated to the request in the prep_rq_fn.  The queue
2237  * lock is held when calling this.
2238  */
2239 void blk_unprep_request(struct request *req)
2240 {
2241         struct request_queue *q = req->q;
2242
2243         req->cmd_flags &= ~REQ_DONTPREP;
2244         if (q->unprep_rq_fn)
2245                 q->unprep_rq_fn(q, req);
2246 }
2247 EXPORT_SYMBOL_GPL(blk_unprep_request);
2248
2249 /*
2250  * queue lock must be held
2251  */
2252 static void blk_finish_request(struct request *req, int error)
2253 {
2254         if (blk_rq_tagged(req))
2255                 blk_queue_end_tag(req->q, req);
2256
2257         BUG_ON(blk_queued_rq(req));
2258
2259         if (unlikely(laptop_mode) && req->cmd_type == REQ_TYPE_FS)
2260                 laptop_io_completion(&req->q->backing_dev_info);
2261
2262         blk_delete_timer(req);
2263
2264         if (req->cmd_flags & REQ_DONTPREP)
2265                 blk_unprep_request(req);
2266
2267
2268         blk_account_io_done(req);
2269
2270         if (req->end_io)
2271                 req->end_io(req, error);
2272         else {
2273                 if (blk_bidi_rq(req))
2274                         __blk_put_request(req->next_rq->q, req->next_rq);
2275
2276                 __blk_put_request(req->q, req);
2277         }
2278 }
2279
2280 /**
2281  * blk_end_bidi_request - Complete a bidi request
2282  * @rq:         the request to complete
2283  * @error:      %0 for success, < %0 for error
2284  * @nr_bytes:   number of bytes to complete @rq
2285  * @bidi_bytes: number of bytes to complete @rq->next_rq
2286  *
2287  * Description:
2288  *     Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
2289  *     Drivers that supports bidi can safely call this member for any
2290  *     type of request, bidi or uni.  In the later case @bidi_bytes is
2291  *     just ignored.
2292  *
2293  * Return:
2294  *     %false - we are done with this request
2295  *     %true  - still buffers pending for this request
2296  **/
2297 static bool blk_end_bidi_request(struct request *rq, int error,
2298                                  unsigned int nr_bytes, unsigned int bidi_bytes)
2299 {
2300         struct request_queue *q = rq->q;
2301         unsigned long flags;
2302
2303         if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2304                 return true;
2305
2306         spin_lock_irqsave(q->queue_lock, flags);
2307         blk_finish_request(rq, error);
2308         spin_unlock_irqrestore(q->queue_lock, flags);
2309
2310         return false;
2311 }
2312
2313 /**
2314  * __blk_end_bidi_request - Complete a bidi request with queue lock held
2315  * @rq:         the request to complete
2316  * @error:      %0 for success, < %0 for error
2317  * @nr_bytes:   number of bytes to complete @rq
2318  * @bidi_bytes: number of bytes to complete @rq->next_rq
2319  *
2320  * Description:
2321  *     Identical to blk_end_bidi_request() except that queue lock is
2322  *     assumed to be locked on entry and remains so on return.
2323  *
2324  * Return:
2325  *     %false - we are done with this request
2326  *     %true  - still buffers pending for this request
2327  **/
2328 bool __blk_end_bidi_request(struct request *rq, int error,
2329                                    unsigned int nr_bytes, unsigned int bidi_bytes)
2330 {
2331         if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2332                 return true;
2333
2334         blk_finish_request(rq, error);
2335
2336         return false;
2337 }
2338
2339 /**
2340  * blk_end_request - Helper function for drivers to complete the request.
2341  * @rq:       the request being processed
2342  * @error:    %0 for success, < %0 for error
2343  * @nr_bytes: number of bytes to complete
2344  *
2345  * Description:
2346  *     Ends I/O on a number of bytes attached to @rq.
2347  *     If @rq has leftover, sets it up for the next range of segments.
2348  *
2349  * Return:
2350  *     %false - we are done with this request
2351  *     %true  - still buffers pending for this request
2352  **/
2353 bool blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
2354 {
2355         return blk_end_bidi_request(rq, error, nr_bytes, 0);
2356 }
2357 EXPORT_SYMBOL(blk_end_request);
2358
2359 /**
2360  * blk_end_request_all - Helper function for drives to finish the request.
2361  * @rq: the request to finish
2362  * @error: %0 for success, < %0 for error
2363  *
2364  * Description:
2365  *     Completely finish @rq.
2366  */
2367 void blk_end_request_all(struct request *rq, int error)
2368 {
2369         bool pending;
2370         unsigned int bidi_bytes = 0;
2371
2372         if (unlikely(blk_bidi_rq(rq)))
2373                 bidi_bytes = blk_rq_bytes(rq->next_rq);
2374
2375         pending = blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2376         BUG_ON(pending);
2377 }
2378 EXPORT_SYMBOL(blk_end_request_all);
2379
2380 /**
2381  * blk_end_request_cur - Helper function to finish the current request chunk.
2382  * @rq: the request to finish the current chunk for
2383  * @error: %0 for success, < %0 for error
2384  *
2385  * Description:
2386  *     Complete the current consecutively mapped chunk from @rq.
2387  *
2388  * Return:
2389  *     %false - we are done with this request
2390  *     %true  - still buffers pending for this request
2391  */
2392 bool blk_end_request_cur(struct request *rq, int error)
2393 {
2394         return blk_end_request(rq, error, blk_rq_cur_bytes(rq));
2395 }
2396 EXPORT_SYMBOL(blk_end_request_cur);
2397
2398 /**
2399  * blk_end_request_err - Finish a request till the next failure boundary.
2400  * @rq: the request to finish till the next failure boundary for
2401  * @error: must be negative errno
2402  *
2403  * Description:
2404  *     Complete @rq till the next failure boundary.
2405  *
2406  * Return:
2407  *     %false - we are done with this request
2408  *     %true  - still buffers pending for this request
2409  */
2410 bool blk_end_request_err(struct request *rq, int error)
2411 {
2412         WARN_ON(error >= 0);
2413         return blk_end_request(rq, error, blk_rq_err_bytes(rq));
2414 }
2415 EXPORT_SYMBOL_GPL(blk_end_request_err);
2416
2417 /**
2418  * __blk_end_request - Helper function for drivers to complete the request.
2419  * @rq:       the request being processed
2420  * @error:    %0 for success, < %0 for error
2421  * @nr_bytes: number of bytes to complete
2422  *
2423  * Description:
2424  *     Must be called with queue lock held unlike blk_end_request().
2425  *
2426  * Return:
2427  *     %false - we are done with this request
2428  *     %true  - still buffers pending for this request
2429  **/
2430 bool __blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
2431 {
2432         return __blk_end_bidi_request(rq, error, nr_bytes, 0);
2433 }
2434 EXPORT_SYMBOL(__blk_end_request);
2435
2436 /**
2437  * __blk_end_request_all - Helper function for drives to finish the request.
2438  * @rq: the request to finish
2439  * @error: %0 for success, < %0 for error
2440  *
2441  * Description:
2442  *     Completely finish @rq.  Must be called with queue lock held.
2443  */
2444 void __blk_end_request_all(struct request *rq, int error)
2445 {
2446         bool pending;
2447         unsigned int bidi_bytes = 0;
2448
2449         if (unlikely(blk_bidi_rq(rq)))
2450                 bidi_bytes = blk_rq_bytes(rq->next_rq);
2451
2452         pending = __blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2453         BUG_ON(pending);
2454 }
2455 EXPORT_SYMBOL(__blk_end_request_all);
2456
2457 /**
2458  * __blk_end_request_cur - Helper function to finish the current request chunk.
2459  * @rq: the request to finish the current chunk for
2460  * @error: %0 for success, < %0 for error
2461  *
2462  * Description:
2463  *     Complete the current consecutively mapped chunk from @rq.  Must
2464  *     be called with queue lock held.
2465  *
2466  * Return:
2467  *     %false - we are done with this request
2468  *     %true  - still buffers pending for this request
2469  */
2470 bool __blk_end_request_cur(struct request *rq, int error)
2471 {
2472         return __blk_end_request(rq, error, blk_rq_cur_bytes(rq));
2473 }
2474 EXPORT_SYMBOL(__blk_end_request_cur);
2475
2476 /**
2477  * __blk_end_request_err - Finish a request till the next failure boundary.
2478  * @rq: the request to finish till the next failure boundary for
2479  * @error: must be negative errno
2480  *
2481  * Description:
2482  *     Complete @rq till the next failure boundary.  Must be called
2483  *     with queue lock held.
2484  *
2485  * Return:
2486  *     %false - we are done with this request
2487  *     %true  - still buffers pending for this request
2488  */
2489 bool __blk_end_request_err(struct request *rq, int error)
2490 {
2491         WARN_ON(error >= 0);
2492         return __blk_end_request(rq, error, blk_rq_err_bytes(rq));
2493 }
2494 EXPORT_SYMBOL_GPL(__blk_end_request_err);
2495
2496 void blk_rq_bio_prep(struct request_queue *q, struct request *rq,
2497                      struct bio *bio)
2498 {
2499         /* Bit 0 (R/W) is identical in rq->cmd_flags and bio->bi_rw */
2500         rq->cmd_flags |= bio->bi_rw & REQ_WRITE;
2501
2502         if (bio_has_data(bio)) {
2503                 rq->nr_phys_segments = bio_phys_segments(q, bio);
2504                 rq->buffer = bio_data(bio);
2505         }
2506         rq->__data_len = bio->bi_size;
2507         rq->bio = rq->biotail = bio;
2508
2509         if (bio->bi_bdev)
2510                 rq->rq_disk = bio->bi_bdev->bd_disk;
2511 }
2512
2513 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE
2514 /**
2515  * rq_flush_dcache_pages - Helper function to flush all pages in a request
2516  * @rq: the request to be flushed
2517  *
2518  * Description:
2519  *     Flush all pages in @rq.
2520  */
2521 void rq_flush_dcache_pages(struct request *rq)
2522 {
2523         struct req_iterator iter;
2524         struct bio_vec *bvec;
2525
2526         rq_for_each_segment(bvec, rq, iter)
2527                 flush_dcache_page(bvec->bv_page);
2528 }
2529 EXPORT_SYMBOL_GPL(rq_flush_dcache_pages);
2530 #endif
2531
2532 /**
2533  * blk_lld_busy - Check if underlying low-level drivers of a device are busy
2534  * @q : the queue of the device being checked
2535  *
2536  * Description:
2537  *    Check if underlying low-level drivers of a device are busy.
2538  *    If the drivers want to export their busy state, they must set own
2539  *    exporting function using blk_queue_lld_busy() first.
2540  *
2541  *    Basically, this function is used only by request stacking drivers
2542  *    to stop dispatching requests to underlying devices when underlying
2543  *    devices are busy.  This behavior helps more I/O merging on the queue
2544  *    of the request stacking driver and prevents I/O throughput regression
2545  *    on burst I/O load.
2546  *
2547  * Return:
2548  *    0 - Not busy (The request stacking driver should dispatch request)
2549  *    1 - Busy (The request stacking driver should stop dispatching request)
2550  */
2551 int blk_lld_busy(struct request_queue *q)
2552 {
2553         if (q->lld_busy_fn)
2554                 return q->lld_busy_fn(q);
2555
2556         return 0;
2557 }
2558 EXPORT_SYMBOL_GPL(blk_lld_busy);
2559
2560 /**
2561  * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
2562  * @rq: the clone request to be cleaned up
2563  *
2564  * Description:
2565  *     Free all bios in @rq for a cloned request.
2566  */
2567 void blk_rq_unprep_clone(struct request *rq)
2568 {
2569         struct bio *bio;
2570
2571         while ((bio = rq->bio) != NULL) {
2572                 rq->bio = bio->bi_next;
2573
2574                 bio_put(bio);
2575         }
2576 }
2577 EXPORT_SYMBOL_GPL(blk_rq_unprep_clone);
2578
2579 /*
2580  * Copy attributes of the original request to the clone request.
2581  * The actual data parts (e.g. ->cmd, ->buffer, ->sense) are not copied.
2582  */
2583 static void __blk_rq_prep_clone(struct request *dst, struct request *src)
2584 {
2585         dst->cpu = src->cpu;
2586         dst->cmd_flags = (src->cmd_flags & REQ_CLONE_MASK) | REQ_NOMERGE;
2587         dst->cmd_type = src->cmd_type;
2588         dst->__sector = blk_rq_pos(src);
2589         dst->__data_len = blk_rq_bytes(src);
2590         dst->nr_phys_segments = src->nr_phys_segments;
2591         dst->ioprio = src->ioprio;
2592         dst->extra_len = src->extra_len;
2593 }
2594
2595 /**
2596  * blk_rq_prep_clone - Helper function to setup clone request
2597  * @rq: the request to be setup
2598  * @rq_src: original request to be cloned
2599  * @bs: bio_set that bios for clone are allocated from
2600  * @gfp_mask: memory allocation mask for bio
2601  * @bio_ctr: setup function to be called for each clone bio.
2602  *           Returns %0 for success, non %0 for failure.
2603  * @data: private data to be passed to @bio_ctr
2604  *
2605  * Description:
2606  *     Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
2607  *     The actual data parts of @rq_src (e.g. ->cmd, ->buffer, ->sense)
2608  *     are not copied, and copying such parts is the caller's responsibility.
2609  *     Also, pages which the original bios are pointing to are not copied
2610  *     and the cloned bios just point same pages.
2611  *     So cloned bios must be completed before original bios, which means
2612  *     the caller must complete @rq before @rq_src.
2613  */
2614 int blk_rq_prep_clone(struct request *rq, struct request *rq_src,
2615                       struct bio_set *bs, gfp_t gfp_mask,
2616                       int (*bio_ctr)(struct bio *, struct bio *, void *),
2617                       void *data)
2618 {
2619         struct bio *bio, *bio_src;
2620
2621         if (!bs)
2622                 bs = fs_bio_set;
2623
2624         blk_rq_init(NULL, rq);
2625
2626         __rq_for_each_bio(bio_src, rq_src) {
2627                 bio = bio_alloc_bioset(gfp_mask, bio_src->bi_max_vecs, bs);
2628                 if (!bio)
2629                         goto free_and_out;
2630
2631                 __bio_clone(bio, bio_src);
2632
2633                 if (bio_integrity(bio_src) &&
2634                     bio_integrity_clone(bio, bio_src, gfp_mask, bs))
2635                         goto free_and_out;
2636
2637                 if (bio_ctr && bio_ctr(bio, bio_src, data))
2638                         goto free_and_out;
2639
2640                 if (rq->bio) {
2641                         rq->biotail->bi_next = bio;
2642                         rq->biotail = bio;
2643                 } else
2644                         rq->bio = rq->biotail = bio;
2645         }
2646
2647         __blk_rq_prep_clone(rq, rq_src);
2648
2649         return 0;
2650
2651 free_and_out:
2652         if (bio)
2653                 bio_free(bio, bs);
2654         blk_rq_unprep_clone(rq);
2655
2656         return -ENOMEM;
2657 }
2658 EXPORT_SYMBOL_GPL(blk_rq_prep_clone);
2659
2660 int kblockd_schedule_work(struct request_queue *q, struct work_struct *work)
2661 {
2662         return queue_work(kblockd_workqueue, work);
2663 }
2664 EXPORT_SYMBOL(kblockd_schedule_work);
2665
2666 int kblockd_schedule_delayed_work(struct request_queue *q,
2667                         struct delayed_work *dwork, unsigned long delay)
2668 {
2669         return queue_delayed_work(kblockd_workqueue, dwork, delay);
2670 }
2671 EXPORT_SYMBOL(kblockd_schedule_delayed_work);
2672
2673 #define PLUG_MAGIC      0x91827364
2674
2675 /**
2676  * blk_start_plug - initialize blk_plug and track it inside the task_struct
2677  * @plug:       The &struct blk_plug that needs to be initialized
2678  *
2679  * Description:
2680  *   Tracking blk_plug inside the task_struct will help with auto-flushing the
2681  *   pending I/O should the task end up blocking between blk_start_plug() and
2682  *   blk_finish_plug(). This is important from a performance perspective, but
2683  *   also ensures that we don't deadlock. For instance, if the task is blocking
2684  *   for a memory allocation, memory reclaim could end up wanting to free a
2685  *   page belonging to that request that is currently residing in our private
2686  *   plug. By flushing the pending I/O when the process goes to sleep, we avoid
2687  *   this kind of deadlock.
2688  */
2689 void blk_start_plug(struct blk_plug *plug)
2690 {
2691         struct task_struct *tsk = current;
2692
2693         plug->magic = PLUG_MAGIC;
2694         INIT_LIST_HEAD(&plug->list);
2695         INIT_LIST_HEAD(&plug->cb_list);
2696         plug->should_sort = 0;
2697
2698         /*
2699          * If this is a nested plug, don't actually assign it. It will be
2700          * flushed on its own.
2701          */
2702         if (!tsk->plug) {
2703                 /*
2704                  * Store ordering should not be needed here, since a potential
2705                  * preempt will imply a full memory barrier
2706                  */
2707                 tsk->plug = plug;
2708         }
2709 }
2710 EXPORT_SYMBOL(blk_start_plug);
2711
2712 static int plug_rq_cmp(void *priv, struct list_head *a, struct list_head *b)
2713 {
2714         struct request *rqa = container_of(a, struct request, queuelist);
2715         struct request *rqb = container_of(b, struct request, queuelist);
2716
2717         return !(rqa->q <= rqb->q);
2718 }
2719
2720 /*
2721  * If 'from_schedule' is true, then postpone the dispatch of requests
2722  * until a safe kblockd context. We due this to avoid accidental big
2723  * additional stack usage in driver dispatch, in places where the originally
2724  * plugger did not intend it.
2725  */
2726 static void queue_unplugged(struct request_queue *q, unsigned int depth,
2727                             bool from_schedule)
2728         __releases(q->queue_lock)
2729 {
2730         trace_block_unplug(q, depth, !from_schedule);
2731
2732         /*
2733          * If we are punting this to kblockd, then we can safely drop
2734          * the queue_lock before waking kblockd (which needs to take
2735          * this lock).
2736          */
2737         if (from_schedule) {
2738                 spin_unlock(q->queue_lock);
2739                 blk_run_queue_async(q);
2740         } else {
2741                 __blk_run_queue(q);
2742                 spin_unlock(q->queue_lock);
2743         }
2744
2745 }
2746
2747 static void flush_plug_callbacks(struct blk_plug *plug)
2748 {
2749         LIST_HEAD(callbacks);
2750
2751         if (list_empty(&plug->cb_list))
2752                 return;
2753
2754         list_splice_init(&plug->cb_list, &callbacks);
2755
2756         while (!list_empty(&callbacks)) {
2757                 struct blk_plug_cb *cb = list_first_entry(&callbacks,
2758                                                           struct blk_plug_cb,
2759                                                           list);
2760                 list_del(&cb->list);
2761                 cb->callback(cb);
2762         }
2763 }
2764
2765 void blk_flush_plug_list(struct blk_plug *plug, bool from_schedule)
2766 {
2767         struct request_queue *q;
2768         unsigned long flags;
2769         struct request *rq;
2770         LIST_HEAD(list);
2771         unsigned int depth;
2772
2773         BUG_ON(plug->magic != PLUG_MAGIC);
2774
2775         flush_plug_callbacks(plug);
2776         if (list_empty(&plug->list))
2777                 return;
2778
2779         list_splice_init(&plug->list, &list);
2780
2781         if (plug->should_sort) {
2782                 list_sort(NULL, &list, plug_rq_cmp);
2783                 plug->should_sort = 0;
2784         }
2785
2786         q = NULL;
2787         depth = 0;
2788
2789         /*
2790          * Save and disable interrupts here, to avoid doing it for every
2791          * queue lock we have to take.
2792          */
2793         local_irq_save(flags);
2794         while (!list_empty(&list)) {
2795                 rq = list_entry_rq(list.next);
2796                 list_del_init(&rq->queuelist);
2797                 BUG_ON(!rq->q);
2798                 if (rq->q != q) {
2799                         /*
2800                          * This drops the queue lock
2801                          */
2802                         if (q)
2803                                 queue_unplugged(q, depth, from_schedule);
2804                         q = rq->q;
2805                         depth = 0;
2806                         spin_lock(q->queue_lock);
2807                 }
2808                 /*
2809                  * rq is already accounted, so use raw insert
2810                  */
2811                 if (rq->cmd_flags & (REQ_FLUSH | REQ_FUA))
2812                         __elv_add_request(q, rq, ELEVATOR_INSERT_FLUSH);
2813                 else
2814                         __elv_add_request(q, rq, ELEVATOR_INSERT_SORT_MERGE);
2815
2816                 depth++;
2817         }
2818
2819         /*
2820          * This drops the queue lock
2821          */
2822         if (q)
2823                 queue_unplugged(q, depth, from_schedule);
2824
2825         local_irq_restore(flags);
2826 }
2827
2828 void blk_finish_plug(struct blk_plug *plug)
2829 {
2830         blk_flush_plug_list(plug, false);
2831
2832         if (plug == current->plug)
2833                 current->plug = NULL;
2834 }
2835 EXPORT_SYMBOL(blk_finish_plug);
2836
2837 int __init blk_dev_init(void)
2838 {
2839         BUILD_BUG_ON(__REQ_NR_BITS > 8 *
2840                         sizeof(((struct request *)0)->cmd_flags));
2841
2842         /* used for unplugging and affects IO latency/throughput - HIGHPRI */
2843         kblockd_workqueue = alloc_workqueue("kblockd",
2844                                             WQ_MEM_RECLAIM | WQ_HIGHPRI, 0);
2845         if (!kblockd_workqueue)
2846                 panic("Failed to create kblockd\n");
2847
2848         request_cachep = kmem_cache_create("blkdev_requests",
2849                         sizeof(struct request), 0, SLAB_PANIC, NULL);
2850
2851         blk_requestq_cachep = kmem_cache_create("blkdev_queue",
2852                         sizeof(struct request_queue), 0, SLAB_PANIC, NULL);
2853
2854         return 0;
2855 }