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