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