~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/block/blk-core.c

Version: ~ [ linux-5.4-rc7 ] ~ [ linux-5.3.11 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.84 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.154 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.201 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.201 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.77 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-3.9.11 ] ~ [ linux-3.8.13 ] ~ [ linux-3.7.10 ] ~ [ linux-3.6.11 ] ~ [ linux-3.5.7 ] ~ [ linux-3.4.113 ] ~ [ linux-3.3.8 ] ~ [ linux-3.2.102 ] ~ [ linux-3.1.10 ] ~ [ linux-3.0.101 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

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

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp