gro: Allow tunnel stacking in the case of FOU/GUE
[linux/fpc-iii.git] / block / blk-core.c
blobbbbf36e6066b452c53619d85a828c1b802cfac3f
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 */
12 * This handles all read/write requests to block devices
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/blk-mq.h>
20 #include <linux/highmem.h>
21 #include <linux/mm.h>
22 #include <linux/kernel_stat.h>
23 #include <linux/string.h>
24 #include <linux/init.h>
25 #include <linux/completion.h>
26 #include <linux/slab.h>
27 #include <linux/swap.h>
28 #include <linux/writeback.h>
29 #include <linux/task_io_accounting_ops.h>
30 #include <linux/fault-inject.h>
31 #include <linux/list_sort.h>
32 #include <linux/delay.h>
33 #include <linux/ratelimit.h>
34 #include <linux/pm_runtime.h>
36 #define CREATE_TRACE_POINTS
37 #include <trace/events/block.h>
39 #include "blk.h"
40 #include "blk-cgroup.h"
41 #include "blk-mq.h"
43 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_remap);
44 EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_remap);
45 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_complete);
46 EXPORT_TRACEPOINT_SYMBOL_GPL(block_split);
47 EXPORT_TRACEPOINT_SYMBOL_GPL(block_unplug);
49 DEFINE_IDA(blk_queue_ida);
52 * For the allocated request tables
54 struct kmem_cache *request_cachep = NULL;
57 * For queue allocation
59 struct kmem_cache *blk_requestq_cachep;
62 * Controlling structure to kblockd
64 static struct workqueue_struct *kblockd_workqueue;
66 void blk_queue_congestion_threshold(struct request_queue *q)
68 int nr;
70 nr = q->nr_requests - (q->nr_requests / 8) + 1;
71 if (nr > q->nr_requests)
72 nr = q->nr_requests;
73 q->nr_congestion_on = nr;
75 nr = q->nr_requests - (q->nr_requests / 8) - (q->nr_requests / 16) - 1;
76 if (nr < 1)
77 nr = 1;
78 q->nr_congestion_off = nr;
81 /**
82 * blk_get_backing_dev_info - get the address of a queue's backing_dev_info
83 * @bdev: device
85 * Locates the passed device's request queue and returns the address of its
86 * backing_dev_info. This function can only be called if @bdev is opened
87 * and the return value is never NULL.
89 struct backing_dev_info *blk_get_backing_dev_info(struct block_device *bdev)
91 struct request_queue *q = bdev_get_queue(bdev);
93 return &q->backing_dev_info;
95 EXPORT_SYMBOL(blk_get_backing_dev_info);
97 void blk_rq_init(struct request_queue *q, struct request *rq)
99 memset(rq, 0, sizeof(*rq));
101 INIT_LIST_HEAD(&rq->queuelist);
102 INIT_LIST_HEAD(&rq->timeout_list);
103 rq->cpu = -1;
104 rq->q = q;
105 rq->__sector = (sector_t) -1;
106 INIT_HLIST_NODE(&rq->hash);
107 RB_CLEAR_NODE(&rq->rb_node);
108 rq->cmd = rq->__cmd;
109 rq->cmd_len = BLK_MAX_CDB;
110 rq->tag = -1;
111 rq->start_time = jiffies;
112 set_start_time_ns(rq);
113 rq->part = NULL;
115 EXPORT_SYMBOL(blk_rq_init);
117 static void req_bio_endio(struct request *rq, struct bio *bio,
118 unsigned int nbytes, int error)
120 if (error)
121 clear_bit(BIO_UPTODATE, &bio->bi_flags);
122 else if (!test_bit(BIO_UPTODATE, &bio->bi_flags))
123 error = -EIO;
125 if (unlikely(rq->cmd_flags & REQ_QUIET))
126 set_bit(BIO_QUIET, &bio->bi_flags);
128 bio_advance(bio, nbytes);
130 /* don't actually finish bio if it's part of flush sequence */
131 if (bio->bi_iter.bi_size == 0 && !(rq->cmd_flags & REQ_FLUSH_SEQ))
132 bio_endio(bio, error);
135 void blk_dump_rq_flags(struct request *rq, char *msg)
137 int bit;
139 printk(KERN_INFO "%s: dev %s: type=%x, flags=%llx\n", msg,
140 rq->rq_disk ? rq->rq_disk->disk_name : "?", rq->cmd_type,
141 (unsigned long long) rq->cmd_flags);
143 printk(KERN_INFO " sector %llu, nr/cnr %u/%u\n",
144 (unsigned long long)blk_rq_pos(rq),
145 blk_rq_sectors(rq), blk_rq_cur_sectors(rq));
146 printk(KERN_INFO " bio %p, biotail %p, len %u\n",
147 rq->bio, rq->biotail, blk_rq_bytes(rq));
149 if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
150 printk(KERN_INFO " cdb: ");
151 for (bit = 0; bit < BLK_MAX_CDB; bit++)
152 printk("%02x ", rq->cmd[bit]);
153 printk("\n");
156 EXPORT_SYMBOL(blk_dump_rq_flags);
158 static void blk_delay_work(struct work_struct *work)
160 struct request_queue *q;
162 q = container_of(work, struct request_queue, delay_work.work);
163 spin_lock_irq(q->queue_lock);
164 __blk_run_queue(q);
165 spin_unlock_irq(q->queue_lock);
169 * blk_delay_queue - restart queueing after defined interval
170 * @q: The &struct request_queue in question
171 * @msecs: Delay in msecs
173 * Description:
174 * Sometimes queueing needs to be postponed for a little while, to allow
175 * resources to come back. This function will make sure that queueing is
176 * restarted around the specified time. Queue lock must be held.
178 void blk_delay_queue(struct request_queue *q, unsigned long msecs)
180 if (likely(!blk_queue_dead(q)))
181 queue_delayed_work(kblockd_workqueue, &q->delay_work,
182 msecs_to_jiffies(msecs));
184 EXPORT_SYMBOL(blk_delay_queue);
187 * blk_start_queue - restart a previously stopped queue
188 * @q: The &struct request_queue in question
190 * Description:
191 * blk_start_queue() will clear the stop flag on the queue, and call
192 * the request_fn for the queue if it was in a stopped state when
193 * entered. Also see blk_stop_queue(). Queue lock must be held.
195 void blk_start_queue(struct request_queue *q)
197 WARN_ON(!irqs_disabled());
199 queue_flag_clear(QUEUE_FLAG_STOPPED, q);
200 __blk_run_queue(q);
202 EXPORT_SYMBOL(blk_start_queue);
205 * blk_stop_queue - stop a queue
206 * @q: The &struct request_queue in question
208 * Description:
209 * The Linux block layer assumes that a block driver will consume all
210 * entries on the request queue when the request_fn strategy is called.
211 * Often this will not happen, because of hardware limitations (queue
212 * depth settings). If a device driver gets a 'queue full' response,
213 * or if it simply chooses not to queue more I/O at one point, it can
214 * call this function to prevent the request_fn from being called until
215 * the driver has signalled it's ready to go again. This happens by calling
216 * blk_start_queue() to restart queue operations. Queue lock must be held.
218 void blk_stop_queue(struct request_queue *q)
220 cancel_delayed_work(&q->delay_work);
221 queue_flag_set(QUEUE_FLAG_STOPPED, q);
223 EXPORT_SYMBOL(blk_stop_queue);
226 * blk_sync_queue - cancel any pending callbacks on a queue
227 * @q: the queue
229 * Description:
230 * The block layer may perform asynchronous callback activity
231 * on a queue, such as calling the unplug function after a timeout.
232 * A block device may call blk_sync_queue to ensure that any
233 * such activity is cancelled, thus allowing it to release resources
234 * that the callbacks might use. The caller must already have made sure
235 * that its ->make_request_fn will not re-add plugging prior to calling
236 * this function.
238 * This function does not cancel any asynchronous activity arising
239 * out of elevator or throttling code. That would require elevator_exit()
240 * and blkcg_exit_queue() to be called with queue lock initialized.
243 void blk_sync_queue(struct request_queue *q)
245 del_timer_sync(&q->timeout);
247 if (q->mq_ops) {
248 struct blk_mq_hw_ctx *hctx;
249 int i;
251 queue_for_each_hw_ctx(q, hctx, i) {
252 cancel_delayed_work_sync(&hctx->run_work);
253 cancel_delayed_work_sync(&hctx->delay_work);
255 } else {
256 cancel_delayed_work_sync(&q->delay_work);
259 EXPORT_SYMBOL(blk_sync_queue);
262 * __blk_run_queue_uncond - run a queue whether or not it has been stopped
263 * @q: The queue to run
265 * Description:
266 * Invoke request handling on a queue if there are any pending requests.
267 * May be used to restart request handling after a request has completed.
268 * This variant runs the queue whether or not the queue has been
269 * stopped. Must be called with the queue lock held and interrupts
270 * disabled. See also @blk_run_queue.
272 inline void __blk_run_queue_uncond(struct request_queue *q)
274 if (unlikely(blk_queue_dead(q)))
275 return;
278 * Some request_fn implementations, e.g. scsi_request_fn(), unlock
279 * the queue lock internally. As a result multiple threads may be
280 * running such a request function concurrently. Keep track of the
281 * number of active request_fn invocations such that blk_drain_queue()
282 * can wait until all these request_fn calls have finished.
284 q->request_fn_active++;
285 q->request_fn(q);
286 q->request_fn_active--;
290 * __blk_run_queue - run a single device queue
291 * @q: The queue to run
293 * Description:
294 * See @blk_run_queue. This variant must be called with the queue lock
295 * held and interrupts disabled.
297 void __blk_run_queue(struct request_queue *q)
299 if (unlikely(blk_queue_stopped(q)))
300 return;
302 __blk_run_queue_uncond(q);
304 EXPORT_SYMBOL(__blk_run_queue);
307 * blk_run_queue_async - run a single device queue in workqueue context
308 * @q: The queue to run
310 * Description:
311 * Tells kblockd to perform the equivalent of @blk_run_queue on behalf
312 * of us. The caller must hold the queue lock.
314 void blk_run_queue_async(struct request_queue *q)
316 if (likely(!blk_queue_stopped(q) && !blk_queue_dead(q)))
317 mod_delayed_work(kblockd_workqueue, &q->delay_work, 0);
319 EXPORT_SYMBOL(blk_run_queue_async);
322 * blk_run_queue - run a single device queue
323 * @q: The queue to run
325 * Description:
326 * Invoke request handling on this queue, if it has pending work to do.
327 * May be used to restart queueing when a request has completed.
329 void blk_run_queue(struct request_queue *q)
331 unsigned long flags;
333 spin_lock_irqsave(q->queue_lock, flags);
334 __blk_run_queue(q);
335 spin_unlock_irqrestore(q->queue_lock, flags);
337 EXPORT_SYMBOL(blk_run_queue);
339 void blk_put_queue(struct request_queue *q)
341 kobject_put(&q->kobj);
343 EXPORT_SYMBOL(blk_put_queue);
346 * __blk_drain_queue - drain requests from request_queue
347 * @q: queue to drain
348 * @drain_all: whether to drain all requests or only the ones w/ ELVPRIV
350 * Drain requests from @q. If @drain_all is set, all requests are drained.
351 * If not, only ELVPRIV requests are drained. The caller is responsible
352 * for ensuring that no new requests which need to be drained are queued.
354 static void __blk_drain_queue(struct request_queue *q, bool drain_all)
355 __releases(q->queue_lock)
356 __acquires(q->queue_lock)
358 int i;
360 lockdep_assert_held(q->queue_lock);
362 while (true) {
363 bool drain = false;
366 * The caller might be trying to drain @q before its
367 * elevator is initialized.
369 if (q->elevator)
370 elv_drain_elevator(q);
372 blkcg_drain_queue(q);
375 * This function might be called on a queue which failed
376 * driver init after queue creation or is not yet fully
377 * active yet. Some drivers (e.g. fd and loop) get unhappy
378 * in such cases. Kick queue iff dispatch queue has
379 * something on it and @q has request_fn set.
381 if (!list_empty(&q->queue_head) && q->request_fn)
382 __blk_run_queue(q);
384 drain |= q->nr_rqs_elvpriv;
385 drain |= q->request_fn_active;
388 * Unfortunately, requests are queued at and tracked from
389 * multiple places and there's no single counter which can
390 * be drained. Check all the queues and counters.
392 if (drain_all) {
393 struct blk_flush_queue *fq = blk_get_flush_queue(q, NULL);
394 drain |= !list_empty(&q->queue_head);
395 for (i = 0; i < 2; i++) {
396 drain |= q->nr_rqs[i];
397 drain |= q->in_flight[i];
398 if (fq)
399 drain |= !list_empty(&fq->flush_queue[i]);
403 if (!drain)
404 break;
406 spin_unlock_irq(q->queue_lock);
408 msleep(10);
410 spin_lock_irq(q->queue_lock);
414 * With queue marked dead, any woken up waiter will fail the
415 * allocation path, so the wakeup chaining is lost and we're
416 * left with hung waiters. We need to wake up those waiters.
418 if (q->request_fn) {
419 struct request_list *rl;
421 blk_queue_for_each_rl(rl, q)
422 for (i = 0; i < ARRAY_SIZE(rl->wait); i++)
423 wake_up_all(&rl->wait[i]);
428 * blk_queue_bypass_start - enter queue bypass mode
429 * @q: queue of interest
431 * In bypass mode, only the dispatch FIFO queue of @q is used. This
432 * function makes @q enter bypass mode and drains all requests which were
433 * throttled or issued before. On return, it's guaranteed that no request
434 * is being throttled or has ELVPRIV set and blk_queue_bypass() %true
435 * inside queue or RCU read lock.
437 void blk_queue_bypass_start(struct request_queue *q)
439 spin_lock_irq(q->queue_lock);
440 q->bypass_depth++;
441 queue_flag_set(QUEUE_FLAG_BYPASS, q);
442 spin_unlock_irq(q->queue_lock);
445 * Queues start drained. Skip actual draining till init is
446 * complete. This avoids lenghty delays during queue init which
447 * can happen many times during boot.
449 if (blk_queue_init_done(q)) {
450 spin_lock_irq(q->queue_lock);
451 __blk_drain_queue(q, false);
452 spin_unlock_irq(q->queue_lock);
454 /* ensure blk_queue_bypass() is %true inside RCU read lock */
455 synchronize_rcu();
458 EXPORT_SYMBOL_GPL(blk_queue_bypass_start);
461 * blk_queue_bypass_end - leave queue bypass mode
462 * @q: queue of interest
464 * Leave bypass mode and restore the normal queueing behavior.
466 void blk_queue_bypass_end(struct request_queue *q)
468 spin_lock_irq(q->queue_lock);
469 if (!--q->bypass_depth)
470 queue_flag_clear(QUEUE_FLAG_BYPASS, q);
471 WARN_ON_ONCE(q->bypass_depth < 0);
472 spin_unlock_irq(q->queue_lock);
474 EXPORT_SYMBOL_GPL(blk_queue_bypass_end);
476 void blk_set_queue_dying(struct request_queue *q)
478 spin_lock_irq(q->queue_lock);
479 queue_flag_set(QUEUE_FLAG_DYING, q);
480 spin_unlock_irq(q->queue_lock);
482 if (q->mq_ops)
483 blk_mq_wake_waiters(q);
484 else {
485 struct request_list *rl;
487 blk_queue_for_each_rl(rl, q) {
488 if (rl->rq_pool) {
489 wake_up(&rl->wait[BLK_RW_SYNC]);
490 wake_up(&rl->wait[BLK_RW_ASYNC]);
495 EXPORT_SYMBOL_GPL(blk_set_queue_dying);
498 * blk_cleanup_queue - shutdown a request queue
499 * @q: request queue to shutdown
501 * Mark @q DYING, drain all pending requests, mark @q DEAD, destroy and
502 * put it. All future requests will be failed immediately with -ENODEV.
504 void blk_cleanup_queue(struct request_queue *q)
506 spinlock_t *lock = q->queue_lock;
508 /* mark @q DYING, no new request or merges will be allowed afterwards */
509 mutex_lock(&q->sysfs_lock);
510 blk_set_queue_dying(q);
511 spin_lock_irq(lock);
514 * A dying queue is permanently in bypass mode till released. Note
515 * that, unlike blk_queue_bypass_start(), we aren't performing
516 * synchronize_rcu() after entering bypass mode to avoid the delay
517 * as some drivers create and destroy a lot of queues while
518 * probing. This is still safe because blk_release_queue() will be
519 * called only after the queue refcnt drops to zero and nothing,
520 * RCU or not, would be traversing the queue by then.
522 q->bypass_depth++;
523 queue_flag_set(QUEUE_FLAG_BYPASS, q);
525 queue_flag_set(QUEUE_FLAG_NOMERGES, q);
526 queue_flag_set(QUEUE_FLAG_NOXMERGES, q);
527 queue_flag_set(QUEUE_FLAG_DYING, q);
528 spin_unlock_irq(lock);
529 mutex_unlock(&q->sysfs_lock);
532 * Drain all requests queued before DYING marking. Set DEAD flag to
533 * prevent that q->request_fn() gets invoked after draining finished.
535 if (q->mq_ops) {
536 blk_mq_freeze_queue(q);
537 spin_lock_irq(lock);
538 } else {
539 spin_lock_irq(lock);
540 __blk_drain_queue(q, true);
542 queue_flag_set(QUEUE_FLAG_DEAD, q);
543 spin_unlock_irq(lock);
545 /* @q won't process any more request, flush async actions */
546 del_timer_sync(&q->backing_dev_info.laptop_mode_wb_timer);
547 blk_sync_queue(q);
549 if (q->mq_ops)
550 blk_mq_free_queue(q);
552 spin_lock_irq(lock);
553 if (q->queue_lock != &q->__queue_lock)
554 q->queue_lock = &q->__queue_lock;
555 spin_unlock_irq(lock);
557 bdi_destroy(&q->backing_dev_info);
559 /* @q is and will stay empty, shutdown and put */
560 blk_put_queue(q);
562 EXPORT_SYMBOL(blk_cleanup_queue);
564 /* Allocate memory local to the request queue */
565 static void *alloc_request_struct(gfp_t gfp_mask, void *data)
567 int nid = (int)(long)data;
568 return kmem_cache_alloc_node(request_cachep, gfp_mask, nid);
571 static void free_request_struct(void *element, void *unused)
573 kmem_cache_free(request_cachep, element);
576 int blk_init_rl(struct request_list *rl, struct request_queue *q,
577 gfp_t gfp_mask)
579 if (unlikely(rl->rq_pool))
580 return 0;
582 rl->q = q;
583 rl->count[BLK_RW_SYNC] = rl->count[BLK_RW_ASYNC] = 0;
584 rl->starved[BLK_RW_SYNC] = rl->starved[BLK_RW_ASYNC] = 0;
585 init_waitqueue_head(&rl->wait[BLK_RW_SYNC]);
586 init_waitqueue_head(&rl->wait[BLK_RW_ASYNC]);
588 rl->rq_pool = mempool_create_node(BLKDEV_MIN_RQ, alloc_request_struct,
589 free_request_struct,
590 (void *)(long)q->node, gfp_mask,
591 q->node);
592 if (!rl->rq_pool)
593 return -ENOMEM;
595 return 0;
598 void blk_exit_rl(struct request_list *rl)
600 if (rl->rq_pool)
601 mempool_destroy(rl->rq_pool);
604 struct request_queue *blk_alloc_queue(gfp_t gfp_mask)
606 return blk_alloc_queue_node(gfp_mask, NUMA_NO_NODE);
608 EXPORT_SYMBOL(blk_alloc_queue);
610 struct request_queue *blk_alloc_queue_node(gfp_t gfp_mask, int node_id)
612 struct request_queue *q;
613 int err;
615 q = kmem_cache_alloc_node(blk_requestq_cachep,
616 gfp_mask | __GFP_ZERO, node_id);
617 if (!q)
618 return NULL;
620 q->id = ida_simple_get(&blk_queue_ida, 0, 0, gfp_mask);
621 if (q->id < 0)
622 goto fail_q;
624 q->backing_dev_info.ra_pages =
625 (VM_MAX_READAHEAD * 1024) / PAGE_CACHE_SIZE;
626 q->backing_dev_info.state = 0;
627 q->backing_dev_info.capabilities = 0;
628 q->backing_dev_info.name = "block";
629 q->node = node_id;
631 err = bdi_init(&q->backing_dev_info);
632 if (err)
633 goto fail_id;
635 setup_timer(&q->backing_dev_info.laptop_mode_wb_timer,
636 laptop_mode_timer_fn, (unsigned long) q);
637 setup_timer(&q->timeout, blk_rq_timed_out_timer, (unsigned long) q);
638 INIT_LIST_HEAD(&q->queue_head);
639 INIT_LIST_HEAD(&q->timeout_list);
640 INIT_LIST_HEAD(&q->icq_list);
641 #ifdef CONFIG_BLK_CGROUP
642 INIT_LIST_HEAD(&q->blkg_list);
643 #endif
644 INIT_DELAYED_WORK(&q->delay_work, blk_delay_work);
646 kobject_init(&q->kobj, &blk_queue_ktype);
648 mutex_init(&q->sysfs_lock);
649 spin_lock_init(&q->__queue_lock);
652 * By default initialize queue_lock to internal lock and driver can
653 * override it later if need be.
655 q->queue_lock = &q->__queue_lock;
658 * A queue starts its life with bypass turned on to avoid
659 * unnecessary bypass on/off overhead and nasty surprises during
660 * init. The initial bypass will be finished when the queue is
661 * registered by blk_register_queue().
663 q->bypass_depth = 1;
664 __set_bit(QUEUE_FLAG_BYPASS, &q->queue_flags);
666 init_waitqueue_head(&q->mq_freeze_wq);
668 if (blkcg_init_queue(q))
669 goto fail_bdi;
671 return q;
673 fail_bdi:
674 bdi_destroy(&q->backing_dev_info);
675 fail_id:
676 ida_simple_remove(&blk_queue_ida, q->id);
677 fail_q:
678 kmem_cache_free(blk_requestq_cachep, q);
679 return NULL;
681 EXPORT_SYMBOL(blk_alloc_queue_node);
684 * blk_init_queue - prepare a request queue for use with a block device
685 * @rfn: The function to be called to process requests that have been
686 * placed on the queue.
687 * @lock: Request queue spin lock
689 * Description:
690 * If a block device wishes to use the standard request handling procedures,
691 * which sorts requests and coalesces adjacent requests, then it must
692 * call blk_init_queue(). The function @rfn will be called when there
693 * are requests on the queue that need to be processed. If the device
694 * supports plugging, then @rfn may not be called immediately when requests
695 * are available on the queue, but may be called at some time later instead.
696 * Plugged queues are generally unplugged when a buffer belonging to one
697 * of the requests on the queue is needed, or due to memory pressure.
699 * @rfn is not required, or even expected, to remove all requests off the
700 * queue, but only as many as it can handle at a time. If it does leave
701 * requests on the queue, it is responsible for arranging that the requests
702 * get dealt with eventually.
704 * The queue spin lock must be held while manipulating the requests on the
705 * request queue; this lock will be taken also from interrupt context, so irq
706 * disabling is needed for it.
708 * Function returns a pointer to the initialized request queue, or %NULL if
709 * it didn't succeed.
711 * Note:
712 * blk_init_queue() must be paired with a blk_cleanup_queue() call
713 * when the block device is deactivated (such as at module unload).
716 struct request_queue *blk_init_queue(request_fn_proc *rfn, spinlock_t *lock)
718 return blk_init_queue_node(rfn, lock, NUMA_NO_NODE);
720 EXPORT_SYMBOL(blk_init_queue);
722 struct request_queue *
723 blk_init_queue_node(request_fn_proc *rfn, spinlock_t *lock, int node_id)
725 struct request_queue *uninit_q, *q;
727 uninit_q = blk_alloc_queue_node(GFP_KERNEL, node_id);
728 if (!uninit_q)
729 return NULL;
731 q = blk_init_allocated_queue(uninit_q, rfn, lock);
732 if (!q)
733 blk_cleanup_queue(uninit_q);
735 return q;
737 EXPORT_SYMBOL(blk_init_queue_node);
739 static void blk_queue_bio(struct request_queue *q, struct bio *bio);
741 struct request_queue *
742 blk_init_allocated_queue(struct request_queue *q, request_fn_proc *rfn,
743 spinlock_t *lock)
745 if (!q)
746 return NULL;
748 q->fq = blk_alloc_flush_queue(q, NUMA_NO_NODE, 0);
749 if (!q->fq)
750 return NULL;
752 if (blk_init_rl(&q->root_rl, q, GFP_KERNEL))
753 goto fail;
755 q->request_fn = rfn;
756 q->prep_rq_fn = NULL;
757 q->unprep_rq_fn = NULL;
758 q->queue_flags |= QUEUE_FLAG_DEFAULT;
760 /* Override internal queue lock with supplied lock pointer */
761 if (lock)
762 q->queue_lock = lock;
765 * This also sets hw/phys segments, boundary and size
767 blk_queue_make_request(q, blk_queue_bio);
769 q->sg_reserved_size = INT_MAX;
771 /* Protect q->elevator from elevator_change */
772 mutex_lock(&q->sysfs_lock);
774 /* init elevator */
775 if (elevator_init(q, NULL)) {
776 mutex_unlock(&q->sysfs_lock);
777 goto fail;
780 mutex_unlock(&q->sysfs_lock);
782 return q;
784 fail:
785 blk_free_flush_queue(q->fq);
786 return NULL;
788 EXPORT_SYMBOL(blk_init_allocated_queue);
790 bool blk_get_queue(struct request_queue *q)
792 if (likely(!blk_queue_dying(q))) {
793 __blk_get_queue(q);
794 return true;
797 return false;
799 EXPORT_SYMBOL(blk_get_queue);
801 static inline void blk_free_request(struct request_list *rl, struct request *rq)
803 if (rq->cmd_flags & REQ_ELVPRIV) {
804 elv_put_request(rl->q, rq);
805 if (rq->elv.icq)
806 put_io_context(rq->elv.icq->ioc);
809 mempool_free(rq, rl->rq_pool);
813 * ioc_batching returns true if the ioc is a valid batching request and
814 * should be given priority access to a request.
816 static inline int ioc_batching(struct request_queue *q, struct io_context *ioc)
818 if (!ioc)
819 return 0;
822 * Make sure the process is able to allocate at least 1 request
823 * even if the batch times out, otherwise we could theoretically
824 * lose wakeups.
826 return ioc->nr_batch_requests == q->nr_batching ||
827 (ioc->nr_batch_requests > 0
828 && time_before(jiffies, ioc->last_waited + BLK_BATCH_TIME));
832 * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
833 * will cause the process to be a "batcher" on all queues in the system. This
834 * is the behaviour we want though - once it gets a wakeup it should be given
835 * a nice run.
837 static void ioc_set_batching(struct request_queue *q, struct io_context *ioc)
839 if (!ioc || ioc_batching(q, ioc))
840 return;
842 ioc->nr_batch_requests = q->nr_batching;
843 ioc->last_waited = jiffies;
846 static void __freed_request(struct request_list *rl, int sync)
848 struct request_queue *q = rl->q;
851 * bdi isn't aware of blkcg yet. As all async IOs end up root
852 * blkcg anyway, just use root blkcg state.
854 if (rl == &q->root_rl &&
855 rl->count[sync] < queue_congestion_off_threshold(q))
856 blk_clear_queue_congested(q, sync);
858 if (rl->count[sync] + 1 <= q->nr_requests) {
859 if (waitqueue_active(&rl->wait[sync]))
860 wake_up(&rl->wait[sync]);
862 blk_clear_rl_full(rl, sync);
867 * A request has just been released. Account for it, update the full and
868 * congestion status, wake up any waiters. Called under q->queue_lock.
870 static void freed_request(struct request_list *rl, unsigned int flags)
872 struct request_queue *q = rl->q;
873 int sync = rw_is_sync(flags);
875 q->nr_rqs[sync]--;
876 rl->count[sync]--;
877 if (flags & REQ_ELVPRIV)
878 q->nr_rqs_elvpriv--;
880 __freed_request(rl, sync);
882 if (unlikely(rl->starved[sync ^ 1]))
883 __freed_request(rl, sync ^ 1);
886 int blk_update_nr_requests(struct request_queue *q, unsigned int nr)
888 struct request_list *rl;
890 spin_lock_irq(q->queue_lock);
891 q->nr_requests = nr;
892 blk_queue_congestion_threshold(q);
894 /* congestion isn't cgroup aware and follows root blkcg for now */
895 rl = &q->root_rl;
897 if (rl->count[BLK_RW_SYNC] >= queue_congestion_on_threshold(q))
898 blk_set_queue_congested(q, BLK_RW_SYNC);
899 else if (rl->count[BLK_RW_SYNC] < queue_congestion_off_threshold(q))
900 blk_clear_queue_congested(q, BLK_RW_SYNC);
902 if (rl->count[BLK_RW_ASYNC] >= queue_congestion_on_threshold(q))
903 blk_set_queue_congested(q, BLK_RW_ASYNC);
904 else if (rl->count[BLK_RW_ASYNC] < queue_congestion_off_threshold(q))
905 blk_clear_queue_congested(q, BLK_RW_ASYNC);
907 blk_queue_for_each_rl(rl, q) {
908 if (rl->count[BLK_RW_SYNC] >= q->nr_requests) {
909 blk_set_rl_full(rl, BLK_RW_SYNC);
910 } else {
911 blk_clear_rl_full(rl, BLK_RW_SYNC);
912 wake_up(&rl->wait[BLK_RW_SYNC]);
915 if (rl->count[BLK_RW_ASYNC] >= q->nr_requests) {
916 blk_set_rl_full(rl, BLK_RW_ASYNC);
917 } else {
918 blk_clear_rl_full(rl, BLK_RW_ASYNC);
919 wake_up(&rl->wait[BLK_RW_ASYNC]);
923 spin_unlock_irq(q->queue_lock);
924 return 0;
928 * Determine if elevator data should be initialized when allocating the
929 * request associated with @bio.
931 static bool blk_rq_should_init_elevator(struct bio *bio)
933 if (!bio)
934 return true;
937 * Flush requests do not use the elevator so skip initialization.
938 * This allows a request to share the flush and elevator data.
940 if (bio->bi_rw & (REQ_FLUSH | REQ_FUA))
941 return false;
943 return true;
947 * rq_ioc - determine io_context for request allocation
948 * @bio: request being allocated is for this bio (can be %NULL)
950 * Determine io_context to use for request allocation for @bio. May return
951 * %NULL if %current->io_context doesn't exist.
953 static struct io_context *rq_ioc(struct bio *bio)
955 #ifdef CONFIG_BLK_CGROUP
956 if (bio && bio->bi_ioc)
957 return bio->bi_ioc;
958 #endif
959 return current->io_context;
963 * __get_request - get a free request
964 * @rl: request list to allocate from
965 * @rw_flags: RW and SYNC flags
966 * @bio: bio to allocate request for (can be %NULL)
967 * @gfp_mask: allocation mask
969 * Get a free request from @q. This function may fail under memory
970 * pressure or if @q is dead.
972 * Must be called with @q->queue_lock held and,
973 * Returns ERR_PTR on failure, with @q->queue_lock held.
974 * Returns request pointer on success, with @q->queue_lock *not held*.
976 static struct request *__get_request(struct request_list *rl, int rw_flags,
977 struct bio *bio, gfp_t gfp_mask)
979 struct request_queue *q = rl->q;
980 struct request *rq;
981 struct elevator_type *et = q->elevator->type;
982 struct io_context *ioc = rq_ioc(bio);
983 struct io_cq *icq = NULL;
984 const bool is_sync = rw_is_sync(rw_flags) != 0;
985 int may_queue;
987 if (unlikely(blk_queue_dying(q)))
988 return ERR_PTR(-ENODEV);
990 may_queue = elv_may_queue(q, rw_flags);
991 if (may_queue == ELV_MQUEUE_NO)
992 goto rq_starved;
994 if (rl->count[is_sync]+1 >= queue_congestion_on_threshold(q)) {
995 if (rl->count[is_sync]+1 >= q->nr_requests) {
997 * The queue will fill after this allocation, so set
998 * it as full, and mark this process as "batching".
999 * This process will be allowed to complete a batch of
1000 * requests, others will be blocked.
1002 if (!blk_rl_full(rl, is_sync)) {
1003 ioc_set_batching(q, ioc);
1004 blk_set_rl_full(rl, is_sync);
1005 } else {
1006 if (may_queue != ELV_MQUEUE_MUST
1007 && !ioc_batching(q, ioc)) {
1009 * The queue is full and the allocating
1010 * process is not a "batcher", and not
1011 * exempted by the IO scheduler
1013 return ERR_PTR(-ENOMEM);
1018 * bdi isn't aware of blkcg yet. As all async IOs end up
1019 * root blkcg anyway, just use root blkcg state.
1021 if (rl == &q->root_rl)
1022 blk_set_queue_congested(q, is_sync);
1026 * Only allow batching queuers to allocate up to 50% over the defined
1027 * limit of requests, otherwise we could have thousands of requests
1028 * allocated with any setting of ->nr_requests
1030 if (rl->count[is_sync] >= (3 * q->nr_requests / 2))
1031 return ERR_PTR(-ENOMEM);
1033 q->nr_rqs[is_sync]++;
1034 rl->count[is_sync]++;
1035 rl->starved[is_sync] = 0;
1038 * Decide whether the new request will be managed by elevator. If
1039 * so, mark @rw_flags and increment elvpriv. Non-zero elvpriv will
1040 * prevent the current elevator from being destroyed until the new
1041 * request is freed. This guarantees icq's won't be destroyed and
1042 * makes creating new ones safe.
1044 * Also, lookup icq while holding queue_lock. If it doesn't exist,
1045 * it will be created after releasing queue_lock.
1047 if (blk_rq_should_init_elevator(bio) && !blk_queue_bypass(q)) {
1048 rw_flags |= REQ_ELVPRIV;
1049 q->nr_rqs_elvpriv++;
1050 if (et->icq_cache && ioc)
1051 icq = ioc_lookup_icq(ioc, q);
1054 if (blk_queue_io_stat(q))
1055 rw_flags |= REQ_IO_STAT;
1056 spin_unlock_irq(q->queue_lock);
1058 /* allocate and init request */
1059 rq = mempool_alloc(rl->rq_pool, gfp_mask);
1060 if (!rq)
1061 goto fail_alloc;
1063 blk_rq_init(q, rq);
1064 blk_rq_set_rl(rq, rl);
1065 rq->cmd_flags = rw_flags | REQ_ALLOCED;
1067 /* init elvpriv */
1068 if (rw_flags & REQ_ELVPRIV) {
1069 if (unlikely(et->icq_cache && !icq)) {
1070 if (ioc)
1071 icq = ioc_create_icq(ioc, q, gfp_mask);
1072 if (!icq)
1073 goto fail_elvpriv;
1076 rq->elv.icq = icq;
1077 if (unlikely(elv_set_request(q, rq, bio, gfp_mask)))
1078 goto fail_elvpriv;
1080 /* @rq->elv.icq holds io_context until @rq is freed */
1081 if (icq)
1082 get_io_context(icq->ioc);
1084 out:
1086 * ioc may be NULL here, and ioc_batching will be false. That's
1087 * OK, if the queue is under the request limit then requests need
1088 * not count toward the nr_batch_requests limit. There will always
1089 * be some limit enforced by BLK_BATCH_TIME.
1091 if (ioc_batching(q, ioc))
1092 ioc->nr_batch_requests--;
1094 trace_block_getrq(q, bio, rw_flags & 1);
1095 return rq;
1097 fail_elvpriv:
1099 * elvpriv init failed. ioc, icq and elvpriv aren't mempool backed
1100 * and may fail indefinitely under memory pressure and thus
1101 * shouldn't stall IO. Treat this request as !elvpriv. This will
1102 * disturb iosched and blkcg but weird is bettern than dead.
1104 printk_ratelimited(KERN_WARNING "%s: dev %s: request aux data allocation failed, iosched may be disturbed\n",
1105 __func__, dev_name(q->backing_dev_info.dev));
1107 rq->cmd_flags &= ~REQ_ELVPRIV;
1108 rq->elv.icq = NULL;
1110 spin_lock_irq(q->queue_lock);
1111 q->nr_rqs_elvpriv--;
1112 spin_unlock_irq(q->queue_lock);
1113 goto out;
1115 fail_alloc:
1117 * Allocation failed presumably due to memory. Undo anything we
1118 * might have messed up.
1120 * Allocating task should really be put onto the front of the wait
1121 * queue, but this is pretty rare.
1123 spin_lock_irq(q->queue_lock);
1124 freed_request(rl, rw_flags);
1127 * in the very unlikely event that allocation failed and no
1128 * requests for this direction was pending, mark us starved so that
1129 * freeing of a request in the other direction will notice
1130 * us. another possible fix would be to split the rq mempool into
1131 * READ and WRITE
1133 rq_starved:
1134 if (unlikely(rl->count[is_sync] == 0))
1135 rl->starved[is_sync] = 1;
1136 return ERR_PTR(-ENOMEM);
1140 * get_request - get a free request
1141 * @q: request_queue to allocate request from
1142 * @rw_flags: RW and SYNC flags
1143 * @bio: bio to allocate request for (can be %NULL)
1144 * @gfp_mask: allocation mask
1146 * Get a free request from @q. If %__GFP_WAIT is set in @gfp_mask, this
1147 * function keeps retrying under memory pressure and fails iff @q is dead.
1149 * Must be called with @q->queue_lock held and,
1150 * Returns ERR_PTR on failure, with @q->queue_lock held.
1151 * Returns request pointer on success, with @q->queue_lock *not held*.
1153 static struct request *get_request(struct request_queue *q, int rw_flags,
1154 struct bio *bio, gfp_t gfp_mask)
1156 const bool is_sync = rw_is_sync(rw_flags) != 0;
1157 DEFINE_WAIT(wait);
1158 struct request_list *rl;
1159 struct request *rq;
1161 rl = blk_get_rl(q, bio); /* transferred to @rq on success */
1162 retry:
1163 rq = __get_request(rl, rw_flags, bio, gfp_mask);
1164 if (!IS_ERR(rq))
1165 return rq;
1167 if (!(gfp_mask & __GFP_WAIT) || unlikely(blk_queue_dying(q))) {
1168 blk_put_rl(rl);
1169 return rq;
1172 /* wait on @rl and retry */
1173 prepare_to_wait_exclusive(&rl->wait[is_sync], &wait,
1174 TASK_UNINTERRUPTIBLE);
1176 trace_block_sleeprq(q, bio, rw_flags & 1);
1178 spin_unlock_irq(q->queue_lock);
1179 io_schedule();
1182 * After sleeping, we become a "batching" process and will be able
1183 * to allocate at least one request, and up to a big batch of them
1184 * for a small period time. See ioc_batching, ioc_set_batching
1186 ioc_set_batching(q, current->io_context);
1188 spin_lock_irq(q->queue_lock);
1189 finish_wait(&rl->wait[is_sync], &wait);
1191 goto retry;
1194 static struct request *blk_old_get_request(struct request_queue *q, int rw,
1195 gfp_t gfp_mask)
1197 struct request *rq;
1199 BUG_ON(rw != READ && rw != WRITE);
1201 /* create ioc upfront */
1202 create_io_context(gfp_mask, q->node);
1204 spin_lock_irq(q->queue_lock);
1205 rq = get_request(q, rw, NULL, gfp_mask);
1206 if (IS_ERR(rq))
1207 spin_unlock_irq(q->queue_lock);
1208 /* q->queue_lock is unlocked at this point */
1210 return rq;
1213 struct request *blk_get_request(struct request_queue *q, int rw, gfp_t gfp_mask)
1215 if (q->mq_ops)
1216 return blk_mq_alloc_request(q, rw, gfp_mask, false);
1217 else
1218 return blk_old_get_request(q, rw, gfp_mask);
1220 EXPORT_SYMBOL(blk_get_request);
1223 * blk_make_request - given a bio, allocate a corresponding struct request.
1224 * @q: target request queue
1225 * @bio: The bio describing the memory mappings that will be submitted for IO.
1226 * It may be a chained-bio properly constructed by block/bio layer.
1227 * @gfp_mask: gfp flags to be used for memory allocation
1229 * blk_make_request is the parallel of generic_make_request for BLOCK_PC
1230 * type commands. Where the struct request needs to be farther initialized by
1231 * the caller. It is passed a &struct bio, which describes the memory info of
1232 * the I/O transfer.
1234 * The caller of blk_make_request must make sure that bi_io_vec
1235 * are set to describe the memory buffers. That bio_data_dir() will return
1236 * the needed direction of the request. (And all bio's in the passed bio-chain
1237 * are properly set accordingly)
1239 * If called under none-sleepable conditions, mapped bio buffers must not
1240 * need bouncing, by calling the appropriate masked or flagged allocator,
1241 * suitable for the target device. Otherwise the call to blk_queue_bounce will
1242 * BUG.
1244 * WARNING: When allocating/cloning a bio-chain, careful consideration should be
1245 * given to how you allocate bios. In particular, you cannot use __GFP_WAIT for
1246 * anything but the first bio in the chain. Otherwise you risk waiting for IO
1247 * completion of a bio that hasn't been submitted yet, thus resulting in a
1248 * deadlock. Alternatively bios should be allocated using bio_kmalloc() instead
1249 * of bio_alloc(), as that avoids the mempool deadlock.
1250 * If possible a big IO should be split into smaller parts when allocation
1251 * fails. Partial allocation should not be an error, or you risk a live-lock.
1253 struct request *blk_make_request(struct request_queue *q, struct bio *bio,
1254 gfp_t gfp_mask)
1256 struct request *rq = blk_get_request(q, bio_data_dir(bio), gfp_mask);
1258 if (IS_ERR(rq))
1259 return rq;
1261 blk_rq_set_block_pc(rq);
1263 for_each_bio(bio) {
1264 struct bio *bounce_bio = bio;
1265 int ret;
1267 blk_queue_bounce(q, &bounce_bio);
1268 ret = blk_rq_append_bio(q, rq, bounce_bio);
1269 if (unlikely(ret)) {
1270 blk_put_request(rq);
1271 return ERR_PTR(ret);
1275 return rq;
1277 EXPORT_SYMBOL(blk_make_request);
1280 * blk_rq_set_block_pc - initialize a request to type BLOCK_PC
1281 * @rq: request to be initialized
1284 void blk_rq_set_block_pc(struct request *rq)
1286 rq->cmd_type = REQ_TYPE_BLOCK_PC;
1287 rq->__data_len = 0;
1288 rq->__sector = (sector_t) -1;
1289 rq->bio = rq->biotail = NULL;
1290 memset(rq->__cmd, 0, sizeof(rq->__cmd));
1292 EXPORT_SYMBOL(blk_rq_set_block_pc);
1295 * blk_requeue_request - put a request back on queue
1296 * @q: request queue where request should be inserted
1297 * @rq: request to be inserted
1299 * Description:
1300 * Drivers often keep queueing requests until the hardware cannot accept
1301 * more, when that condition happens we need to put the request back
1302 * on the queue. Must be called with queue lock held.
1304 void blk_requeue_request(struct request_queue *q, struct request *rq)
1306 blk_delete_timer(rq);
1307 blk_clear_rq_complete(rq);
1308 trace_block_rq_requeue(q, rq);
1310 if (rq->cmd_flags & REQ_QUEUED)
1311 blk_queue_end_tag(q, rq);
1313 BUG_ON(blk_queued_rq(rq));
1315 elv_requeue_request(q, rq);
1317 EXPORT_SYMBOL(blk_requeue_request);
1319 static void add_acct_request(struct request_queue *q, struct request *rq,
1320 int where)
1322 blk_account_io_start(rq, true);
1323 __elv_add_request(q, rq, where);
1326 static void part_round_stats_single(int cpu, struct hd_struct *part,
1327 unsigned long now)
1329 int inflight;
1331 if (now == part->stamp)
1332 return;
1334 inflight = part_in_flight(part);
1335 if (inflight) {
1336 __part_stat_add(cpu, part, time_in_queue,
1337 inflight * (now - part->stamp));
1338 __part_stat_add(cpu, part, io_ticks, (now - part->stamp));
1340 part->stamp = now;
1344 * part_round_stats() - Round off the performance stats on a struct disk_stats.
1345 * @cpu: cpu number for stats access
1346 * @part: target partition
1348 * The average IO queue length and utilisation statistics are maintained
1349 * by observing the current state of the queue length and the amount of
1350 * time it has been in this state for.
1352 * Normally, that accounting is done on IO completion, but that can result
1353 * in more than a second's worth of IO being accounted for within any one
1354 * second, leading to >100% utilisation. To deal with that, we call this
1355 * function to do a round-off before returning the results when reading
1356 * /proc/diskstats. This accounts immediately for all queue usage up to
1357 * the current jiffies and restarts the counters again.
1359 void part_round_stats(int cpu, struct hd_struct *part)
1361 unsigned long now = jiffies;
1363 if (part->partno)
1364 part_round_stats_single(cpu, &part_to_disk(part)->part0, now);
1365 part_round_stats_single(cpu, part, now);
1367 EXPORT_SYMBOL_GPL(part_round_stats);
1369 #ifdef CONFIG_PM
1370 static void blk_pm_put_request(struct request *rq)
1372 if (rq->q->dev && !(rq->cmd_flags & REQ_PM) && !--rq->q->nr_pending)
1373 pm_runtime_mark_last_busy(rq->q->dev);
1375 #else
1376 static inline void blk_pm_put_request(struct request *rq) {}
1377 #endif
1380 * queue lock must be held
1382 void __blk_put_request(struct request_queue *q, struct request *req)
1384 if (unlikely(!q))
1385 return;
1387 if (q->mq_ops) {
1388 blk_mq_free_request(req);
1389 return;
1392 blk_pm_put_request(req);
1394 elv_completed_request(q, req);
1396 /* this is a bio leak */
1397 WARN_ON(req->bio != NULL);
1400 * Request may not have originated from ll_rw_blk. if not,
1401 * it didn't come out of our reserved rq pools
1403 if (req->cmd_flags & REQ_ALLOCED) {
1404 unsigned int flags = req->cmd_flags;
1405 struct request_list *rl = blk_rq_rl(req);
1407 BUG_ON(!list_empty(&req->queuelist));
1408 BUG_ON(ELV_ON_HASH(req));
1410 blk_free_request(rl, req);
1411 freed_request(rl, flags);
1412 blk_put_rl(rl);
1415 EXPORT_SYMBOL_GPL(__blk_put_request);
1417 void blk_put_request(struct request *req)
1419 struct request_queue *q = req->q;
1421 if (q->mq_ops)
1422 blk_mq_free_request(req);
1423 else {
1424 unsigned long flags;
1426 spin_lock_irqsave(q->queue_lock, flags);
1427 __blk_put_request(q, req);
1428 spin_unlock_irqrestore(q->queue_lock, flags);
1431 EXPORT_SYMBOL(blk_put_request);
1434 * blk_add_request_payload - add a payload to a request
1435 * @rq: request to update
1436 * @page: page backing the payload
1437 * @len: length of the payload.
1439 * This allows to later add a payload to an already submitted request by
1440 * a block driver. The driver needs to take care of freeing the payload
1441 * itself.
1443 * Note that this is a quite horrible hack and nothing but handling of
1444 * discard requests should ever use it.
1446 void blk_add_request_payload(struct request *rq, struct page *page,
1447 unsigned int len)
1449 struct bio *bio = rq->bio;
1451 bio->bi_io_vec->bv_page = page;
1452 bio->bi_io_vec->bv_offset = 0;
1453 bio->bi_io_vec->bv_len = len;
1455 bio->bi_iter.bi_size = len;
1456 bio->bi_vcnt = 1;
1457 bio->bi_phys_segments = 1;
1459 rq->__data_len = rq->resid_len = len;
1460 rq->nr_phys_segments = 1;
1462 EXPORT_SYMBOL_GPL(blk_add_request_payload);
1464 bool bio_attempt_back_merge(struct request_queue *q, struct request *req,
1465 struct bio *bio)
1467 const int ff = bio->bi_rw & REQ_FAILFAST_MASK;
1469 if (!ll_back_merge_fn(q, req, bio))
1470 return false;
1472 trace_block_bio_backmerge(q, req, bio);
1474 if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
1475 blk_rq_set_mixed_merge(req);
1477 req->biotail->bi_next = bio;
1478 req->biotail = bio;
1479 req->__data_len += bio->bi_iter.bi_size;
1480 req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
1482 blk_account_io_start(req, false);
1483 return true;
1486 bool bio_attempt_front_merge(struct request_queue *q, struct request *req,
1487 struct bio *bio)
1489 const int ff = bio->bi_rw & REQ_FAILFAST_MASK;
1491 if (!ll_front_merge_fn(q, req, bio))
1492 return false;
1494 trace_block_bio_frontmerge(q, req, bio);
1496 if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
1497 blk_rq_set_mixed_merge(req);
1499 bio->bi_next = req->bio;
1500 req->bio = bio;
1502 req->__sector = bio->bi_iter.bi_sector;
1503 req->__data_len += bio->bi_iter.bi_size;
1504 req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
1506 blk_account_io_start(req, false);
1507 return true;
1511 * blk_attempt_plug_merge - try to merge with %current's plugged list
1512 * @q: request_queue new bio is being queued at
1513 * @bio: new bio being queued
1514 * @request_count: out parameter for number of traversed plugged requests
1516 * Determine whether @bio being queued on @q can be merged with a request
1517 * on %current's plugged list. Returns %true if merge was successful,
1518 * otherwise %false.
1520 * Plugging coalesces IOs from the same issuer for the same purpose without
1521 * going through @q->queue_lock. As such it's more of an issuing mechanism
1522 * than scheduling, and the request, while may have elvpriv data, is not
1523 * added on the elevator at this point. In addition, we don't have
1524 * reliable access to the elevator outside queue lock. Only check basic
1525 * merging parameters without querying the elevator.
1527 * Caller must ensure !blk_queue_nomerges(q) beforehand.
1529 bool blk_attempt_plug_merge(struct request_queue *q, struct bio *bio,
1530 unsigned int *request_count)
1532 struct blk_plug *plug;
1533 struct request *rq;
1534 bool ret = false;
1535 struct list_head *plug_list;
1537 plug = current->plug;
1538 if (!plug)
1539 goto out;
1540 *request_count = 0;
1542 if (q->mq_ops)
1543 plug_list = &plug->mq_list;
1544 else
1545 plug_list = &plug->list;
1547 list_for_each_entry_reverse(rq, plug_list, queuelist) {
1548 int el_ret;
1550 if (rq->q == q)
1551 (*request_count)++;
1553 if (rq->q != q || !blk_rq_merge_ok(rq, bio))
1554 continue;
1556 el_ret = blk_try_merge(rq, bio);
1557 if (el_ret == ELEVATOR_BACK_MERGE) {
1558 ret = bio_attempt_back_merge(q, rq, bio);
1559 if (ret)
1560 break;
1561 } else if (el_ret == ELEVATOR_FRONT_MERGE) {
1562 ret = bio_attempt_front_merge(q, rq, bio);
1563 if (ret)
1564 break;
1567 out:
1568 return ret;
1571 void init_request_from_bio(struct request *req, struct bio *bio)
1573 req->cmd_type = REQ_TYPE_FS;
1575 req->cmd_flags |= bio->bi_rw & REQ_COMMON_MASK;
1576 if (bio->bi_rw & REQ_RAHEAD)
1577 req->cmd_flags |= REQ_FAILFAST_MASK;
1579 req->errors = 0;
1580 req->__sector = bio->bi_iter.bi_sector;
1581 req->ioprio = bio_prio(bio);
1582 blk_rq_bio_prep(req->q, req, bio);
1585 static void blk_queue_bio(struct request_queue *q, struct bio *bio)
1587 const bool sync = !!(bio->bi_rw & REQ_SYNC);
1588 struct blk_plug *plug;
1589 int el_ret, rw_flags, where = ELEVATOR_INSERT_SORT;
1590 struct request *req;
1591 unsigned int request_count = 0;
1594 * low level driver can indicate that it wants pages above a
1595 * certain limit bounced to low memory (ie for highmem, or even
1596 * ISA dma in theory)
1598 blk_queue_bounce(q, &bio);
1600 if (bio_integrity_enabled(bio) && bio_integrity_prep(bio)) {
1601 bio_endio(bio, -EIO);
1602 return;
1605 if (bio->bi_rw & (REQ_FLUSH | REQ_FUA)) {
1606 spin_lock_irq(q->queue_lock);
1607 where = ELEVATOR_INSERT_FLUSH;
1608 goto get_rq;
1612 * Check if we can merge with the plugged list before grabbing
1613 * any locks.
1615 if (!blk_queue_nomerges(q) &&
1616 blk_attempt_plug_merge(q, bio, &request_count))
1617 return;
1619 spin_lock_irq(q->queue_lock);
1621 el_ret = elv_merge(q, &req, bio);
1622 if (el_ret == ELEVATOR_BACK_MERGE) {
1623 if (bio_attempt_back_merge(q, req, bio)) {
1624 elv_bio_merged(q, req, bio);
1625 if (!attempt_back_merge(q, req))
1626 elv_merged_request(q, req, el_ret);
1627 goto out_unlock;
1629 } else if (el_ret == ELEVATOR_FRONT_MERGE) {
1630 if (bio_attempt_front_merge(q, req, bio)) {
1631 elv_bio_merged(q, req, bio);
1632 if (!attempt_front_merge(q, req))
1633 elv_merged_request(q, req, el_ret);
1634 goto out_unlock;
1638 get_rq:
1640 * This sync check and mask will be re-done in init_request_from_bio(),
1641 * but we need to set it earlier to expose the sync flag to the
1642 * rq allocator and io schedulers.
1644 rw_flags = bio_data_dir(bio);
1645 if (sync)
1646 rw_flags |= REQ_SYNC;
1649 * Grab a free request. This is might sleep but can not fail.
1650 * Returns with the queue unlocked.
1652 req = get_request(q, rw_flags, bio, GFP_NOIO);
1653 if (IS_ERR(req)) {
1654 bio_endio(bio, PTR_ERR(req)); /* @q is dead */
1655 goto out_unlock;
1659 * After dropping the lock and possibly sleeping here, our request
1660 * may now be mergeable after it had proven unmergeable (above).
1661 * We don't worry about that case for efficiency. It won't happen
1662 * often, and the elevators are able to handle it.
1664 init_request_from_bio(req, bio);
1666 if (test_bit(QUEUE_FLAG_SAME_COMP, &q->queue_flags))
1667 req->cpu = raw_smp_processor_id();
1669 plug = current->plug;
1670 if (plug) {
1672 * If this is the first request added after a plug, fire
1673 * of a plug trace.
1675 if (!request_count)
1676 trace_block_plug(q);
1677 else {
1678 if (request_count >= BLK_MAX_REQUEST_COUNT) {
1679 blk_flush_plug_list(plug, false);
1680 trace_block_plug(q);
1683 list_add_tail(&req->queuelist, &plug->list);
1684 blk_account_io_start(req, true);
1685 } else {
1686 spin_lock_irq(q->queue_lock);
1687 add_acct_request(q, req, where);
1688 __blk_run_queue(q);
1689 out_unlock:
1690 spin_unlock_irq(q->queue_lock);
1695 * If bio->bi_dev is a partition, remap the location
1697 static inline void blk_partition_remap(struct bio *bio)
1699 struct block_device *bdev = bio->bi_bdev;
1701 if (bio_sectors(bio) && bdev != bdev->bd_contains) {
1702 struct hd_struct *p = bdev->bd_part;
1704 bio->bi_iter.bi_sector += p->start_sect;
1705 bio->bi_bdev = bdev->bd_contains;
1707 trace_block_bio_remap(bdev_get_queue(bio->bi_bdev), bio,
1708 bdev->bd_dev,
1709 bio->bi_iter.bi_sector - p->start_sect);
1713 static void handle_bad_sector(struct bio *bio)
1715 char b[BDEVNAME_SIZE];
1717 printk(KERN_INFO "attempt to access beyond end of device\n");
1718 printk(KERN_INFO "%s: rw=%ld, want=%Lu, limit=%Lu\n",
1719 bdevname(bio->bi_bdev, b),
1720 bio->bi_rw,
1721 (unsigned long long)bio_end_sector(bio),
1722 (long long)(i_size_read(bio->bi_bdev->bd_inode) >> 9));
1724 set_bit(BIO_EOF, &bio->bi_flags);
1727 #ifdef CONFIG_FAIL_MAKE_REQUEST
1729 static DECLARE_FAULT_ATTR(fail_make_request);
1731 static int __init setup_fail_make_request(char *str)
1733 return setup_fault_attr(&fail_make_request, str);
1735 __setup("fail_make_request=", setup_fail_make_request);
1737 static bool should_fail_request(struct hd_struct *part, unsigned int bytes)
1739 return part->make_it_fail && should_fail(&fail_make_request, bytes);
1742 static int __init fail_make_request_debugfs(void)
1744 struct dentry *dir = fault_create_debugfs_attr("fail_make_request",
1745 NULL, &fail_make_request);
1747 return PTR_ERR_OR_ZERO(dir);
1750 late_initcall(fail_make_request_debugfs);
1752 #else /* CONFIG_FAIL_MAKE_REQUEST */
1754 static inline bool should_fail_request(struct hd_struct *part,
1755 unsigned int bytes)
1757 return false;
1760 #endif /* CONFIG_FAIL_MAKE_REQUEST */
1763 * Check whether this bio extends beyond the end of the device.
1765 static inline int bio_check_eod(struct bio *bio, unsigned int nr_sectors)
1767 sector_t maxsector;
1769 if (!nr_sectors)
1770 return 0;
1772 /* Test device or partition size, when known. */
1773 maxsector = i_size_read(bio->bi_bdev->bd_inode) >> 9;
1774 if (maxsector) {
1775 sector_t sector = bio->bi_iter.bi_sector;
1777 if (maxsector < nr_sectors || maxsector - nr_sectors < sector) {
1779 * This may well happen - the kernel calls bread()
1780 * without checking the size of the device, e.g., when
1781 * mounting a device.
1783 handle_bad_sector(bio);
1784 return 1;
1788 return 0;
1791 static noinline_for_stack bool
1792 generic_make_request_checks(struct bio *bio)
1794 struct request_queue *q;
1795 int nr_sectors = bio_sectors(bio);
1796 int err = -EIO;
1797 char b[BDEVNAME_SIZE];
1798 struct hd_struct *part;
1800 might_sleep();
1802 if (bio_check_eod(bio, nr_sectors))
1803 goto end_io;
1805 q = bdev_get_queue(bio->bi_bdev);
1806 if (unlikely(!q)) {
1807 printk(KERN_ERR
1808 "generic_make_request: Trying to access "
1809 "nonexistent block-device %s (%Lu)\n",
1810 bdevname(bio->bi_bdev, b),
1811 (long long) bio->bi_iter.bi_sector);
1812 goto end_io;
1815 if (likely(bio_is_rw(bio) &&
1816 nr_sectors > queue_max_hw_sectors(q))) {
1817 printk(KERN_ERR "bio too big device %s (%u > %u)\n",
1818 bdevname(bio->bi_bdev, b),
1819 bio_sectors(bio),
1820 queue_max_hw_sectors(q));
1821 goto end_io;
1824 part = bio->bi_bdev->bd_part;
1825 if (should_fail_request(part, bio->bi_iter.bi_size) ||
1826 should_fail_request(&part_to_disk(part)->part0,
1827 bio->bi_iter.bi_size))
1828 goto end_io;
1831 * If this device has partitions, remap block n
1832 * of partition p to block n+start(p) of the disk.
1834 blk_partition_remap(bio);
1836 if (bio_check_eod(bio, nr_sectors))
1837 goto end_io;
1840 * Filter flush bio's early so that make_request based
1841 * drivers without flush support don't have to worry
1842 * about them.
1844 if ((bio->bi_rw & (REQ_FLUSH | REQ_FUA)) && !q->flush_flags) {
1845 bio->bi_rw &= ~(REQ_FLUSH | REQ_FUA);
1846 if (!nr_sectors) {
1847 err = 0;
1848 goto end_io;
1852 if ((bio->bi_rw & REQ_DISCARD) &&
1853 (!blk_queue_discard(q) ||
1854 ((bio->bi_rw & REQ_SECURE) && !blk_queue_secdiscard(q)))) {
1855 err = -EOPNOTSUPP;
1856 goto end_io;
1859 if (bio->bi_rw & REQ_WRITE_SAME && !bdev_write_same(bio->bi_bdev)) {
1860 err = -EOPNOTSUPP;
1861 goto end_io;
1865 * Various block parts want %current->io_context and lazy ioc
1866 * allocation ends up trading a lot of pain for a small amount of
1867 * memory. Just allocate it upfront. This may fail and block
1868 * layer knows how to live with it.
1870 create_io_context(GFP_ATOMIC, q->node);
1872 if (blk_throtl_bio(q, bio))
1873 return false; /* throttled, will be resubmitted later */
1875 trace_block_bio_queue(q, bio);
1876 return true;
1878 end_io:
1879 bio_endio(bio, err);
1880 return false;
1884 * generic_make_request - hand a buffer to its device driver for I/O
1885 * @bio: The bio describing the location in memory and on the device.
1887 * generic_make_request() is used to make I/O requests of block
1888 * devices. It is passed a &struct bio, which describes the I/O that needs
1889 * to be done.
1891 * generic_make_request() does not return any status. The
1892 * success/failure status of the request, along with notification of
1893 * completion, is delivered asynchronously through the bio->bi_end_io
1894 * function described (one day) else where.
1896 * The caller of generic_make_request must make sure that bi_io_vec
1897 * are set to describe the memory buffer, and that bi_dev and bi_sector are
1898 * set to describe the device address, and the
1899 * bi_end_io and optionally bi_private are set to describe how
1900 * completion notification should be signaled.
1902 * generic_make_request and the drivers it calls may use bi_next if this
1903 * bio happens to be merged with someone else, and may resubmit the bio to
1904 * a lower device by calling into generic_make_request recursively, which
1905 * means the bio should NOT be touched after the call to ->make_request_fn.
1907 void generic_make_request(struct bio *bio)
1909 struct bio_list bio_list_on_stack;
1911 if (!generic_make_request_checks(bio))
1912 return;
1915 * We only want one ->make_request_fn to be active at a time, else
1916 * stack usage with stacked devices could be a problem. So use
1917 * current->bio_list to keep a list of requests submited by a
1918 * make_request_fn function. current->bio_list is also used as a
1919 * flag to say if generic_make_request is currently active in this
1920 * task or not. If it is NULL, then no make_request is active. If
1921 * it is non-NULL, then a make_request is active, and new requests
1922 * should be added at the tail
1924 if (current->bio_list) {
1925 bio_list_add(current->bio_list, bio);
1926 return;
1929 /* following loop may be a bit non-obvious, and so deserves some
1930 * explanation.
1931 * Before entering the loop, bio->bi_next is NULL (as all callers
1932 * ensure that) so we have a list with a single bio.
1933 * We pretend that we have just taken it off a longer list, so
1934 * we assign bio_list to a pointer to the bio_list_on_stack,
1935 * thus initialising the bio_list of new bios to be
1936 * added. ->make_request() may indeed add some more bios
1937 * through a recursive call to generic_make_request. If it
1938 * did, we find a non-NULL value in bio_list and re-enter the loop
1939 * from the top. In this case we really did just take the bio
1940 * of the top of the list (no pretending) and so remove it from
1941 * bio_list, and call into ->make_request() again.
1943 BUG_ON(bio->bi_next);
1944 bio_list_init(&bio_list_on_stack);
1945 current->bio_list = &bio_list_on_stack;
1946 do {
1947 struct request_queue *q = bdev_get_queue(bio->bi_bdev);
1949 q->make_request_fn(q, bio);
1951 bio = bio_list_pop(current->bio_list);
1952 } while (bio);
1953 current->bio_list = NULL; /* deactivate */
1955 EXPORT_SYMBOL(generic_make_request);
1958 * submit_bio - submit a bio to the block device layer for I/O
1959 * @rw: whether to %READ or %WRITE, or maybe to %READA (read ahead)
1960 * @bio: The &struct bio which describes the I/O
1962 * submit_bio() is very similar in purpose to generic_make_request(), and
1963 * uses that function to do most of the work. Both are fairly rough
1964 * interfaces; @bio must be presetup and ready for I/O.
1967 void submit_bio(int rw, struct bio *bio)
1969 bio->bi_rw |= rw;
1972 * If it's a regular read/write or a barrier with data attached,
1973 * go through the normal accounting stuff before submission.
1975 if (bio_has_data(bio)) {
1976 unsigned int count;
1978 if (unlikely(rw & REQ_WRITE_SAME))
1979 count = bdev_logical_block_size(bio->bi_bdev) >> 9;
1980 else
1981 count = bio_sectors(bio);
1983 if (rw & WRITE) {
1984 count_vm_events(PGPGOUT, count);
1985 } else {
1986 task_io_account_read(bio->bi_iter.bi_size);
1987 count_vm_events(PGPGIN, count);
1990 if (unlikely(block_dump)) {
1991 char b[BDEVNAME_SIZE];
1992 printk(KERN_DEBUG "%s(%d): %s block %Lu on %s (%u sectors)\n",
1993 current->comm, task_pid_nr(current),
1994 (rw & WRITE) ? "WRITE" : "READ",
1995 (unsigned long long)bio->bi_iter.bi_sector,
1996 bdevname(bio->bi_bdev, b),
1997 count);
2001 generic_make_request(bio);
2003 EXPORT_SYMBOL(submit_bio);
2006 * blk_rq_check_limits - Helper function to check a request for the queue limit
2007 * @q: the queue
2008 * @rq: the request being checked
2010 * Description:
2011 * @rq may have been made based on weaker limitations of upper-level queues
2012 * in request stacking drivers, and it may violate the limitation of @q.
2013 * Since the block layer and the underlying device driver trust @rq
2014 * after it is inserted to @q, it should be checked against @q before
2015 * the insertion using this generic function.
2017 * This function should also be useful for request stacking drivers
2018 * in some cases below, so export this function.
2019 * Request stacking drivers like request-based dm may change the queue
2020 * limits while requests are in the queue (e.g. dm's table swapping).
2021 * Such request stacking drivers should check those requests against
2022 * the new queue limits again when they dispatch those requests,
2023 * although such checkings are also done against the old queue limits
2024 * when submitting requests.
2026 int blk_rq_check_limits(struct request_queue *q, struct request *rq)
2028 if (!rq_mergeable(rq))
2029 return 0;
2031 if (blk_rq_sectors(rq) > blk_queue_get_max_sectors(q, rq->cmd_flags)) {
2032 printk(KERN_ERR "%s: over max size limit.\n", __func__);
2033 return -EIO;
2037 * queue's settings related to segment counting like q->bounce_pfn
2038 * may differ from that of other stacking queues.
2039 * Recalculate it to check the request correctly on this queue's
2040 * limitation.
2042 blk_recalc_rq_segments(rq);
2043 if (rq->nr_phys_segments > queue_max_segments(q)) {
2044 printk(KERN_ERR "%s: over max segments limit.\n", __func__);
2045 return -EIO;
2048 return 0;
2050 EXPORT_SYMBOL_GPL(blk_rq_check_limits);
2053 * blk_insert_cloned_request - Helper for stacking drivers to submit a request
2054 * @q: the queue to submit the request
2055 * @rq: the request being queued
2057 int blk_insert_cloned_request(struct request_queue *q, struct request *rq)
2059 unsigned long flags;
2060 int where = ELEVATOR_INSERT_BACK;
2062 if (blk_rq_check_limits(q, rq))
2063 return -EIO;
2065 if (rq->rq_disk &&
2066 should_fail_request(&rq->rq_disk->part0, blk_rq_bytes(rq)))
2067 return -EIO;
2069 if (q->mq_ops) {
2070 if (blk_queue_io_stat(q))
2071 blk_account_io_start(rq, true);
2072 blk_mq_insert_request(rq, false, true, false);
2073 return 0;
2076 spin_lock_irqsave(q->queue_lock, flags);
2077 if (unlikely(blk_queue_dying(q))) {
2078 spin_unlock_irqrestore(q->queue_lock, flags);
2079 return -ENODEV;
2083 * Submitting request must be dequeued before calling this function
2084 * because it will be linked to another request_queue
2086 BUG_ON(blk_queued_rq(rq));
2088 if (rq->cmd_flags & (REQ_FLUSH|REQ_FUA))
2089 where = ELEVATOR_INSERT_FLUSH;
2091 add_acct_request(q, rq, where);
2092 if (where == ELEVATOR_INSERT_FLUSH)
2093 __blk_run_queue(q);
2094 spin_unlock_irqrestore(q->queue_lock, flags);
2096 return 0;
2098 EXPORT_SYMBOL_GPL(blk_insert_cloned_request);
2101 * blk_rq_err_bytes - determine number of bytes till the next failure boundary
2102 * @rq: request to examine
2104 * Description:
2105 * A request could be merge of IOs which require different failure
2106 * handling. This function determines the number of bytes which
2107 * can be failed from the beginning of the request without
2108 * crossing into area which need to be retried further.
2110 * Return:
2111 * The number of bytes to fail.
2113 * Context:
2114 * queue_lock must be held.
2116 unsigned int blk_rq_err_bytes(const struct request *rq)
2118 unsigned int ff = rq->cmd_flags & REQ_FAILFAST_MASK;
2119 unsigned int bytes = 0;
2120 struct bio *bio;
2122 if (!(rq->cmd_flags & REQ_MIXED_MERGE))
2123 return blk_rq_bytes(rq);
2126 * Currently the only 'mixing' which can happen is between
2127 * different fastfail types. We can safely fail portions
2128 * which have all the failfast bits that the first one has -
2129 * the ones which are at least as eager to fail as the first
2130 * one.
2132 for (bio = rq->bio; bio; bio = bio->bi_next) {
2133 if ((bio->bi_rw & ff) != ff)
2134 break;
2135 bytes += bio->bi_iter.bi_size;
2138 /* this could lead to infinite loop */
2139 BUG_ON(blk_rq_bytes(rq) && !bytes);
2140 return bytes;
2142 EXPORT_SYMBOL_GPL(blk_rq_err_bytes);
2144 void blk_account_io_completion(struct request *req, unsigned int bytes)
2146 if (blk_do_io_stat(req)) {
2147 const int rw = rq_data_dir(req);
2148 struct hd_struct *part;
2149 int cpu;
2151 cpu = part_stat_lock();
2152 part = req->part;
2153 part_stat_add(cpu, part, sectors[rw], bytes >> 9);
2154 part_stat_unlock();
2158 void blk_account_io_done(struct request *req)
2161 * Account IO completion. flush_rq isn't accounted as a
2162 * normal IO on queueing nor completion. Accounting the
2163 * containing request is enough.
2165 if (blk_do_io_stat(req) && !(req->cmd_flags & REQ_FLUSH_SEQ)) {
2166 unsigned long duration = jiffies - req->start_time;
2167 const int rw = rq_data_dir(req);
2168 struct hd_struct *part;
2169 int cpu;
2171 cpu = part_stat_lock();
2172 part = req->part;
2174 part_stat_inc(cpu, part, ios[rw]);
2175 part_stat_add(cpu, part, ticks[rw], duration);
2176 part_round_stats(cpu, part);
2177 part_dec_in_flight(part, rw);
2179 hd_struct_put(part);
2180 part_stat_unlock();
2184 #ifdef CONFIG_PM
2186 * Don't process normal requests when queue is suspended
2187 * or in the process of suspending/resuming
2189 static struct request *blk_pm_peek_request(struct request_queue *q,
2190 struct request *rq)
2192 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
2193 (q->rpm_status != RPM_ACTIVE && !(rq->cmd_flags & REQ_PM))))
2194 return NULL;
2195 else
2196 return rq;
2198 #else
2199 static inline struct request *blk_pm_peek_request(struct request_queue *q,
2200 struct request *rq)
2202 return rq;
2204 #endif
2206 void blk_account_io_start(struct request *rq, bool new_io)
2208 struct hd_struct *part;
2209 int rw = rq_data_dir(rq);
2210 int cpu;
2212 if (!blk_do_io_stat(rq))
2213 return;
2215 cpu = part_stat_lock();
2217 if (!new_io) {
2218 part = rq->part;
2219 part_stat_inc(cpu, part, merges[rw]);
2220 } else {
2221 part = disk_map_sector_rcu(rq->rq_disk, blk_rq_pos(rq));
2222 if (!hd_struct_try_get(part)) {
2224 * The partition is already being removed,
2225 * the request will be accounted on the disk only
2227 * We take a reference on disk->part0 although that
2228 * partition will never be deleted, so we can treat
2229 * it as any other partition.
2231 part = &rq->rq_disk->part0;
2232 hd_struct_get(part);
2234 part_round_stats(cpu, part);
2235 part_inc_in_flight(part, rw);
2236 rq->part = part;
2239 part_stat_unlock();
2243 * blk_peek_request - peek at the top of a request queue
2244 * @q: request queue to peek at
2246 * Description:
2247 * Return the request at the top of @q. The returned request
2248 * should be started using blk_start_request() before LLD starts
2249 * processing it.
2251 * Return:
2252 * Pointer to the request at the top of @q if available. Null
2253 * otherwise.
2255 * Context:
2256 * queue_lock must be held.
2258 struct request *blk_peek_request(struct request_queue *q)
2260 struct request *rq;
2261 int ret;
2263 while ((rq = __elv_next_request(q)) != NULL) {
2265 rq = blk_pm_peek_request(q, rq);
2266 if (!rq)
2267 break;
2269 if (!(rq->cmd_flags & REQ_STARTED)) {
2271 * This is the first time the device driver
2272 * sees this request (possibly after
2273 * requeueing). Notify IO scheduler.
2275 if (rq->cmd_flags & REQ_SORTED)
2276 elv_activate_rq(q, rq);
2279 * just mark as started even if we don't start
2280 * it, a request that has been delayed should
2281 * not be passed by new incoming requests
2283 rq->cmd_flags |= REQ_STARTED;
2284 trace_block_rq_issue(q, rq);
2287 if (!q->boundary_rq || q->boundary_rq == rq) {
2288 q->end_sector = rq_end_sector(rq);
2289 q->boundary_rq = NULL;
2292 if (rq->cmd_flags & REQ_DONTPREP)
2293 break;
2295 if (q->dma_drain_size && blk_rq_bytes(rq)) {
2297 * make sure space for the drain appears we
2298 * know we can do this because max_hw_segments
2299 * has been adjusted to be one fewer than the
2300 * device can handle
2302 rq->nr_phys_segments++;
2305 if (!q->prep_rq_fn)
2306 break;
2308 ret = q->prep_rq_fn(q, rq);
2309 if (ret == BLKPREP_OK) {
2310 break;
2311 } else if (ret == BLKPREP_DEFER) {
2313 * the request may have been (partially) prepped.
2314 * we need to keep this request in the front to
2315 * avoid resource deadlock. REQ_STARTED will
2316 * prevent other fs requests from passing this one.
2318 if (q->dma_drain_size && blk_rq_bytes(rq) &&
2319 !(rq->cmd_flags & REQ_DONTPREP)) {
2321 * remove the space for the drain we added
2322 * so that we don't add it again
2324 --rq->nr_phys_segments;
2327 rq = NULL;
2328 break;
2329 } else if (ret == BLKPREP_KILL) {
2330 rq->cmd_flags |= REQ_QUIET;
2332 * Mark this request as started so we don't trigger
2333 * any debug logic in the end I/O path.
2335 blk_start_request(rq);
2336 __blk_end_request_all(rq, -EIO);
2337 } else {
2338 printk(KERN_ERR "%s: bad return=%d\n", __func__, ret);
2339 break;
2343 return rq;
2345 EXPORT_SYMBOL(blk_peek_request);
2347 void blk_dequeue_request(struct request *rq)
2349 struct request_queue *q = rq->q;
2351 BUG_ON(list_empty(&rq->queuelist));
2352 BUG_ON(ELV_ON_HASH(rq));
2354 list_del_init(&rq->queuelist);
2357 * the time frame between a request being removed from the lists
2358 * and to it is freed is accounted as io that is in progress at
2359 * the driver side.
2361 if (blk_account_rq(rq)) {
2362 q->in_flight[rq_is_sync(rq)]++;
2363 set_io_start_time_ns(rq);
2368 * blk_start_request - start request processing on the driver
2369 * @req: request to dequeue
2371 * Description:
2372 * Dequeue @req and start timeout timer on it. This hands off the
2373 * request to the driver.
2375 * Block internal functions which don't want to start timer should
2376 * call blk_dequeue_request().
2378 * Context:
2379 * queue_lock must be held.
2381 void blk_start_request(struct request *req)
2383 blk_dequeue_request(req);
2386 * We are now handing the request to the hardware, initialize
2387 * resid_len to full count and add the timeout handler.
2389 req->resid_len = blk_rq_bytes(req);
2390 if (unlikely(blk_bidi_rq(req)))
2391 req->next_rq->resid_len = blk_rq_bytes(req->next_rq);
2393 BUG_ON(test_bit(REQ_ATOM_COMPLETE, &req->atomic_flags));
2394 blk_add_timer(req);
2396 EXPORT_SYMBOL(blk_start_request);
2399 * blk_fetch_request - fetch a request from a request queue
2400 * @q: request queue to fetch a request from
2402 * Description:
2403 * Return the request at the top of @q. The request is started on
2404 * return and LLD can start processing it immediately.
2406 * Return:
2407 * Pointer to the request at the top of @q if available. Null
2408 * otherwise.
2410 * Context:
2411 * queue_lock must be held.
2413 struct request *blk_fetch_request(struct request_queue *q)
2415 struct request *rq;
2417 rq = blk_peek_request(q);
2418 if (rq)
2419 blk_start_request(rq);
2420 return rq;
2422 EXPORT_SYMBOL(blk_fetch_request);
2425 * blk_update_request - Special helper function for request stacking drivers
2426 * @req: the request being processed
2427 * @error: %0 for success, < %0 for error
2428 * @nr_bytes: number of bytes to complete @req
2430 * Description:
2431 * Ends I/O on a number of bytes attached to @req, but doesn't complete
2432 * the request structure even if @req doesn't have leftover.
2433 * If @req has leftover, sets it up for the next range of segments.
2435 * This special helper function is only for request stacking drivers
2436 * (e.g. request-based dm) so that they can handle partial completion.
2437 * Actual device drivers should use blk_end_request instead.
2439 * Passing the result of blk_rq_bytes() as @nr_bytes guarantees
2440 * %false return from this function.
2442 * Return:
2443 * %false - this request doesn't have any more data
2444 * %true - this request has more data
2446 bool blk_update_request(struct request *req, int error, unsigned int nr_bytes)
2448 int total_bytes;
2450 trace_block_rq_complete(req->q, req, nr_bytes);
2452 if (!req->bio)
2453 return false;
2456 * For fs requests, rq is just carrier of independent bio's
2457 * and each partial completion should be handled separately.
2458 * Reset per-request error on each partial completion.
2460 * TODO: tj: This is too subtle. It would be better to let
2461 * low level drivers do what they see fit.
2463 if (req->cmd_type == REQ_TYPE_FS)
2464 req->errors = 0;
2466 if (error && req->cmd_type == REQ_TYPE_FS &&
2467 !(req->cmd_flags & REQ_QUIET)) {
2468 char *error_type;
2470 switch (error) {
2471 case -ENOLINK:
2472 error_type = "recoverable transport";
2473 break;
2474 case -EREMOTEIO:
2475 error_type = "critical target";
2476 break;
2477 case -EBADE:
2478 error_type = "critical nexus";
2479 break;
2480 case -ETIMEDOUT:
2481 error_type = "timeout";
2482 break;
2483 case -ENOSPC:
2484 error_type = "critical space allocation";
2485 break;
2486 case -ENODATA:
2487 error_type = "critical medium";
2488 break;
2489 case -EIO:
2490 default:
2491 error_type = "I/O";
2492 break;
2494 printk_ratelimited(KERN_ERR "%s: %s error, dev %s, sector %llu\n",
2495 __func__, error_type, req->rq_disk ?
2496 req->rq_disk->disk_name : "?",
2497 (unsigned long long)blk_rq_pos(req));
2501 blk_account_io_completion(req, nr_bytes);
2503 total_bytes = 0;
2504 while (req->bio) {
2505 struct bio *bio = req->bio;
2506 unsigned bio_bytes = min(bio->bi_iter.bi_size, nr_bytes);
2508 if (bio_bytes == bio->bi_iter.bi_size)
2509 req->bio = bio->bi_next;
2511 req_bio_endio(req, bio, bio_bytes, error);
2513 total_bytes += bio_bytes;
2514 nr_bytes -= bio_bytes;
2516 if (!nr_bytes)
2517 break;
2521 * completely done
2523 if (!req->bio) {
2525 * Reset counters so that the request stacking driver
2526 * can find how many bytes remain in the request
2527 * later.
2529 req->__data_len = 0;
2530 return false;
2533 req->__data_len -= total_bytes;
2535 /* update sector only for requests with clear definition of sector */
2536 if (req->cmd_type == REQ_TYPE_FS)
2537 req->__sector += total_bytes >> 9;
2539 /* mixed attributes always follow the first bio */
2540 if (req->cmd_flags & REQ_MIXED_MERGE) {
2541 req->cmd_flags &= ~REQ_FAILFAST_MASK;
2542 req->cmd_flags |= req->bio->bi_rw & REQ_FAILFAST_MASK;
2546 * If total number of sectors is less than the first segment
2547 * size, something has gone terribly wrong.
2549 if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {
2550 blk_dump_rq_flags(req, "request botched");
2551 req->__data_len = blk_rq_cur_bytes(req);
2554 /* recalculate the number of segments */
2555 blk_recalc_rq_segments(req);
2557 return true;
2559 EXPORT_SYMBOL_GPL(blk_update_request);
2561 static bool blk_update_bidi_request(struct request *rq, int error,
2562 unsigned int nr_bytes,
2563 unsigned int bidi_bytes)
2565 if (blk_update_request(rq, error, nr_bytes))
2566 return true;
2568 /* Bidi request must be completed as a whole */
2569 if (unlikely(blk_bidi_rq(rq)) &&
2570 blk_update_request(rq->next_rq, error, bidi_bytes))
2571 return true;
2573 if (blk_queue_add_random(rq->q))
2574 add_disk_randomness(rq->rq_disk);
2576 return false;
2580 * blk_unprep_request - unprepare a request
2581 * @req: the request
2583 * This function makes a request ready for complete resubmission (or
2584 * completion). It happens only after all error handling is complete,
2585 * so represents the appropriate moment to deallocate any resources
2586 * that were allocated to the request in the prep_rq_fn. The queue
2587 * lock is held when calling this.
2589 void blk_unprep_request(struct request *req)
2591 struct request_queue *q = req->q;
2593 req->cmd_flags &= ~REQ_DONTPREP;
2594 if (q->unprep_rq_fn)
2595 q->unprep_rq_fn(q, req);
2597 EXPORT_SYMBOL_GPL(blk_unprep_request);
2600 * queue lock must be held
2602 void blk_finish_request(struct request *req, int error)
2604 if (req->cmd_flags & REQ_QUEUED)
2605 blk_queue_end_tag(req->q, req);
2607 BUG_ON(blk_queued_rq(req));
2609 if (unlikely(laptop_mode) && req->cmd_type == REQ_TYPE_FS)
2610 laptop_io_completion(&req->q->backing_dev_info);
2612 blk_delete_timer(req);
2614 if (req->cmd_flags & REQ_DONTPREP)
2615 blk_unprep_request(req);
2617 blk_account_io_done(req);
2619 if (req->end_io)
2620 req->end_io(req, error);
2621 else {
2622 if (blk_bidi_rq(req))
2623 __blk_put_request(req->next_rq->q, req->next_rq);
2625 __blk_put_request(req->q, req);
2628 EXPORT_SYMBOL(blk_finish_request);
2631 * blk_end_bidi_request - Complete a bidi request
2632 * @rq: the request to complete
2633 * @error: %0 for success, < %0 for error
2634 * @nr_bytes: number of bytes to complete @rq
2635 * @bidi_bytes: number of bytes to complete @rq->next_rq
2637 * Description:
2638 * Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
2639 * Drivers that supports bidi can safely call this member for any
2640 * type of request, bidi or uni. In the later case @bidi_bytes is
2641 * just ignored.
2643 * Return:
2644 * %false - we are done with this request
2645 * %true - still buffers pending for this request
2647 static bool blk_end_bidi_request(struct request *rq, int error,
2648 unsigned int nr_bytes, unsigned int bidi_bytes)
2650 struct request_queue *q = rq->q;
2651 unsigned long flags;
2653 if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2654 return true;
2656 spin_lock_irqsave(q->queue_lock, flags);
2657 blk_finish_request(rq, error);
2658 spin_unlock_irqrestore(q->queue_lock, flags);
2660 return false;
2664 * __blk_end_bidi_request - Complete a bidi request with queue lock held
2665 * @rq: the request to complete
2666 * @error: %0 for success, < %0 for error
2667 * @nr_bytes: number of bytes to complete @rq
2668 * @bidi_bytes: number of bytes to complete @rq->next_rq
2670 * Description:
2671 * Identical to blk_end_bidi_request() except that queue lock is
2672 * assumed to be locked on entry and remains so on return.
2674 * Return:
2675 * %false - we are done with this request
2676 * %true - still buffers pending for this request
2678 bool __blk_end_bidi_request(struct request *rq, int error,
2679 unsigned int nr_bytes, unsigned int bidi_bytes)
2681 if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2682 return true;
2684 blk_finish_request(rq, error);
2686 return false;
2690 * blk_end_request - Helper function for drivers to complete the request.
2691 * @rq: the request being processed
2692 * @error: %0 for success, < %0 for error
2693 * @nr_bytes: number of bytes to complete
2695 * Description:
2696 * Ends I/O on a number of bytes attached to @rq.
2697 * If @rq has leftover, sets it up for the next range of segments.
2699 * Return:
2700 * %false - we are done with this request
2701 * %true - still buffers pending for this request
2703 bool blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
2705 return blk_end_bidi_request(rq, error, nr_bytes, 0);
2707 EXPORT_SYMBOL(blk_end_request);
2710 * blk_end_request_all - Helper function for drives to finish the request.
2711 * @rq: the request to finish
2712 * @error: %0 for success, < %0 for error
2714 * Description:
2715 * Completely finish @rq.
2717 void blk_end_request_all(struct request *rq, int error)
2719 bool pending;
2720 unsigned int bidi_bytes = 0;
2722 if (unlikely(blk_bidi_rq(rq)))
2723 bidi_bytes = blk_rq_bytes(rq->next_rq);
2725 pending = blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2726 BUG_ON(pending);
2728 EXPORT_SYMBOL(blk_end_request_all);
2731 * blk_end_request_cur - Helper function to finish the current request chunk.
2732 * @rq: the request to finish the current chunk for
2733 * @error: %0 for success, < %0 for error
2735 * Description:
2736 * Complete the current consecutively mapped chunk from @rq.
2738 * Return:
2739 * %false - we are done with this request
2740 * %true - still buffers pending for this request
2742 bool blk_end_request_cur(struct request *rq, int error)
2744 return blk_end_request(rq, error, blk_rq_cur_bytes(rq));
2746 EXPORT_SYMBOL(blk_end_request_cur);
2749 * blk_end_request_err - Finish a request till the next failure boundary.
2750 * @rq: the request to finish till the next failure boundary for
2751 * @error: must be negative errno
2753 * Description:
2754 * Complete @rq till the next failure boundary.
2756 * Return:
2757 * %false - we are done with this request
2758 * %true - still buffers pending for this request
2760 bool blk_end_request_err(struct request *rq, int error)
2762 WARN_ON(error >= 0);
2763 return blk_end_request(rq, error, blk_rq_err_bytes(rq));
2765 EXPORT_SYMBOL_GPL(blk_end_request_err);
2768 * __blk_end_request - Helper function for drivers to complete the request.
2769 * @rq: the request being processed
2770 * @error: %0 for success, < %0 for error
2771 * @nr_bytes: number of bytes to complete
2773 * Description:
2774 * Must be called with queue lock held unlike blk_end_request().
2776 * Return:
2777 * %false - we are done with this request
2778 * %true - still buffers pending for this request
2780 bool __blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
2782 return __blk_end_bidi_request(rq, error, nr_bytes, 0);
2784 EXPORT_SYMBOL(__blk_end_request);
2787 * __blk_end_request_all - Helper function for drives to finish the request.
2788 * @rq: the request to finish
2789 * @error: %0 for success, < %0 for error
2791 * Description:
2792 * Completely finish @rq. Must be called with queue lock held.
2794 void __blk_end_request_all(struct request *rq, int error)
2796 bool pending;
2797 unsigned int bidi_bytes = 0;
2799 if (unlikely(blk_bidi_rq(rq)))
2800 bidi_bytes = blk_rq_bytes(rq->next_rq);
2802 pending = __blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2803 BUG_ON(pending);
2805 EXPORT_SYMBOL(__blk_end_request_all);
2808 * __blk_end_request_cur - Helper function to finish the current request chunk.
2809 * @rq: the request to finish the current chunk for
2810 * @error: %0 for success, < %0 for error
2812 * Description:
2813 * Complete the current consecutively mapped chunk from @rq. Must
2814 * be called with queue lock held.
2816 * Return:
2817 * %false - we are done with this request
2818 * %true - still buffers pending for this request
2820 bool __blk_end_request_cur(struct request *rq, int error)
2822 return __blk_end_request(rq, error, blk_rq_cur_bytes(rq));
2824 EXPORT_SYMBOL(__blk_end_request_cur);
2827 * __blk_end_request_err - Finish a request till the next failure boundary.
2828 * @rq: the request to finish till the next failure boundary for
2829 * @error: must be negative errno
2831 * Description:
2832 * Complete @rq till the next failure boundary. Must be called
2833 * with queue lock held.
2835 * Return:
2836 * %false - we are done with this request
2837 * %true - still buffers pending for this request
2839 bool __blk_end_request_err(struct request *rq, int error)
2841 WARN_ON(error >= 0);
2842 return __blk_end_request(rq, error, blk_rq_err_bytes(rq));
2844 EXPORT_SYMBOL_GPL(__blk_end_request_err);
2846 void blk_rq_bio_prep(struct request_queue *q, struct request *rq,
2847 struct bio *bio)
2849 /* Bit 0 (R/W) is identical in rq->cmd_flags and bio->bi_rw */
2850 rq->cmd_flags |= bio->bi_rw & REQ_WRITE;
2852 if (bio_has_data(bio))
2853 rq->nr_phys_segments = bio_phys_segments(q, bio);
2855 rq->__data_len = bio->bi_iter.bi_size;
2856 rq->bio = rq->biotail = bio;
2858 if (bio->bi_bdev)
2859 rq->rq_disk = bio->bi_bdev->bd_disk;
2862 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE
2864 * rq_flush_dcache_pages - Helper function to flush all pages in a request
2865 * @rq: the request to be flushed
2867 * Description:
2868 * Flush all pages in @rq.
2870 void rq_flush_dcache_pages(struct request *rq)
2872 struct req_iterator iter;
2873 struct bio_vec bvec;
2875 rq_for_each_segment(bvec, rq, iter)
2876 flush_dcache_page(bvec.bv_page);
2878 EXPORT_SYMBOL_GPL(rq_flush_dcache_pages);
2879 #endif
2882 * blk_lld_busy - Check if underlying low-level drivers of a device are busy
2883 * @q : the queue of the device being checked
2885 * Description:
2886 * Check if underlying low-level drivers of a device are busy.
2887 * If the drivers want to export their busy state, they must set own
2888 * exporting function using blk_queue_lld_busy() first.
2890 * Basically, this function is used only by request stacking drivers
2891 * to stop dispatching requests to underlying devices when underlying
2892 * devices are busy. This behavior helps more I/O merging on the queue
2893 * of the request stacking driver and prevents I/O throughput regression
2894 * on burst I/O load.
2896 * Return:
2897 * 0 - Not busy (The request stacking driver should dispatch request)
2898 * 1 - Busy (The request stacking driver should stop dispatching request)
2900 int blk_lld_busy(struct request_queue *q)
2902 if (q->lld_busy_fn)
2903 return q->lld_busy_fn(q);
2905 return 0;
2907 EXPORT_SYMBOL_GPL(blk_lld_busy);
2910 * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
2911 * @rq: the clone request to be cleaned up
2913 * Description:
2914 * Free all bios in @rq for a cloned request.
2916 void blk_rq_unprep_clone(struct request *rq)
2918 struct bio *bio;
2920 while ((bio = rq->bio) != NULL) {
2921 rq->bio = bio->bi_next;
2923 bio_put(bio);
2926 EXPORT_SYMBOL_GPL(blk_rq_unprep_clone);
2929 * Copy attributes of the original request to the clone request.
2930 * The actual data parts (e.g. ->cmd, ->sense) are not copied.
2932 static void __blk_rq_prep_clone(struct request *dst, struct request *src)
2934 dst->cpu = src->cpu;
2935 dst->cmd_flags |= (src->cmd_flags & REQ_CLONE_MASK) | REQ_NOMERGE;
2936 dst->cmd_type = src->cmd_type;
2937 dst->__sector = blk_rq_pos(src);
2938 dst->__data_len = blk_rq_bytes(src);
2939 dst->nr_phys_segments = src->nr_phys_segments;
2940 dst->ioprio = src->ioprio;
2941 dst->extra_len = src->extra_len;
2945 * blk_rq_prep_clone - Helper function to setup clone request
2946 * @rq: the request to be setup
2947 * @rq_src: original request to be cloned
2948 * @bs: bio_set that bios for clone are allocated from
2949 * @gfp_mask: memory allocation mask for bio
2950 * @bio_ctr: setup function to be called for each clone bio.
2951 * Returns %0 for success, non %0 for failure.
2952 * @data: private data to be passed to @bio_ctr
2954 * Description:
2955 * Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
2956 * The actual data parts of @rq_src (e.g. ->cmd, ->sense)
2957 * are not copied, and copying such parts is the caller's responsibility.
2958 * Also, pages which the original bios are pointing to are not copied
2959 * and the cloned bios just point same pages.
2960 * So cloned bios must be completed before original bios, which means
2961 * the caller must complete @rq before @rq_src.
2963 int blk_rq_prep_clone(struct request *rq, struct request *rq_src,
2964 struct bio_set *bs, gfp_t gfp_mask,
2965 int (*bio_ctr)(struct bio *, struct bio *, void *),
2966 void *data)
2968 struct bio *bio, *bio_src;
2970 if (!bs)
2971 bs = fs_bio_set;
2973 __rq_for_each_bio(bio_src, rq_src) {
2974 bio = bio_clone_fast(bio_src, gfp_mask, bs);
2975 if (!bio)
2976 goto free_and_out;
2978 if (bio_ctr && bio_ctr(bio, bio_src, data))
2979 goto free_and_out;
2981 if (rq->bio) {
2982 rq->biotail->bi_next = bio;
2983 rq->biotail = bio;
2984 } else
2985 rq->bio = rq->biotail = bio;
2988 __blk_rq_prep_clone(rq, rq_src);
2990 return 0;
2992 free_and_out:
2993 if (bio)
2994 bio_put(bio);
2995 blk_rq_unprep_clone(rq);
2997 return -ENOMEM;
2999 EXPORT_SYMBOL_GPL(blk_rq_prep_clone);
3001 int kblockd_schedule_work(struct work_struct *work)
3003 return queue_work(kblockd_workqueue, work);
3005 EXPORT_SYMBOL(kblockd_schedule_work);
3007 int kblockd_schedule_delayed_work(struct delayed_work *dwork,
3008 unsigned long delay)
3010 return queue_delayed_work(kblockd_workqueue, dwork, delay);
3012 EXPORT_SYMBOL(kblockd_schedule_delayed_work);
3014 int kblockd_schedule_delayed_work_on(int cpu, struct delayed_work *dwork,
3015 unsigned long delay)
3017 return queue_delayed_work_on(cpu, kblockd_workqueue, dwork, delay);
3019 EXPORT_SYMBOL(kblockd_schedule_delayed_work_on);
3022 * blk_start_plug - initialize blk_plug and track it inside the task_struct
3023 * @plug: The &struct blk_plug that needs to be initialized
3025 * Description:
3026 * Tracking blk_plug inside the task_struct will help with auto-flushing the
3027 * pending I/O should the task end up blocking between blk_start_plug() and
3028 * blk_finish_plug(). This is important from a performance perspective, but
3029 * also ensures that we don't deadlock. For instance, if the task is blocking
3030 * for a memory allocation, memory reclaim could end up wanting to free a
3031 * page belonging to that request that is currently residing in our private
3032 * plug. By flushing the pending I/O when the process goes to sleep, we avoid
3033 * this kind of deadlock.
3035 void blk_start_plug(struct blk_plug *plug)
3037 struct task_struct *tsk = current;
3039 INIT_LIST_HEAD(&plug->list);
3040 INIT_LIST_HEAD(&plug->mq_list);
3041 INIT_LIST_HEAD(&plug->cb_list);
3044 * If this is a nested plug, don't actually assign it. It will be
3045 * flushed on its own.
3047 if (!tsk->plug) {
3049 * Store ordering should not be needed here, since a potential
3050 * preempt will imply a full memory barrier
3052 tsk->plug = plug;
3055 EXPORT_SYMBOL(blk_start_plug);
3057 static int plug_rq_cmp(void *priv, struct list_head *a, struct list_head *b)
3059 struct request *rqa = container_of(a, struct request, queuelist);
3060 struct request *rqb = container_of(b, struct request, queuelist);
3062 return !(rqa->q < rqb->q ||
3063 (rqa->q == rqb->q && blk_rq_pos(rqa) < blk_rq_pos(rqb)));
3067 * If 'from_schedule' is true, then postpone the dispatch of requests
3068 * until a safe kblockd context. We due this to avoid accidental big
3069 * additional stack usage in driver dispatch, in places where the originally
3070 * plugger did not intend it.
3072 static void queue_unplugged(struct request_queue *q, unsigned int depth,
3073 bool from_schedule)
3074 __releases(q->queue_lock)
3076 trace_block_unplug(q, depth, !from_schedule);
3078 if (from_schedule)
3079 blk_run_queue_async(q);
3080 else
3081 __blk_run_queue(q);
3082 spin_unlock(q->queue_lock);
3085 static void flush_plug_callbacks(struct blk_plug *plug, bool from_schedule)
3087 LIST_HEAD(callbacks);
3089 while (!list_empty(&plug->cb_list)) {
3090 list_splice_init(&plug->cb_list, &callbacks);
3092 while (!list_empty(&callbacks)) {
3093 struct blk_plug_cb *cb = list_first_entry(&callbacks,
3094 struct blk_plug_cb,
3095 list);
3096 list_del(&cb->list);
3097 cb->callback(cb, from_schedule);
3102 struct blk_plug_cb *blk_check_plugged(blk_plug_cb_fn unplug, void *data,
3103 int size)
3105 struct blk_plug *plug = current->plug;
3106 struct blk_plug_cb *cb;
3108 if (!plug)
3109 return NULL;
3111 list_for_each_entry(cb, &plug->cb_list, list)
3112 if (cb->callback == unplug && cb->data == data)
3113 return cb;
3115 /* Not currently on the callback list */
3116 BUG_ON(size < sizeof(*cb));
3117 cb = kzalloc(size, GFP_ATOMIC);
3118 if (cb) {
3119 cb->data = data;
3120 cb->callback = unplug;
3121 list_add(&cb->list, &plug->cb_list);
3123 return cb;
3125 EXPORT_SYMBOL(blk_check_plugged);
3127 void blk_flush_plug_list(struct blk_plug *plug, bool from_schedule)
3129 struct request_queue *q;
3130 unsigned long flags;
3131 struct request *rq;
3132 LIST_HEAD(list);
3133 unsigned int depth;
3135 flush_plug_callbacks(plug, from_schedule);
3137 if (!list_empty(&plug->mq_list))
3138 blk_mq_flush_plug_list(plug, from_schedule);
3140 if (list_empty(&plug->list))
3141 return;
3143 list_splice_init(&plug->list, &list);
3145 list_sort(NULL, &list, plug_rq_cmp);
3147 q = NULL;
3148 depth = 0;
3151 * Save and disable interrupts here, to avoid doing it for every
3152 * queue lock we have to take.
3154 local_irq_save(flags);
3155 while (!list_empty(&list)) {
3156 rq = list_entry_rq(list.next);
3157 list_del_init(&rq->queuelist);
3158 BUG_ON(!rq->q);
3159 if (rq->q != q) {
3161 * This drops the queue lock
3163 if (q)
3164 queue_unplugged(q, depth, from_schedule);
3165 q = rq->q;
3166 depth = 0;
3167 spin_lock(q->queue_lock);
3171 * Short-circuit if @q is dead
3173 if (unlikely(blk_queue_dying(q))) {
3174 __blk_end_request_all(rq, -ENODEV);
3175 continue;
3179 * rq is already accounted, so use raw insert
3181 if (rq->cmd_flags & (REQ_FLUSH | REQ_FUA))
3182 __elv_add_request(q, rq, ELEVATOR_INSERT_FLUSH);
3183 else
3184 __elv_add_request(q, rq, ELEVATOR_INSERT_SORT_MERGE);
3186 depth++;
3190 * This drops the queue lock
3192 if (q)
3193 queue_unplugged(q, depth, from_schedule);
3195 local_irq_restore(flags);
3198 void blk_finish_plug(struct blk_plug *plug)
3200 blk_flush_plug_list(plug, false);
3202 if (plug == current->plug)
3203 current->plug = NULL;
3205 EXPORT_SYMBOL(blk_finish_plug);
3207 #ifdef CONFIG_PM
3209 * blk_pm_runtime_init - Block layer runtime PM initialization routine
3210 * @q: the queue of the device
3211 * @dev: the device the queue belongs to
3213 * Description:
3214 * Initialize runtime-PM-related fields for @q and start auto suspend for
3215 * @dev. Drivers that want to take advantage of request-based runtime PM
3216 * should call this function after @dev has been initialized, and its
3217 * request queue @q has been allocated, and runtime PM for it can not happen
3218 * yet(either due to disabled/forbidden or its usage_count > 0). In most
3219 * cases, driver should call this function before any I/O has taken place.
3221 * This function takes care of setting up using auto suspend for the device,
3222 * the autosuspend delay is set to -1 to make runtime suspend impossible
3223 * until an updated value is either set by user or by driver. Drivers do
3224 * not need to touch other autosuspend settings.
3226 * The block layer runtime PM is request based, so only works for drivers
3227 * that use request as their IO unit instead of those directly use bio's.
3229 void blk_pm_runtime_init(struct request_queue *q, struct device *dev)
3231 q->dev = dev;
3232 q->rpm_status = RPM_ACTIVE;
3233 pm_runtime_set_autosuspend_delay(q->dev, -1);
3234 pm_runtime_use_autosuspend(q->dev);
3236 EXPORT_SYMBOL(blk_pm_runtime_init);
3239 * blk_pre_runtime_suspend - Pre runtime suspend check
3240 * @q: the queue of the device
3242 * Description:
3243 * This function will check if runtime suspend is allowed for the device
3244 * by examining if there are any requests pending in the queue. If there
3245 * are requests pending, the device can not be runtime suspended; otherwise,
3246 * the queue's status will be updated to SUSPENDING and the driver can
3247 * proceed to suspend the device.
3249 * For the not allowed case, we mark last busy for the device so that
3250 * runtime PM core will try to autosuspend it some time later.
3252 * This function should be called near the start of the device's
3253 * runtime_suspend callback.
3255 * Return:
3256 * 0 - OK to runtime suspend the device
3257 * -EBUSY - Device should not be runtime suspended
3259 int blk_pre_runtime_suspend(struct request_queue *q)
3261 int ret = 0;
3263 spin_lock_irq(q->queue_lock);
3264 if (q->nr_pending) {
3265 ret = -EBUSY;
3266 pm_runtime_mark_last_busy(q->dev);
3267 } else {
3268 q->rpm_status = RPM_SUSPENDING;
3270 spin_unlock_irq(q->queue_lock);
3271 return ret;
3273 EXPORT_SYMBOL(blk_pre_runtime_suspend);
3276 * blk_post_runtime_suspend - Post runtime suspend processing
3277 * @q: the queue of the device
3278 * @err: return value of the device's runtime_suspend function
3280 * Description:
3281 * Update the queue's runtime status according to the return value of the
3282 * device's runtime suspend function and mark last busy for the device so
3283 * that PM core will try to auto suspend the device at a later time.
3285 * This function should be called near the end of the device's
3286 * runtime_suspend callback.
3288 void blk_post_runtime_suspend(struct request_queue *q, int err)
3290 spin_lock_irq(q->queue_lock);
3291 if (!err) {
3292 q->rpm_status = RPM_SUSPENDED;
3293 } else {
3294 q->rpm_status = RPM_ACTIVE;
3295 pm_runtime_mark_last_busy(q->dev);
3297 spin_unlock_irq(q->queue_lock);
3299 EXPORT_SYMBOL(blk_post_runtime_suspend);
3302 * blk_pre_runtime_resume - Pre runtime resume processing
3303 * @q: the queue of the device
3305 * Description:
3306 * Update the queue's runtime status to RESUMING in preparation for the
3307 * runtime resume of the device.
3309 * This function should be called near the start of the device's
3310 * runtime_resume callback.
3312 void blk_pre_runtime_resume(struct request_queue *q)
3314 spin_lock_irq(q->queue_lock);
3315 q->rpm_status = RPM_RESUMING;
3316 spin_unlock_irq(q->queue_lock);
3318 EXPORT_SYMBOL(blk_pre_runtime_resume);
3321 * blk_post_runtime_resume - Post runtime resume processing
3322 * @q: the queue of the device
3323 * @err: return value of the device's runtime_resume function
3325 * Description:
3326 * Update the queue's runtime status according to the return value of the
3327 * device's runtime_resume function. If it is successfully resumed, process
3328 * the requests that are queued into the device's queue when it is resuming
3329 * and then mark last busy and initiate autosuspend for it.
3331 * This function should be called near the end of the device's
3332 * runtime_resume callback.
3334 void blk_post_runtime_resume(struct request_queue *q, int err)
3336 spin_lock_irq(q->queue_lock);
3337 if (!err) {
3338 q->rpm_status = RPM_ACTIVE;
3339 __blk_run_queue(q);
3340 pm_runtime_mark_last_busy(q->dev);
3341 pm_request_autosuspend(q->dev);
3342 } else {
3343 q->rpm_status = RPM_SUSPENDED;
3345 spin_unlock_irq(q->queue_lock);
3347 EXPORT_SYMBOL(blk_post_runtime_resume);
3348 #endif
3350 int __init blk_dev_init(void)
3352 BUILD_BUG_ON(__REQ_NR_BITS > 8 *
3353 sizeof(((struct request *)0)->cmd_flags));
3355 /* used for unplugging and affects IO latency/throughput - HIGHPRI */
3356 kblockd_workqueue = alloc_workqueue("kblockd",
3357 WQ_MEM_RECLAIM | WQ_HIGHPRI, 0);
3358 if (!kblockd_workqueue)
3359 panic("Failed to create kblockd\n");
3361 request_cachep = kmem_cache_create("blkdev_requests",
3362 sizeof(struct request), 0, SLAB_PANIC, NULL);
3364 blk_requestq_cachep = kmem_cache_create("blkdev_queue",
3365 sizeof(struct request_queue), 0, SLAB_PANIC, NULL);
3367 return 0;