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>
8 * bio rewrite, highmem i/o, etc, Jens Axboe <axboe@suse.de> - may 2001
12 * This handles all read/write requests to block devices
15 #ifdef CONFIG_BLOCK_PERF_FRAMEWORK
16 #define DRIVER_NAME "Block"
17 #define pr_fmt(fmt) DRIVER_NAME ": %s: " fmt, __func__
20 #include <linux/kernel.h>
21 #include <linux/module.h>
22 #include <linux/backing-dev.h>
23 #include <linux/bio.h>
24 #include <linux/blkdev.h>
25 #include <linux/blk-mq.h>
26 #include <linux/highmem.h>
28 #include <linux/kernel_stat.h>
29 #include <linux/string.h>
30 #include <linux/init.h>
31 #include <linux/completion.h>
32 #include <linux/slab.h>
33 #include <linux/swap.h>
34 #include <linux/writeback.h>
35 #include <linux/task_io_accounting_ops.h>
36 #include <linux/fault-inject.h>
37 #include <linux/list_sort.h>
38 #include <linux/delay.h>
39 #include <linux/ratelimit.h>
40 #include <linux/pm_runtime.h>
41 #include <linux/blk-cgroup.h>
43 #ifdef CONFIG_BLOCK_PERF_FRAMEWORK
44 #include <linux/ktime.h>
45 #include <linux/spinlock.h>
46 #include <linux/debugfs.h>
49 #define CREATE_TRACE_POINTS
50 #include <trace/events/block.h>
55 #include <linux/math64.h>
57 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_remap);
58 EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_remap);
59 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_complete);
60 EXPORT_TRACEPOINT_SYMBOL_GPL(block_split);
61 EXPORT_TRACEPOINT_SYMBOL_GPL(block_unplug);
63 DEFINE_IDA(blk_queue_ida);
66 * For the allocated request tables
68 struct kmem_cache *request_cachep = NULL;
71 * For queue allocation
73 struct kmem_cache *blk_requestq_cachep;
76 * Controlling structure to kblockd
78 static struct workqueue_struct *kblockd_workqueue;
80 static void blk_clear_congested(struct request_list *rl, int sync)
82 #ifdef CONFIG_CGROUP_WRITEBACK
83 clear_wb_congested(rl->blkg->wb_congested, sync);
86 * If !CGROUP_WRITEBACK, all blkg's map to bdi->wb and we shouldn't
87 * flip its congestion state for events on other blkcgs.
89 if (rl == &rl->q->root_rl)
90 clear_wb_congested(rl->q->backing_dev_info.wb.congested, sync);
94 static void blk_set_congested(struct request_list *rl, int sync)
96 #ifdef CONFIG_CGROUP_WRITEBACK
97 set_wb_congested(rl->blkg->wb_congested, sync);
99 /* see blk_clear_congested() */
100 if (rl == &rl->q->root_rl)
101 set_wb_congested(rl->q->backing_dev_info.wb.congested, sync);
105 void blk_queue_congestion_threshold(struct request_queue *q)
109 nr = q->nr_requests - (q->nr_requests / 8) + 1;
110 if (nr > q->nr_requests)
112 q->nr_congestion_on = nr;
114 nr = q->nr_requests - (q->nr_requests / 8) - (q->nr_requests / 16) - 1;
117 q->nr_congestion_off = nr;
121 * blk_get_backing_dev_info - get the address of a queue's backing_dev_info
124 * Locates the passed device's request queue and returns the address of its
125 * backing_dev_info. This function can only be called if @bdev is opened
126 * and the return value is never NULL.
128 struct backing_dev_info *blk_get_backing_dev_info(struct block_device *bdev)
130 struct request_queue *q = bdev_get_queue(bdev);
132 return &q->backing_dev_info;
134 EXPORT_SYMBOL(blk_get_backing_dev_info);
136 void blk_rq_init(struct request_queue *q, struct request *rq)
138 memset(rq, 0, sizeof(*rq));
140 INIT_LIST_HEAD(&rq->queuelist);
141 INIT_LIST_HEAD(&rq->timeout_list);
144 rq->__sector = (sector_t) -1;
145 INIT_HLIST_NODE(&rq->hash);
146 RB_CLEAR_NODE(&rq->rb_node);
148 rq->cmd_len = BLK_MAX_CDB;
150 rq->start_time = jiffies;
151 set_start_time_ns(rq);
154 EXPORT_SYMBOL(blk_rq_init);
156 static void req_bio_endio(struct request *rq, struct bio *bio,
157 unsigned int nbytes, int error)
160 bio->bi_error = error;
162 if (unlikely(rq->cmd_flags & REQ_QUIET))
163 bio_set_flag(bio, BIO_QUIET);
165 bio_advance(bio, nbytes);
167 /* don't actually finish bio if it's part of flush sequence */
168 if (bio->bi_iter.bi_size == 0 && !(rq->cmd_flags & REQ_FLUSH_SEQ))
172 void blk_dump_rq_flags(struct request *rq, char *msg)
176 printk(KERN_INFO "%s: dev %s: type=%x, flags=%llx\n", msg,
177 rq->rq_disk ? rq->rq_disk->disk_name : "?", rq->cmd_type,
178 (unsigned long long) rq->cmd_flags);
180 printk(KERN_INFO " sector %llu, nr/cnr %u/%u\n",
181 (unsigned long long)blk_rq_pos(rq),
182 blk_rq_sectors(rq), blk_rq_cur_sectors(rq));
183 printk(KERN_INFO " bio %p, biotail %p, len %u\n",
184 rq->bio, rq->biotail, blk_rq_bytes(rq));
186 if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
187 printk(KERN_INFO " cdb: ");
188 for (bit = 0; bit < BLK_MAX_CDB; bit++)
189 printk("%02x ", rq->cmd[bit]);
193 EXPORT_SYMBOL(blk_dump_rq_flags);
195 static void blk_delay_work(struct work_struct *work)
197 struct request_queue *q;
199 q = container_of(work, struct request_queue, delay_work.work);
200 spin_lock_irq(q->queue_lock);
202 spin_unlock_irq(q->queue_lock);
206 * blk_delay_queue - restart queueing after defined interval
207 * @q: The &struct request_queue in question
208 * @msecs: Delay in msecs
211 * Sometimes queueing needs to be postponed for a little while, to allow
212 * resources to come back. This function will make sure that queueing is
213 * restarted around the specified time. Queue lock must be held.
215 void blk_delay_queue(struct request_queue *q, unsigned long msecs)
217 if (likely(!blk_queue_dead(q)))
218 queue_delayed_work(kblockd_workqueue, &q->delay_work,
219 msecs_to_jiffies(msecs));
221 EXPORT_SYMBOL(blk_delay_queue);
224 * blk_start_queue_async - asynchronously restart a previously stopped queue
225 * @q: The &struct request_queue in question
228 * blk_start_queue_async() will clear the stop flag on the queue, and
229 * ensure that the request_fn for the queue is run from an async
232 void blk_start_queue_async(struct request_queue *q)
234 queue_flag_clear(QUEUE_FLAG_STOPPED, q);
235 blk_run_queue_async(q);
237 EXPORT_SYMBOL(blk_start_queue_async);
240 * blk_start_queue - restart a previously stopped queue
241 * @q: The &struct request_queue in question
244 * blk_start_queue() will clear the stop flag on the queue, and call
245 * the request_fn for the queue if it was in a stopped state when
246 * entered. Also see blk_stop_queue(). Queue lock must be held.
248 void blk_start_queue(struct request_queue *q)
250 WARN_ON(!irqs_disabled());
252 queue_flag_clear(QUEUE_FLAG_STOPPED, q);
255 EXPORT_SYMBOL(blk_start_queue);
258 * blk_stop_queue - stop a queue
259 * @q: The &struct request_queue in question
262 * The Linux block layer assumes that a block driver will consume all
263 * entries on the request queue when the request_fn strategy is called.
264 * Often this will not happen, because of hardware limitations (queue
265 * depth settings). If a device driver gets a 'queue full' response,
266 * or if it simply chooses not to queue more I/O at one point, it can
267 * call this function to prevent the request_fn from being called until
268 * the driver has signalled it's ready to go again. This happens by calling
269 * blk_start_queue() to restart queue operations. Queue lock must be held.
271 void blk_stop_queue(struct request_queue *q)
273 cancel_delayed_work(&q->delay_work);
274 queue_flag_set(QUEUE_FLAG_STOPPED, q);
276 EXPORT_SYMBOL(blk_stop_queue);
279 * blk_sync_queue - cancel any pending callbacks on a queue
283 * The block layer may perform asynchronous callback activity
284 * on a queue, such as calling the unplug function after a timeout.
285 * A block device may call blk_sync_queue to ensure that any
286 * such activity is cancelled, thus allowing it to release resources
287 * that the callbacks might use. The caller must already have made sure
288 * that its ->make_request_fn will not re-add plugging prior to calling
291 * This function does not cancel any asynchronous activity arising
292 * out of elevator or throttling code. That would require elevator_exit()
293 * and blkcg_exit_queue() to be called with queue lock initialized.
296 void blk_sync_queue(struct request_queue *q)
298 del_timer_sync(&q->timeout);
301 struct blk_mq_hw_ctx *hctx;
304 queue_for_each_hw_ctx(q, hctx, i) {
305 cancel_delayed_work_sync(&hctx->run_work);
306 cancel_delayed_work_sync(&hctx->delay_work);
309 cancel_delayed_work_sync(&q->delay_work);
312 EXPORT_SYMBOL(blk_sync_queue);
315 * __blk_run_queue_uncond - run a queue whether or not it has been stopped
316 * @q: The queue to run
319 * Invoke request handling on a queue if there are any pending requests.
320 * May be used to restart request handling after a request has completed.
321 * This variant runs the queue whether or not the queue has been
322 * stopped. Must be called with the queue lock held and interrupts
323 * disabled. See also @blk_run_queue.
325 inline void __blk_run_queue_uncond(struct request_queue *q)
327 if (unlikely(blk_queue_dead(q)))
331 * Some request_fn implementations, e.g. scsi_request_fn(), unlock
332 * the queue lock internally. As a result multiple threads may be
333 * running such a request function concurrently. Keep track of the
334 * number of active request_fn invocations such that blk_drain_queue()
335 * can wait until all these request_fn calls have finished.
337 q->request_fn_active++;
339 q->request_fn_active--;
341 EXPORT_SYMBOL_GPL(__blk_run_queue_uncond);
344 * __blk_run_queue - run a single device queue
345 * @q: The queue to run
348 * See @blk_run_queue. This variant must be called with the queue lock
349 * held and interrupts disabled.
351 void __blk_run_queue(struct request_queue *q)
353 if (unlikely(blk_queue_stopped(q)))
356 __blk_run_queue_uncond(q);
358 EXPORT_SYMBOL(__blk_run_queue);
361 * blk_run_queue_async - run a single device queue in workqueue context
362 * @q: The queue to run
365 * Tells kblockd to perform the equivalent of @blk_run_queue on behalf
366 * of us. The caller must hold the queue lock.
368 void blk_run_queue_async(struct request_queue *q)
370 if (likely(!blk_queue_stopped(q) && !blk_queue_dead(q)))
371 mod_delayed_work(kblockd_workqueue, &q->delay_work, 0);
373 EXPORT_SYMBOL(blk_run_queue_async);
376 * blk_run_queue - run a single device queue
377 * @q: The queue to run
380 * Invoke request handling on this queue, if it has pending work to do.
381 * May be used to restart queueing when a request has completed.
383 void blk_run_queue(struct request_queue *q)
387 spin_lock_irqsave(q->queue_lock, flags);
389 spin_unlock_irqrestore(q->queue_lock, flags);
391 EXPORT_SYMBOL(blk_run_queue);
393 void blk_put_queue(struct request_queue *q)
395 kobject_put(&q->kobj);
397 EXPORT_SYMBOL(blk_put_queue);
400 * __blk_drain_queue - drain requests from request_queue
402 * @drain_all: whether to drain all requests or only the ones w/ ELVPRIV
404 * Drain requests from @q. If @drain_all is set, all requests are drained.
405 * If not, only ELVPRIV requests are drained. The caller is responsible
406 * for ensuring that no new requests which need to be drained are queued.
408 static void __blk_drain_queue(struct request_queue *q, bool drain_all)
409 __releases(q->queue_lock)
410 __acquires(q->queue_lock)
414 lockdep_assert_held(q->queue_lock);
420 * The caller might be trying to drain @q before its
421 * elevator is initialized.
424 elv_drain_elevator(q);
426 blkcg_drain_queue(q);
429 * This function might be called on a queue which failed
430 * driver init after queue creation or is not yet fully
431 * active yet. Some drivers (e.g. fd and loop) get unhappy
432 * in such cases. Kick queue iff dispatch queue has
433 * something on it and @q has request_fn set.
435 if (!list_empty(&q->queue_head) && q->request_fn)
438 drain |= q->nr_rqs_elvpriv;
439 drain |= q->request_fn_active;
442 * Unfortunately, requests are queued at and tracked from
443 * multiple places and there's no single counter which can
444 * be drained. Check all the queues and counters.
447 struct blk_flush_queue *fq = blk_get_flush_queue(q, NULL);
448 drain |= !list_empty(&q->queue_head);
449 for (i = 0; i < 2; i++) {
450 drain |= q->nr_rqs[i];
451 drain |= q->in_flight[i];
453 drain |= !list_empty(&fq->flush_queue[i]);
460 spin_unlock_irq(q->queue_lock);
464 spin_lock_irq(q->queue_lock);
468 * With queue marked dead, any woken up waiter will fail the
469 * allocation path, so the wakeup chaining is lost and we're
470 * left with hung waiters. We need to wake up those waiters.
473 struct request_list *rl;
475 blk_queue_for_each_rl(rl, q)
476 for (i = 0; i < ARRAY_SIZE(rl->wait); i++)
477 wake_up_all(&rl->wait[i]);
482 * blk_queue_bypass_start - enter queue bypass mode
483 * @q: queue of interest
485 * In bypass mode, only the dispatch FIFO queue of @q is used. This
486 * function makes @q enter bypass mode and drains all requests which were
487 * throttled or issued before. On return, it's guaranteed that no request
488 * is being throttled or has ELVPRIV set and blk_queue_bypass() %true
489 * inside queue or RCU read lock.
491 void blk_queue_bypass_start(struct request_queue *q)
493 spin_lock_irq(q->queue_lock);
495 queue_flag_set(QUEUE_FLAG_BYPASS, q);
496 spin_unlock_irq(q->queue_lock);
499 * Queues start drained. Skip actual draining till init is
500 * complete. This avoids lenghty delays during queue init which
501 * can happen many times during boot.
503 if (blk_queue_init_done(q)) {
504 spin_lock_irq(q->queue_lock);
505 __blk_drain_queue(q, false);
506 spin_unlock_irq(q->queue_lock);
508 /* ensure blk_queue_bypass() is %true inside RCU read lock */
512 EXPORT_SYMBOL_GPL(blk_queue_bypass_start);
515 * blk_queue_bypass_end - leave queue bypass mode
516 * @q: queue of interest
518 * Leave bypass mode and restore the normal queueing behavior.
520 void blk_queue_bypass_end(struct request_queue *q)
522 spin_lock_irq(q->queue_lock);
523 if (!--q->bypass_depth)
524 queue_flag_clear(QUEUE_FLAG_BYPASS, q);
525 WARN_ON_ONCE(q->bypass_depth < 0);
526 spin_unlock_irq(q->queue_lock);
528 EXPORT_SYMBOL_GPL(blk_queue_bypass_end);
530 void blk_set_queue_dying(struct request_queue *q)
532 spin_lock_irq(q->queue_lock);
533 queue_flag_set(QUEUE_FLAG_DYING, q);
534 spin_unlock_irq(q->queue_lock);
537 blk_mq_wake_waiters(q);
539 struct request_list *rl;
541 blk_queue_for_each_rl(rl, q) {
543 wake_up(&rl->wait[BLK_RW_SYNC]);
544 wake_up(&rl->wait[BLK_RW_ASYNC]);
549 EXPORT_SYMBOL_GPL(blk_set_queue_dying);
552 * blk_cleanup_queue - shutdown a request queue
553 * @q: request queue to shutdown
555 * Mark @q DYING, drain all pending requests, mark @q DEAD, destroy and
556 * put it. All future requests will be failed immediately with -ENODEV.
558 void blk_cleanup_queue(struct request_queue *q)
560 spinlock_t *lock = q->queue_lock;
562 /* mark @q DYING, no new request or merges will be allowed afterwards */
563 mutex_lock(&q->sysfs_lock);
564 blk_set_queue_dying(q);
568 * A dying queue is permanently in bypass mode till released. Note
569 * that, unlike blk_queue_bypass_start(), we aren't performing
570 * synchronize_rcu() after entering bypass mode to avoid the delay
571 * as some drivers create and destroy a lot of queues while
572 * probing. This is still safe because blk_release_queue() will be
573 * called only after the queue refcnt drops to zero and nothing,
574 * RCU or not, would be traversing the queue by then.
577 queue_flag_set(QUEUE_FLAG_BYPASS, q);
579 queue_flag_set(QUEUE_FLAG_NOMERGES, q);
580 queue_flag_set(QUEUE_FLAG_NOXMERGES, q);
581 queue_flag_set(QUEUE_FLAG_DYING, q);
582 spin_unlock_irq(lock);
583 mutex_unlock(&q->sysfs_lock);
586 * Drain all requests queued before DYING marking. Set DEAD flag to
587 * prevent that q->request_fn() gets invoked after draining finished.
592 __blk_drain_queue(q, true);
593 queue_flag_set(QUEUE_FLAG_DEAD, q);
594 spin_unlock_irq(lock);
596 /* for synchronous bio-based driver finish in-flight integrity i/o */
597 blk_flush_integrity();
599 /* @q won't process any more request, flush async actions */
600 del_timer_sync(&q->backing_dev_info.laptop_mode_wb_timer);
604 blk_mq_free_queue(q);
605 percpu_ref_exit(&q->q_usage_counter);
608 if (q->queue_lock != &q->__queue_lock)
609 q->queue_lock = &q->__queue_lock;
610 spin_unlock_irq(lock);
612 /* @q is and will stay empty, shutdown and put */
615 EXPORT_SYMBOL(blk_cleanup_queue);
617 /* Allocate memory local to the request queue */
618 static void *alloc_request_struct(gfp_t gfp_mask, void *data)
620 int nid = (int)(long)data;
621 return kmem_cache_alloc_node(request_cachep, gfp_mask, nid);
624 static void free_request_struct(void *element, void *unused)
626 kmem_cache_free(request_cachep, element);
629 int blk_init_rl(struct request_list *rl, struct request_queue *q,
632 if (unlikely(rl->rq_pool))
636 rl->count[BLK_RW_SYNC] = rl->count[BLK_RW_ASYNC] = 0;
637 rl->starved[BLK_RW_SYNC] = rl->starved[BLK_RW_ASYNC] = 0;
638 init_waitqueue_head(&rl->wait[BLK_RW_SYNC]);
639 init_waitqueue_head(&rl->wait[BLK_RW_ASYNC]);
641 rl->rq_pool = mempool_create_node(BLKDEV_MIN_RQ, alloc_request_struct,
643 (void *)(long)q->node, gfp_mask,
651 void blk_exit_rl(struct request_list *rl)
654 mempool_destroy(rl->rq_pool);
657 struct request_queue *blk_alloc_queue(gfp_t gfp_mask)
659 return blk_alloc_queue_node(gfp_mask, NUMA_NO_NODE);
661 EXPORT_SYMBOL(blk_alloc_queue);
663 int blk_queue_enter(struct request_queue *q, gfp_t gfp)
668 if (percpu_ref_tryget_live(&q->q_usage_counter))
671 if (!gfpflags_allow_blocking(gfp))
674 ret = wait_event_interruptible(q->mq_freeze_wq,
675 !atomic_read(&q->mq_freeze_depth) ||
677 if (blk_queue_dying(q))
684 void blk_queue_exit(struct request_queue *q)
686 percpu_ref_put(&q->q_usage_counter);
689 static void blk_queue_usage_counter_release(struct percpu_ref *ref)
691 struct request_queue *q =
692 container_of(ref, struct request_queue, q_usage_counter);
694 wake_up_all(&q->mq_freeze_wq);
697 struct request_queue *blk_alloc_queue_node(gfp_t gfp_mask, int node_id)
699 struct request_queue *q;
702 q = kmem_cache_alloc_node(blk_requestq_cachep,
703 gfp_mask | __GFP_ZERO, node_id);
707 q->id = ida_simple_get(&blk_queue_ida, 0, 0, gfp_mask);
711 q->bio_split = bioset_create(BIO_POOL_SIZE, 0);
715 q->backing_dev_info.ra_pages =
716 (VM_MAX_READAHEAD * 1024) / PAGE_CACHE_SIZE;
717 q->backing_dev_info.capabilities = BDI_CAP_CGROUP_WRITEBACK;
718 q->backing_dev_info.name = "block";
721 err = bdi_init(&q->backing_dev_info);
725 setup_timer(&q->backing_dev_info.laptop_mode_wb_timer,
726 laptop_mode_timer_fn, (unsigned long) q);
727 setup_timer(&q->timeout, blk_rq_timed_out_timer, (unsigned long) q);
728 INIT_LIST_HEAD(&q->queue_head);
729 INIT_LIST_HEAD(&q->timeout_list);
730 INIT_LIST_HEAD(&q->icq_list);
731 #ifdef CONFIG_BLK_CGROUP
732 INIT_LIST_HEAD(&q->blkg_list);
734 INIT_DELAYED_WORK(&q->delay_work, blk_delay_work);
736 kobject_init(&q->kobj, &blk_queue_ktype);
738 mutex_init(&q->sysfs_lock);
739 spin_lock_init(&q->__queue_lock);
742 * By default initialize queue_lock to internal lock and driver can
743 * override it later if need be.
745 q->queue_lock = &q->__queue_lock;
748 * A queue starts its life with bypass turned on to avoid
749 * unnecessary bypass on/off overhead and nasty surprises during
750 * init. The initial bypass will be finished when the queue is
751 * registered by blk_register_queue().
754 __set_bit(QUEUE_FLAG_BYPASS, &q->queue_flags);
756 init_waitqueue_head(&q->mq_freeze_wq);
759 * Init percpu_ref in atomic mode so that it's faster to shutdown.
760 * See blk_register_queue() for details.
762 if (percpu_ref_init(&q->q_usage_counter,
763 blk_queue_usage_counter_release,
764 PERCPU_REF_INIT_ATOMIC, GFP_KERNEL))
767 if (blkcg_init_queue(q))
773 percpu_ref_exit(&q->q_usage_counter);
775 bdi_destroy(&q->backing_dev_info);
777 bioset_free(q->bio_split);
779 ida_simple_remove(&blk_queue_ida, q->id);
781 kmem_cache_free(blk_requestq_cachep, q);
784 EXPORT_SYMBOL(blk_alloc_queue_node);
787 * blk_init_queue - prepare a request queue for use with a block device
788 * @rfn: The function to be called to process requests that have been
789 * placed on the queue.
790 * @lock: Request queue spin lock
793 * If a block device wishes to use the standard request handling procedures,
794 * which sorts requests and coalesces adjacent requests, then it must
795 * call blk_init_queue(). The function @rfn will be called when there
796 * are requests on the queue that need to be processed. If the device
797 * supports plugging, then @rfn may not be called immediately when requests
798 * are available on the queue, but may be called at some time later instead.
799 * Plugged queues are generally unplugged when a buffer belonging to one
800 * of the requests on the queue is needed, or due to memory pressure.
802 * @rfn is not required, or even expected, to remove all requests off the
803 * queue, but only as many as it can handle at a time. If it does leave
804 * requests on the queue, it is responsible for arranging that the requests
805 * get dealt with eventually.
807 * The queue spin lock must be held while manipulating the requests on the
808 * request queue; this lock will be taken also from interrupt context, so irq
809 * disabling is needed for it.
811 * Function returns a pointer to the initialized request queue, or %NULL if
815 * blk_init_queue() must be paired with a blk_cleanup_queue() call
816 * when the block device is deactivated (such as at module unload).
819 struct request_queue *blk_init_queue(request_fn_proc *rfn, spinlock_t *lock)
821 return blk_init_queue_node(rfn, lock, NUMA_NO_NODE);
823 EXPORT_SYMBOL(blk_init_queue);
825 struct request_queue *
826 blk_init_queue_node(request_fn_proc *rfn, spinlock_t *lock, int node_id)
828 struct request_queue *uninit_q, *q;
830 uninit_q = blk_alloc_queue_node(GFP_KERNEL, node_id);
834 q = blk_init_allocated_queue(uninit_q, rfn, lock);
836 blk_cleanup_queue(uninit_q);
840 EXPORT_SYMBOL(blk_init_queue_node);
842 static blk_qc_t blk_queue_bio(struct request_queue *q, struct bio *bio);
844 struct request_queue *
845 blk_init_allocated_queue(struct request_queue *q, request_fn_proc *rfn,
851 q->fq = blk_alloc_flush_queue(q, NUMA_NO_NODE, 0);
855 if (blk_init_rl(&q->root_rl, q, GFP_KERNEL))
859 q->prep_rq_fn = NULL;
860 q->unprep_rq_fn = NULL;
861 q->queue_flags |= QUEUE_FLAG_DEFAULT;
863 /* Override internal queue lock with supplied lock pointer */
865 q->queue_lock = lock;
868 * This also sets hw/phys segments, boundary and size
870 blk_queue_make_request(q, blk_queue_bio);
872 q->sg_reserved_size = INT_MAX;
874 /* Protect q->elevator from elevator_change */
875 mutex_lock(&q->sysfs_lock);
878 if (elevator_init(q, NULL)) {
879 mutex_unlock(&q->sysfs_lock);
883 mutex_unlock(&q->sysfs_lock);
888 blk_free_flush_queue(q->fq);
891 EXPORT_SYMBOL(blk_init_allocated_queue);
893 bool blk_get_queue(struct request_queue *q)
895 if (likely(!blk_queue_dying(q))) {
902 EXPORT_SYMBOL(blk_get_queue);
904 static inline void blk_free_request(struct request_list *rl, struct request *rq)
906 if (rq->cmd_flags & REQ_ELVPRIV) {
907 elv_put_request(rl->q, rq);
909 put_io_context(rq->elv.icq->ioc);
912 mempool_free(rq, rl->rq_pool);
916 * ioc_batching returns true if the ioc is a valid batching request and
917 * should be given priority access to a request.
919 static inline int ioc_batching(struct request_queue *q, struct io_context *ioc)
925 * Make sure the process is able to allocate at least 1 request
926 * even if the batch times out, otherwise we could theoretically
929 return ioc->nr_batch_requests == q->nr_batching ||
930 (ioc->nr_batch_requests > 0
931 && time_before(jiffies, ioc->last_waited + BLK_BATCH_TIME));
935 * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
936 * will cause the process to be a "batcher" on all queues in the system. This
937 * is the behaviour we want though - once it gets a wakeup it should be given
940 static void ioc_set_batching(struct request_queue *q, struct io_context *ioc)
942 if (!ioc || ioc_batching(q, ioc))
945 ioc->nr_batch_requests = q->nr_batching;
946 ioc->last_waited = jiffies;
949 static void __freed_request(struct request_list *rl, int sync)
951 struct request_queue *q = rl->q;
953 if (rl->count[sync] < queue_congestion_off_threshold(q))
954 blk_clear_congested(rl, sync);
956 if (rl->count[sync] + 1 <= q->nr_requests) {
957 if (waitqueue_active(&rl->wait[sync]))
958 wake_up(&rl->wait[sync]);
960 blk_clear_rl_full(rl, sync);
965 * A request has just been released. Account for it, update the full and
966 * congestion status, wake up any waiters. Called under q->queue_lock.
968 static void freed_request(struct request_list *rl, unsigned int flags)
970 struct request_queue *q = rl->q;
971 int sync = rw_is_sync(flags);
975 if (flags & REQ_ELVPRIV)
978 __freed_request(rl, sync);
980 if (unlikely(rl->starved[sync ^ 1]))
981 __freed_request(rl, sync ^ 1);
984 int blk_update_nr_requests(struct request_queue *q, unsigned int nr)
986 struct request_list *rl;
987 int on_thresh, off_thresh;
989 spin_lock_irq(q->queue_lock);
991 blk_queue_congestion_threshold(q);
992 on_thresh = queue_congestion_on_threshold(q);
993 off_thresh = queue_congestion_off_threshold(q);
995 blk_queue_for_each_rl(rl, q) {
996 if (rl->count[BLK_RW_SYNC] >= on_thresh)
997 blk_set_congested(rl, BLK_RW_SYNC);
998 else if (rl->count[BLK_RW_SYNC] < off_thresh)
999 blk_clear_congested(rl, BLK_RW_SYNC);
1001 if (rl->count[BLK_RW_ASYNC] >= on_thresh)
1002 blk_set_congested(rl, BLK_RW_ASYNC);
1003 else if (rl->count[BLK_RW_ASYNC] < off_thresh)
1004 blk_clear_congested(rl, BLK_RW_ASYNC);
1006 if (rl->count[BLK_RW_SYNC] >= q->nr_requests) {
1007 blk_set_rl_full(rl, BLK_RW_SYNC);
1009 blk_clear_rl_full(rl, BLK_RW_SYNC);
1010 wake_up(&rl->wait[BLK_RW_SYNC]);
1013 if (rl->count[BLK_RW_ASYNC] >= q->nr_requests) {
1014 blk_set_rl_full(rl, BLK_RW_ASYNC);
1016 blk_clear_rl_full(rl, BLK_RW_ASYNC);
1017 wake_up(&rl->wait[BLK_RW_ASYNC]);
1021 spin_unlock_irq(q->queue_lock);
1026 * Determine if elevator data should be initialized when allocating the
1027 * request associated with @bio.
1029 static bool blk_rq_should_init_elevator(struct bio *bio)
1035 * Flush requests do not use the elevator so skip initialization.
1036 * This allows a request to share the flush and elevator data.
1038 if (bio->bi_rw & (REQ_FLUSH | REQ_FUA))
1045 * rq_ioc - determine io_context for request allocation
1046 * @bio: request being allocated is for this bio (can be %NULL)
1048 * Determine io_context to use for request allocation for @bio. May return
1049 * %NULL if %current->io_context doesn't exist.
1051 static struct io_context *rq_ioc(struct bio *bio)
1053 #ifdef CONFIG_BLK_CGROUP
1054 if (bio && bio->bi_ioc)
1057 return current->io_context;
1061 * __get_request - get a free request
1062 * @rl: request list to allocate from
1063 * @rw_flags: RW and SYNC flags
1064 * @bio: bio to allocate request for (can be %NULL)
1065 * @gfp_mask: allocation mask
1067 * Get a free request from @q. This function may fail under memory
1068 * pressure or if @q is dead.
1070 * Must be called with @q->queue_lock held and,
1071 * Returns ERR_PTR on failure, with @q->queue_lock held.
1072 * Returns request pointer on success, with @q->queue_lock *not held*.
1074 static struct request *__get_request(struct request_list *rl, int rw_flags,
1075 struct bio *bio, gfp_t gfp_mask)
1077 struct request_queue *q = rl->q;
1079 struct elevator_type *et = q->elevator->type;
1080 struct io_context *ioc = rq_ioc(bio);
1081 struct io_cq *icq = NULL;
1082 const bool is_sync = rw_is_sync(rw_flags) != 0;
1085 if (unlikely(blk_queue_dying(q)))
1086 return ERR_PTR(-ENODEV);
1088 may_queue = elv_may_queue(q, rw_flags);
1089 if (may_queue == ELV_MQUEUE_NO)
1092 if (rl->count[is_sync]+1 >= queue_congestion_on_threshold(q)) {
1093 if (rl->count[is_sync]+1 >= q->nr_requests) {
1095 * The queue will fill after this allocation, so set
1096 * it as full, and mark this process as "batching".
1097 * This process will be allowed to complete a batch of
1098 * requests, others will be blocked.
1100 if (!blk_rl_full(rl, is_sync)) {
1101 ioc_set_batching(q, ioc);
1102 blk_set_rl_full(rl, is_sync);
1104 if (may_queue != ELV_MQUEUE_MUST
1105 && !ioc_batching(q, ioc)) {
1107 * The queue is full and the allocating
1108 * process is not a "batcher", and not
1109 * exempted by the IO scheduler
1111 return ERR_PTR(-ENOMEM);
1115 blk_set_congested(rl, is_sync);
1119 * Only allow batching queuers to allocate up to 50% over the defined
1120 * limit of requests, otherwise we could have thousands of requests
1121 * allocated with any setting of ->nr_requests
1123 if (rl->count[is_sync] >= (3 * q->nr_requests / 2))
1124 return ERR_PTR(-ENOMEM);
1126 q->nr_rqs[is_sync]++;
1127 rl->count[is_sync]++;
1128 rl->starved[is_sync] = 0;
1131 * Decide whether the new request will be managed by elevator. If
1132 * so, mark @rw_flags and increment elvpriv. Non-zero elvpriv will
1133 * prevent the current elevator from being destroyed until the new
1134 * request is freed. This guarantees icq's won't be destroyed and
1135 * makes creating new ones safe.
1137 * Also, lookup icq while holding queue_lock. If it doesn't exist,
1138 * it will be created after releasing queue_lock.
1140 if (blk_rq_should_init_elevator(bio) && !blk_queue_bypass(q)) {
1141 rw_flags |= REQ_ELVPRIV;
1142 q->nr_rqs_elvpriv++;
1143 if (et->icq_cache && ioc)
1144 icq = ioc_lookup_icq(ioc, q);
1147 if (blk_queue_io_stat(q))
1148 rw_flags |= REQ_IO_STAT;
1149 spin_unlock_irq(q->queue_lock);
1151 /* allocate and init request */
1152 rq = mempool_alloc(rl->rq_pool, gfp_mask);
1157 blk_rq_set_rl(rq, rl);
1158 rq->cmd_flags = rw_flags | REQ_ALLOCED;
1161 if (rw_flags & REQ_ELVPRIV) {
1162 if (unlikely(et->icq_cache && !icq)) {
1164 icq = ioc_create_icq(ioc, q, gfp_mask);
1170 if (unlikely(elv_set_request(q, rq, bio, gfp_mask)))
1173 /* @rq->elv.icq holds io_context until @rq is freed */
1175 get_io_context(icq->ioc);
1179 * ioc may be NULL here, and ioc_batching will be false. That's
1180 * OK, if the queue is under the request limit then requests need
1181 * not count toward the nr_batch_requests limit. There will always
1182 * be some limit enforced by BLK_BATCH_TIME.
1184 if (ioc_batching(q, ioc))
1185 ioc->nr_batch_requests--;
1187 trace_block_getrq(q, bio, rw_flags & 1);
1192 * elvpriv init failed. ioc, icq and elvpriv aren't mempool backed
1193 * and may fail indefinitely under memory pressure and thus
1194 * shouldn't stall IO. Treat this request as !elvpriv. This will
1195 * disturb iosched and blkcg but weird is bettern than dead.
1197 printk_ratelimited(KERN_WARNING "%s: dev %s: request aux data allocation failed, iosched may be disturbed\n",
1198 __func__, dev_name(q->backing_dev_info.dev));
1200 rq->cmd_flags &= ~REQ_ELVPRIV;
1203 spin_lock_irq(q->queue_lock);
1204 q->nr_rqs_elvpriv--;
1205 spin_unlock_irq(q->queue_lock);
1210 * Allocation failed presumably due to memory. Undo anything we
1211 * might have messed up.
1213 * Allocating task should really be put onto the front of the wait
1214 * queue, but this is pretty rare.
1216 spin_lock_irq(q->queue_lock);
1217 freed_request(rl, rw_flags);
1220 * in the very unlikely event that allocation failed and no
1221 * requests for this direction was pending, mark us starved so that
1222 * freeing of a request in the other direction will notice
1223 * us. another possible fix would be to split the rq mempool into
1227 if (unlikely(rl->count[is_sync] == 0))
1228 rl->starved[is_sync] = 1;
1229 return ERR_PTR(-ENOMEM);
1233 * get_request - get a free request
1234 * @q: request_queue to allocate request from
1235 * @rw_flags: RW and SYNC flags
1236 * @bio: bio to allocate request for (can be %NULL)
1237 * @gfp_mask: allocation mask
1239 * Get a free request from @q. If %__GFP_DIRECT_RECLAIM is set in @gfp_mask,
1240 * this function keeps retrying under memory pressure and fails iff @q is dead.
1242 * Must be called with @q->queue_lock held and,
1243 * Returns ERR_PTR on failure, with @q->queue_lock held.
1244 * Returns request pointer on success, with @q->queue_lock *not held*.
1246 static struct request *get_request(struct request_queue *q, int rw_flags,
1247 struct bio *bio, gfp_t gfp_mask)
1249 const bool is_sync = rw_is_sync(rw_flags) != 0;
1251 struct request_list *rl;
1254 rl = blk_get_rl(q, bio); /* transferred to @rq on success */
1256 rq = __get_request(rl, rw_flags, bio, gfp_mask);
1260 if (!gfpflags_allow_blocking(gfp_mask) || unlikely(blk_queue_dying(q))) {
1265 /* wait on @rl and retry */
1266 prepare_to_wait_exclusive(&rl->wait[is_sync], &wait,
1267 TASK_UNINTERRUPTIBLE);
1269 trace_block_sleeprq(q, bio, rw_flags & 1);
1271 spin_unlock_irq(q->queue_lock);
1275 * After sleeping, we become a "batching" process and will be able
1276 * to allocate at least one request, and up to a big batch of them
1277 * for a small period time. See ioc_batching, ioc_set_batching
1279 ioc_set_batching(q, current->io_context);
1281 spin_lock_irq(q->queue_lock);
1282 finish_wait(&rl->wait[is_sync], &wait);
1287 static struct request *blk_old_get_request(struct request_queue *q, int rw,
1292 /* create ioc upfront */
1293 create_io_context(gfp_mask, q->node);
1295 spin_lock_irq(q->queue_lock);
1296 rq = get_request(q, rw, NULL, gfp_mask);
1298 spin_unlock_irq(q->queue_lock);
1299 /* q->queue_lock is unlocked at this point */
1304 struct request *blk_get_request(struct request_queue *q, int rw, gfp_t gfp_mask)
1307 return blk_mq_alloc_request(q, rw, gfp_mask, false);
1309 return blk_old_get_request(q, rw, gfp_mask);
1311 EXPORT_SYMBOL(blk_get_request);
1314 * blk_make_request - given a bio, allocate a corresponding struct request.
1315 * @q: target request queue
1316 * @bio: The bio describing the memory mappings that will be submitted for IO.
1317 * It may be a chained-bio properly constructed by block/bio layer.
1318 * @gfp_mask: gfp flags to be used for memory allocation
1320 * blk_make_request is the parallel of generic_make_request for BLOCK_PC
1321 * type commands. Where the struct request needs to be farther initialized by
1322 * the caller. It is passed a &struct bio, which describes the memory info of
1325 * The caller of blk_make_request must make sure that bi_io_vec
1326 * are set to describe the memory buffers. That bio_data_dir() will return
1327 * the needed direction of the request. (And all bio's in the passed bio-chain
1328 * are properly set accordingly)
1330 * If called under none-sleepable conditions, mapped bio buffers must not
1331 * need bouncing, by calling the appropriate masked or flagged allocator,
1332 * suitable for the target device. Otherwise the call to blk_queue_bounce will
1335 * WARNING: When allocating/cloning a bio-chain, careful consideration should be
1336 * given to how you allocate bios. In particular, you cannot use
1337 * __GFP_DIRECT_RECLAIM for anything but the first bio in the chain. Otherwise
1338 * you risk waiting for IO completion of a bio that hasn't been submitted yet,
1339 * thus resulting in a deadlock. Alternatively bios should be allocated using
1340 * bio_kmalloc() instead of bio_alloc(), as that avoids the mempool deadlock.
1341 * If possible a big IO should be split into smaller parts when allocation
1342 * fails. Partial allocation should not be an error, or you risk a live-lock.
1344 struct request *blk_make_request(struct request_queue *q, struct bio *bio,
1347 struct request *rq = blk_get_request(q, bio_data_dir(bio), gfp_mask);
1352 blk_rq_set_block_pc(rq);
1355 struct bio *bounce_bio = bio;
1358 blk_queue_bounce(q, &bounce_bio);
1359 ret = blk_rq_append_bio(q, rq, bounce_bio);
1360 if (unlikely(ret)) {
1361 blk_put_request(rq);
1362 return ERR_PTR(ret);
1368 EXPORT_SYMBOL(blk_make_request);
1371 * blk_rq_set_block_pc - initialize a request to type BLOCK_PC
1372 * @rq: request to be initialized
1375 void blk_rq_set_block_pc(struct request *rq)
1377 rq->cmd_type = REQ_TYPE_BLOCK_PC;
1379 rq->__sector = (sector_t) -1;
1380 rq->bio = rq->biotail = NULL;
1381 memset(rq->__cmd, 0, sizeof(rq->__cmd));
1383 EXPORT_SYMBOL(blk_rq_set_block_pc);
1386 * blk_requeue_request - put a request back on queue
1387 * @q: request queue where request should be inserted
1388 * @rq: request to be inserted
1391 * Drivers often keep queueing requests until the hardware cannot accept
1392 * more, when that condition happens we need to put the request back
1393 * on the queue. Must be called with queue lock held.
1395 void blk_requeue_request(struct request_queue *q, struct request *rq)
1397 blk_delete_timer(rq);
1398 blk_clear_rq_complete(rq);
1399 trace_block_rq_requeue(q, rq);
1401 if (rq->cmd_flags & REQ_QUEUED)
1402 blk_queue_end_tag(q, rq);
1404 BUG_ON(blk_queued_rq(rq));
1406 elv_requeue_request(q, rq);
1408 EXPORT_SYMBOL(blk_requeue_request);
1410 static void add_acct_request(struct request_queue *q, struct request *rq,
1413 blk_account_io_start(rq, true);
1414 __elv_add_request(q, rq, where);
1417 static void part_round_stats_single(int cpu, struct hd_struct *part,
1422 if (now == part->stamp)
1425 inflight = part_in_flight(part);
1427 __part_stat_add(cpu, part, time_in_queue,
1428 inflight * (now - part->stamp));
1429 __part_stat_add(cpu, part, io_ticks, (now - part->stamp));
1435 * part_round_stats() - Round off the performance stats on a struct disk_stats.
1436 * @cpu: cpu number for stats access
1437 * @part: target partition
1439 * The average IO queue length and utilisation statistics are maintained
1440 * by observing the current state of the queue length and the amount of
1441 * time it has been in this state for.
1443 * Normally, that accounting is done on IO completion, but that can result
1444 * in more than a second's worth of IO being accounted for within any one
1445 * second, leading to >100% utilisation. To deal with that, we call this
1446 * function to do a round-off before returning the results when reading
1447 * /proc/diskstats. This accounts immediately for all queue usage up to
1448 * the current jiffies and restarts the counters again.
1450 void part_round_stats(int cpu, struct hd_struct *part)
1452 unsigned long now = jiffies;
1455 part_round_stats_single(cpu, &part_to_disk(part)->part0, now);
1456 part_round_stats_single(cpu, part, now);
1458 EXPORT_SYMBOL_GPL(part_round_stats);
1461 static void blk_pm_put_request(struct request *rq)
1463 if (rq->q->dev && !(rq->cmd_flags & REQ_PM) && rq->q->nr_pending) {
1464 if (!--rq->q->nr_pending)
1465 pm_runtime_mark_last_busy(rq->q->dev);
1469 static inline void blk_pm_put_request(struct request *rq) {}
1473 * queue lock must be held
1475 void __blk_put_request(struct request_queue *q, struct request *req)
1481 blk_mq_free_request(req);
1485 blk_pm_put_request(req);
1487 elv_completed_request(q, req);
1489 /* this is a bio leak */
1490 WARN_ON(req->bio != NULL);
1492 /* this is a bio leak if the bio is not tagged with BIO_DONTFREE */
1493 WARN_ON(req->bio && !bio_flagged(req->bio, BIO_DONTFREE));
1496 * Request may not have originated from ll_rw_blk. if not,
1497 * it didn't come out of our reserved rq pools
1499 if (req->cmd_flags & REQ_ALLOCED) {
1500 unsigned int flags = req->cmd_flags;
1501 struct request_list *rl = blk_rq_rl(req);
1503 BUG_ON(!list_empty(&req->queuelist));
1504 BUG_ON(ELV_ON_HASH(req));
1506 blk_free_request(rl, req);
1507 freed_request(rl, flags);
1511 EXPORT_SYMBOL_GPL(__blk_put_request);
1513 void blk_put_request(struct request *req)
1515 struct request_queue *q = req->q;
1518 blk_mq_free_request(req);
1520 unsigned long flags;
1522 spin_lock_irqsave(q->queue_lock, flags);
1523 __blk_put_request(q, req);
1524 spin_unlock_irqrestore(q->queue_lock, flags);
1527 EXPORT_SYMBOL(blk_put_request);
1530 * blk_add_request_payload - add a payload to a request
1531 * @rq: request to update
1532 * @page: page backing the payload
1533 * @len: length of the payload.
1535 * This allows to later add a payload to an already submitted request by
1536 * a block driver. The driver needs to take care of freeing the payload
1539 * Note that this is a quite horrible hack and nothing but handling of
1540 * discard requests should ever use it.
1542 void blk_add_request_payload(struct request *rq, struct page *page,
1545 struct bio *bio = rq->bio;
1547 bio->bi_io_vec->bv_page = page;
1548 bio->bi_io_vec->bv_offset = 0;
1549 bio->bi_io_vec->bv_len = len;
1551 bio->bi_iter.bi_size = len;
1553 bio->bi_phys_segments = 1;
1555 rq->__data_len = rq->resid_len = len;
1556 rq->nr_phys_segments = 1;
1558 EXPORT_SYMBOL_GPL(blk_add_request_payload);
1560 bool bio_attempt_back_merge(struct request_queue *q, struct request *req,
1563 const int ff = bio->bi_rw & REQ_FAILFAST_MASK;
1565 if (!ll_back_merge_fn(q, req, bio))
1568 trace_block_bio_backmerge(q, req, bio);
1570 if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
1571 blk_rq_set_mixed_merge(req);
1573 req->biotail->bi_next = bio;
1575 req->__data_len += bio->bi_iter.bi_size;
1576 req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
1578 blk_account_io_start(req, false);
1582 bool bio_attempt_front_merge(struct request_queue *q, struct request *req,
1585 const int ff = bio->bi_rw & REQ_FAILFAST_MASK;
1587 if (!ll_front_merge_fn(q, req, bio))
1590 trace_block_bio_frontmerge(q, req, bio);
1592 if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
1593 blk_rq_set_mixed_merge(req);
1595 bio->bi_next = req->bio;
1598 req->__sector = bio->bi_iter.bi_sector;
1599 req->__data_len += bio->bi_iter.bi_size;
1600 req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
1602 blk_account_io_start(req, false);
1607 * blk_attempt_plug_merge - try to merge with %current's plugged list
1608 * @q: request_queue new bio is being queued at
1609 * @bio: new bio being queued
1610 * @request_count: out parameter for number of traversed plugged requests
1611 * @same_queue_rq: pointer to &struct request that gets filled in when
1612 * another request associated with @q is found on the plug list
1613 * (optional, may be %NULL)
1615 * Determine whether @bio being queued on @q can be merged with a request
1616 * on %current's plugged list. Returns %true if merge was successful,
1619 * Plugging coalesces IOs from the same issuer for the same purpose without
1620 * going through @q->queue_lock. As such it's more of an issuing mechanism
1621 * than scheduling, and the request, while may have elvpriv data, is not
1622 * added on the elevator at this point. In addition, we don't have
1623 * reliable access to the elevator outside queue lock. Only check basic
1624 * merging parameters without querying the elevator.
1626 * Caller must ensure !blk_queue_nomerges(q) beforehand.
1628 bool blk_attempt_plug_merge(struct request_queue *q, struct bio *bio,
1629 unsigned int *request_count,
1630 struct request **same_queue_rq)
1632 struct blk_plug *plug;
1635 struct list_head *plug_list;
1637 plug = current->plug;
1643 plug_list = &plug->mq_list;
1645 plug_list = &plug->list;
1647 list_for_each_entry_reverse(rq, plug_list, queuelist) {
1653 * Only blk-mq multiple hardware queues case checks the
1654 * rq in the same queue, there should be only one such
1658 *same_queue_rq = rq;
1661 if (rq->q != q || !blk_rq_merge_ok(rq, bio))
1664 el_ret = blk_try_merge(rq, bio);
1665 if (el_ret == ELEVATOR_BACK_MERGE) {
1666 ret = bio_attempt_back_merge(q, rq, bio);
1669 } else if (el_ret == ELEVATOR_FRONT_MERGE) {
1670 ret = bio_attempt_front_merge(q, rq, bio);
1679 unsigned int blk_plug_queued_count(struct request_queue *q)
1681 struct blk_plug *plug;
1683 struct list_head *plug_list;
1684 unsigned int ret = 0;
1686 plug = current->plug;
1691 plug_list = &plug->mq_list;
1693 plug_list = &plug->list;
1695 list_for_each_entry(rq, plug_list, queuelist) {
1703 void init_request_from_bio(struct request *req, struct bio *bio)
1705 req->cmd_type = REQ_TYPE_FS;
1707 req->cmd_flags |= bio->bi_rw & REQ_COMMON_MASK;
1708 if (bio->bi_rw & REQ_RAHEAD)
1709 req->cmd_flags |= REQ_FAILFAST_MASK;
1712 req->__sector = bio->bi_iter.bi_sector;
1713 req->ioprio = bio_prio(bio);
1714 blk_rq_bio_prep(req->q, req, bio);
1716 EXPORT_SYMBOL(init_request_from_bio);
1718 static blk_qc_t blk_queue_bio(struct request_queue *q, struct bio *bio)
1720 const bool sync = !!(bio->bi_rw & REQ_SYNC);
1721 struct blk_plug *plug;
1722 int el_ret, rw_flags, where = ELEVATOR_INSERT_SORT;
1723 struct request *req;
1724 unsigned int request_count = 0;
1727 * low level driver can indicate that it wants pages above a
1728 * certain limit bounced to low memory (ie for highmem, or even
1729 * ISA dma in theory)
1731 blk_queue_bounce(q, &bio);
1733 blk_queue_split(q, &bio, q->bio_split);
1735 if (bio_integrity_enabled(bio) && bio_integrity_prep(bio)) {
1736 bio->bi_error = -EIO;
1738 return BLK_QC_T_NONE;
1741 if (bio->bi_rw & (REQ_FLUSH | REQ_FUA | REQ_POST_FLUSH_BARRIER |
1743 spin_lock_irq(q->queue_lock);
1744 where = ELEVATOR_INSERT_FLUSH;
1749 * Check if we can merge with the plugged list before grabbing
1752 if (!blk_queue_nomerges(q)) {
1753 if (blk_attempt_plug_merge(q, bio, &request_count, NULL))
1754 return BLK_QC_T_NONE;
1756 request_count = blk_plug_queued_count(q);
1758 spin_lock_irq(q->queue_lock);
1760 el_ret = elv_merge(q, &req, bio);
1761 if (el_ret == ELEVATOR_BACK_MERGE) {
1762 if (bio_attempt_back_merge(q, req, bio)) {
1763 elv_bio_merged(q, req, bio);
1764 if (!attempt_back_merge(q, req))
1765 elv_merged_request(q, req, el_ret);
1768 } else if (el_ret == ELEVATOR_FRONT_MERGE) {
1769 if (bio_attempt_front_merge(q, req, bio)) {
1770 elv_bio_merged(q, req, bio);
1771 if (!attempt_front_merge(q, req))
1772 elv_merged_request(q, req, el_ret);
1779 * This sync check and mask will be re-done in init_request_from_bio(),
1780 * but we need to set it earlier to expose the sync flag to the
1781 * rq allocator and io schedulers.
1783 rw_flags = bio_data_dir(bio);
1785 rw_flags |= REQ_SYNC;
1788 * Grab a free request. This is might sleep but can not fail.
1789 * Returns with the queue unlocked.
1791 req = get_request(q, rw_flags, bio, GFP_NOIO);
1793 bio->bi_error = PTR_ERR(req);
1799 * After dropping the lock and possibly sleeping here, our request
1800 * may now be mergeable after it had proven unmergeable (above).
1801 * We don't worry about that case for efficiency. It won't happen
1802 * often, and the elevators are able to handle it.
1804 init_request_from_bio(req, bio);
1806 if (test_bit(QUEUE_FLAG_SAME_COMP, &q->queue_flags))
1807 req->cpu = raw_smp_processor_id();
1809 plug = current->plug;
1812 * If this is the first request added after a plug, fire
1816 trace_block_plug(q);
1818 if (request_count >= BLK_MAX_REQUEST_COUNT) {
1819 blk_flush_plug_list(plug, false);
1820 trace_block_plug(q);
1823 list_add_tail(&req->queuelist, &plug->list);
1824 blk_account_io_start(req, true);
1826 spin_lock_irq(q->queue_lock);
1827 add_acct_request(q, req, where);
1830 spin_unlock_irq(q->queue_lock);
1833 return BLK_QC_T_NONE;
1837 * If bio->bi_dev is a partition, remap the location
1839 static inline void blk_partition_remap(struct bio *bio)
1841 struct block_device *bdev = bio->bi_bdev;
1843 if (bio_sectors(bio) && bdev != bdev->bd_contains) {
1844 struct hd_struct *p = bdev->bd_part;
1846 bio->bi_iter.bi_sector += p->start_sect;
1847 bio->bi_bdev = bdev->bd_contains;
1849 trace_block_bio_remap(bdev_get_queue(bio->bi_bdev), bio,
1851 bio->bi_iter.bi_sector - p->start_sect);
1855 static void handle_bad_sector(struct bio *bio)
1857 char b[BDEVNAME_SIZE];
1859 printk(KERN_INFO "attempt to access beyond end of device\n");
1860 printk(KERN_INFO "%s: rw=%ld, want=%Lu, limit=%Lu\n",
1861 bdevname(bio->bi_bdev, b),
1863 (unsigned long long)bio_end_sector(bio),
1864 (long long)(i_size_read(bio->bi_bdev->bd_inode) >> 9));
1867 #ifdef CONFIG_FAIL_MAKE_REQUEST
1869 static DECLARE_FAULT_ATTR(fail_make_request);
1871 static int __init setup_fail_make_request(char *str)
1873 return setup_fault_attr(&fail_make_request, str);
1875 __setup("fail_make_request=", setup_fail_make_request);
1877 static bool should_fail_request(struct hd_struct *part, unsigned int bytes)
1879 return part->make_it_fail && should_fail(&fail_make_request, bytes);
1882 static int __init fail_make_request_debugfs(void)
1884 struct dentry *dir = fault_create_debugfs_attr("fail_make_request",
1885 NULL, &fail_make_request);
1887 return PTR_ERR_OR_ZERO(dir);
1890 late_initcall(fail_make_request_debugfs);
1892 #else /* CONFIG_FAIL_MAKE_REQUEST */
1894 static inline bool should_fail_request(struct hd_struct *part,
1900 #endif /* CONFIG_FAIL_MAKE_REQUEST */
1903 * Check whether this bio extends beyond the end of the device.
1905 static inline int bio_check_eod(struct bio *bio, unsigned int nr_sectors)
1912 /* Test device or partition size, when known. */
1913 maxsector = i_size_read(bio->bi_bdev->bd_inode) >> 9;
1915 sector_t sector = bio->bi_iter.bi_sector;
1917 if (maxsector < nr_sectors || maxsector - nr_sectors < sector) {
1919 * This may well happen - the kernel calls bread()
1920 * without checking the size of the device, e.g., when
1921 * mounting a device.
1923 handle_bad_sector(bio);
1931 static noinline_for_stack bool
1932 generic_make_request_checks(struct bio *bio)
1934 struct request_queue *q;
1935 int nr_sectors = bio_sectors(bio);
1937 char b[BDEVNAME_SIZE];
1938 struct hd_struct *part;
1942 if (bio_check_eod(bio, nr_sectors))
1945 q = bdev_get_queue(bio->bi_bdev);
1948 "generic_make_request: Trying to access "
1949 "nonexistent block-device %s (%Lu)\n",
1950 bdevname(bio->bi_bdev, b),
1951 (long long) bio->bi_iter.bi_sector);
1955 part = bio->bi_bdev->bd_part;
1956 if (should_fail_request(part, bio->bi_iter.bi_size) ||
1957 should_fail_request(&part_to_disk(part)->part0,
1958 bio->bi_iter.bi_size))
1962 * If this device has partitions, remap block n
1963 * of partition p to block n+start(p) of the disk.
1965 blk_partition_remap(bio);
1967 if (bio_check_eod(bio, nr_sectors))
1971 * Filter flush bio's early so that make_request based
1972 * drivers without flush support don't have to worry
1975 if ((bio->bi_rw & (REQ_FLUSH | REQ_FUA)) && !q->flush_flags) {
1976 bio->bi_rw &= ~(REQ_FLUSH | REQ_FUA);
1983 if ((bio->bi_rw & REQ_DISCARD) &&
1984 (!blk_queue_discard(q) ||
1985 ((bio->bi_rw & REQ_SECURE) && !blk_queue_secdiscard(q)))) {
1990 if (bio->bi_rw & REQ_WRITE_SAME && !bdev_write_same(bio->bi_bdev)) {
1996 * Various block parts want %current->io_context and lazy ioc
1997 * allocation ends up trading a lot of pain for a small amount of
1998 * memory. Just allocate it upfront. This may fail and block
1999 * layer knows how to live with it.
2001 create_io_context(GFP_ATOMIC, q->node);
2003 if (!blkcg_bio_issue_check(q, bio))
2006 trace_block_bio_queue(q, bio);
2010 bio->bi_error = err;
2016 * generic_make_request - hand a buffer to its device driver for I/O
2017 * @bio: The bio describing the location in memory and on the device.
2019 * generic_make_request() is used to make I/O requests of block
2020 * devices. It is passed a &struct bio, which describes the I/O that needs
2023 * generic_make_request() does not return any status. The
2024 * success/failure status of the request, along with notification of
2025 * completion, is delivered asynchronously through the bio->bi_end_io
2026 * function described (one day) else where.
2028 * The caller of generic_make_request must make sure that bi_io_vec
2029 * are set to describe the memory buffer, and that bi_dev and bi_sector are
2030 * set to describe the device address, and the
2031 * bi_end_io and optionally bi_private are set to describe how
2032 * completion notification should be signaled.
2034 * generic_make_request and the drivers it calls may use bi_next if this
2035 * bio happens to be merged with someone else, and may resubmit the bio to
2036 * a lower device by calling into generic_make_request recursively, which
2037 * means the bio should NOT be touched after the call to ->make_request_fn.
2039 blk_qc_t generic_make_request(struct bio *bio)
2042 * bio_list_on_stack[0] contains bios submitted by the current
2044 * bio_list_on_stack[1] contains bios that were submitted before
2045 * the current make_request_fn, but that haven't been processed
2048 struct bio_list bio_list_on_stack[2];
2049 blk_qc_t ret = BLK_QC_T_NONE;
2051 if (!generic_make_request_checks(bio))
2055 * We only want one ->make_request_fn to be active at a time, else
2056 * stack usage with stacked devices could be a problem. So use
2057 * current->bio_list to keep a list of requests submited by a
2058 * make_request_fn function. current->bio_list is also used as a
2059 * flag to say if generic_make_request is currently active in this
2060 * task or not. If it is NULL, then no make_request is active. If
2061 * it is non-NULL, then a make_request is active, and new requests
2062 * should be added at the tail
2064 if (current->bio_list) {
2065 bio_list_add(¤t->bio_list[0], bio);
2069 /* following loop may be a bit non-obvious, and so deserves some
2071 * Before entering the loop, bio->bi_next is NULL (as all callers
2072 * ensure that) so we have a list with a single bio.
2073 * We pretend that we have just taken it off a longer list, so
2074 * we assign bio_list to a pointer to the bio_list_on_stack,
2075 * thus initialising the bio_list of new bios to be
2076 * added. ->make_request() may indeed add some more bios
2077 * through a recursive call to generic_make_request. If it
2078 * did, we find a non-NULL value in bio_list and re-enter the loop
2079 * from the top. In this case we really did just take the bio
2080 * of the top of the list (no pretending) and so remove it from
2081 * bio_list, and call into ->make_request() again.
2083 BUG_ON(bio->bi_next);
2084 bio_list_init(&bio_list_on_stack[0]);
2085 current->bio_list = bio_list_on_stack;
2087 struct request_queue *q = bdev_get_queue(bio->bi_bdev);
2089 if (likely(blk_queue_enter(q, __GFP_DIRECT_RECLAIM) == 0)) {
2090 struct bio_list lower, same;
2092 /* Create a fresh bio_list for all subordinate requests */
2093 bio_list_on_stack[1] = bio_list_on_stack[0];
2094 bio_list_init(&bio_list_on_stack[0]);
2096 ret = q->make_request_fn(q, bio);
2099 /* sort new bios into those for a lower level
2100 * and those for the same level
2102 bio_list_init(&lower);
2103 bio_list_init(&same);
2104 while ((bio = bio_list_pop(&bio_list_on_stack[0])) != NULL)
2105 if (q == bdev_get_queue(bio->bi_bdev))
2106 bio_list_add(&same, bio);
2108 bio_list_add(&lower, bio);
2109 /* now assemble so we handle the lowest level first */
2110 bio_list_merge(&bio_list_on_stack[0], &lower);
2111 bio_list_merge(&bio_list_on_stack[0], &same);
2112 bio_list_merge(&bio_list_on_stack[0], &bio_list_on_stack[1]);
2116 bio = bio_list_pop(&bio_list_on_stack[0]);
2118 current->bio_list = NULL; /* deactivate */
2123 EXPORT_SYMBOL(generic_make_request);
2125 #ifdef CONFIG_BLK_DEV_IO_TRACE
2126 static inline struct task_struct *get_dirty_task(struct bio *bio)
2129 * Not all the pages in the bio are dirtied by the
2130 * same task but most likely it will be, since the
2131 * sectors accessed on the device must be adjacent.
2133 if (bio->bi_io_vec && bio->bi_io_vec->bv_page &&
2134 bio->bi_io_vec->bv_page->tsk_dirty)
2135 return bio->bi_io_vec->bv_page->tsk_dirty;
2140 static inline struct task_struct *get_dirty_task(struct bio *bio)
2146 #ifdef CONFIG_BLOCK_PERF_FRAMEWORK
2147 #define BLK_PERF_SIZE (1024 * 15)
2148 #define BLK_PERF_HIST_SIZE (sizeof(u32) * BLK_PERF_SIZE)
2150 struct blk_perf_stats {
2154 int buffers_alloced;
2155 ktime_t max_read_time;
2156 ktime_t max_write_time;
2157 ktime_t max_flush_time;
2158 ktime_t min_write_time;
2159 ktime_t min_read_time;
2160 ktime_t min_flush_time;
2161 ktime_t total_write_time;
2162 ktime_t total_read_time;
2163 u64 total_read_size;
2164 u64 total_write_size;
2169 static struct blk_perf_stats blk_perf;
2170 static struct dentry *blk_perf_debug_dir;
2172 static int alloc_histogram_buffers(void)
2176 if (!blk_perf.read_hist)
2177 blk_perf.read_hist = kzalloc(BLK_PERF_HIST_SIZE, GFP_KERNEL);
2179 if (!blk_perf.write_hist)
2180 blk_perf.write_hist = kzalloc(BLK_PERF_HIST_SIZE, GFP_KERNEL);
2182 if (!blk_perf.flush_hist)
2183 blk_perf.flush_hist = kzalloc(BLK_PERF_HIST_SIZE, GFP_KERNEL);
2185 if (!blk_perf.read_hist || !blk_perf.write_hist || !blk_perf.flush_hist)
2189 blk_perf.buffers_alloced = 1;
2193 static void clear_histogram_buffers(void)
2195 if (!blk_perf.buffers_alloced)
2197 memset(blk_perf.read_hist, 0, BLK_PERF_HIST_SIZE);
2198 memset(blk_perf.write_hist, 0, BLK_PERF_HIST_SIZE);
2199 memset(blk_perf.flush_hist, 0, BLK_PERF_HIST_SIZE);
2202 static int enable_perf(void *data, u64 val)
2206 if (!blk_perf.buffers_alloced)
2207 ret = alloc_histogram_buffers();
2212 spin_lock(&blk_perf.lock);
2213 blk_perf.is_enabled = val;
2214 spin_unlock(&blk_perf.lock);
2218 static int is_perf_enabled(void *data, u64 *val)
2220 spin_lock(&blk_perf.lock);
2221 *val = blk_perf.is_enabled;
2222 spin_unlock(&blk_perf.lock);
2226 DEFINE_SIMPLE_ATTRIBUTE(enable_perf_fops, is_perf_enabled, enable_perf,
2229 static char *blk_debug_buffer;
2230 static u32 blk_debug_data_size;
2231 static DEFINE_MUTEX(blk_perf_debug_buffer_mutex);
2233 static ssize_t blk_perf_read(struct file *file, char __user *buf,
2234 size_t count, loff_t *file_pos)
2238 mutex_lock(&blk_perf_debug_buffer_mutex);
2239 ret = simple_read_from_buffer(buf, count, file_pos, blk_debug_buffer,
2240 blk_debug_data_size);
2241 mutex_unlock(&blk_perf_debug_buffer_mutex);
2246 static int blk_debug_buffer_alloc(u32 buffer_size)
2250 mutex_lock(&blk_perf_debug_buffer_mutex);
2251 if (blk_debug_buffer != NULL) {
2252 pr_err("blk_debug_buffer is in use\n");
2256 blk_debug_buffer = kzalloc(buffer_size, GFP_KERNEL);
2257 if (!blk_debug_buffer)
2260 mutex_unlock(&blk_perf_debug_buffer_mutex);
2264 static int blk_perf_close(struct inode *inode, struct file *file)
2266 mutex_lock(&blk_perf_debug_buffer_mutex);
2267 blk_debug_data_size = 0;
2268 kfree(blk_debug_buffer);
2269 blk_debug_buffer = NULL;
2270 mutex_unlock(&blk_perf_debug_buffer_mutex);
2274 static u32 fill_basic_perf_info(char *buffer, u32 buffer_size)
2278 size += scnprintf(buffer + size, buffer_size - size, "\n");
2280 spin_lock(&blk_perf.lock);
2281 size += scnprintf(buffer + size, buffer_size - size,
2282 "max_read_time_ms: %llu\n",
2283 ktime_to_ms(blk_perf.max_read_time));
2285 size += scnprintf(buffer + size, buffer_size - size,
2286 "min_read_time_ms: %llu\n",
2287 ktime_to_ms(blk_perf.min_read_time));
2289 size += scnprintf(buffer + size, buffer_size - size,
2290 "total_read_time_ms: %llu\n",
2291 ktime_to_ms(blk_perf.total_read_time));
2293 size += scnprintf(buffer + size, buffer_size - size,
2294 "total_read_size: %llu\n\n",
2295 blk_perf.total_read_size);
2297 size += scnprintf(buffer + size, buffer_size - size,
2298 "max_write_time_ms: %llu\n",
2299 ktime_to_ms(blk_perf.max_write_time));
2301 size += scnprintf(buffer + size, buffer_size - size,
2302 "min_write_time_ms: %llu\n",
2303 ktime_to_ms(blk_perf.min_write_time));
2305 size += scnprintf(buffer + size, buffer_size - size,
2306 "total_write_time_ms: %llu\n",
2307 ktime_to_ms(blk_perf.total_write_time));
2309 size += scnprintf(buffer + size, buffer_size - size,
2310 "total_write_size: %llu\n\n",
2311 blk_perf.total_write_size);
2313 size += scnprintf(buffer + size, buffer_size - size,
2314 "max_flush_time_ms: %llu\n",
2315 ktime_to_ms(blk_perf.max_flush_time));
2317 size += scnprintf(buffer + size, buffer_size - size,
2318 "min_flush_time_ms: %llu\n\n",
2319 ktime_to_ms(blk_perf.min_flush_time));
2321 spin_unlock(&blk_perf.lock);
2326 static int basic_perf_open(struct inode *inode, struct file *file)
2331 buffer_size = BLK_PERF_HIST_SIZE;
2332 ret = blk_debug_buffer_alloc(buffer_size);
2336 mutex_lock(&blk_perf_debug_buffer_mutex);
2337 blk_debug_data_size = fill_basic_perf_info(blk_debug_buffer,
2339 mutex_unlock(&blk_perf_debug_buffer_mutex);
2344 static const struct file_operations basic_perf_ops = {
2345 .read = blk_perf_read,
2346 .release = blk_perf_close,
2347 .open = basic_perf_open,
2350 static int hist_open_helper(void *hist_buf)
2354 if (!blk_perf.buffers_alloced)
2357 ret = blk_debug_buffer_alloc(BLK_PERF_HIST_SIZE);
2361 spin_lock(&blk_perf.lock);
2362 memcpy(blk_debug_buffer, hist_buf, BLK_PERF_HIST_SIZE);
2363 spin_unlock(&blk_perf.lock);
2365 mutex_lock(&blk_perf_debug_buffer_mutex);
2366 blk_debug_data_size = BLK_PERF_HIST_SIZE;
2367 mutex_unlock(&blk_perf_debug_buffer_mutex);
2371 static int write_hist_open(struct inode *inode, struct file *file)
2373 return hist_open_helper(blk_perf.write_hist);
2376 static const struct file_operations write_hist_ops = {
2377 .read = blk_perf_read,
2378 .release = blk_perf_close,
2379 .open = write_hist_open,
2383 static int read_hist_open(struct inode *inode, struct file *file)
2385 return hist_open_helper(blk_perf.read_hist);
2388 static const struct file_operations read_hist_ops = {
2389 .read = blk_perf_read,
2390 .release = blk_perf_close,
2391 .open = read_hist_open,
2394 static int flush_hist_open(struct inode *inode, struct file *file)
2396 return hist_open_helper(blk_perf.flush_hist);
2399 static const struct file_operations flush_hist_ops = {
2400 .read = blk_perf_read,
2401 .release = blk_perf_close,
2402 .open = flush_hist_open,
2405 static void clear_perf_stats_helper(void)
2407 spin_lock(&blk_perf.lock);
2408 blk_perf.max_write_time = ktime_set(0, 0);
2409 blk_perf.max_read_time = ktime_set(0, 0);
2410 blk_perf.max_flush_time = ktime_set(0, 0);
2411 blk_perf.min_write_time = ktime_set(KTIME_MAX, 0);
2412 blk_perf.min_read_time = ktime_set(KTIME_MAX, 0);
2413 blk_perf.min_flush_time = ktime_set(KTIME_MAX, 0);
2414 blk_perf.total_write_time = ktime_set(0, 0);
2415 blk_perf.total_read_time = ktime_set(0, 0);
2416 blk_perf.total_read_size = 0;
2417 blk_perf.total_write_size = 0;
2418 blk_perf.is_enabled = 0;
2419 clear_histogram_buffers();
2420 spin_unlock(&blk_perf.lock);
2423 static int clear_perf_stats(void *data, u64 val)
2425 clear_perf_stats_helper();
2429 DEFINE_SIMPLE_ATTRIBUTE(clear_perf_stats_fops, NULL, clear_perf_stats,
2432 static void blk_debugfs_init(void)
2434 struct dentry *f_ent;
2436 blk_perf_debug_dir = debugfs_create_dir("block_perf", NULL);
2437 if (IS_ERR(blk_perf_debug_dir)) {
2438 pr_err("Failed to create block_perf debug_fs directory\n");
2442 f_ent = debugfs_create_file("basic_perf", 0400, blk_perf_debug_dir,
2443 NULL, &basic_perf_ops);
2444 if (IS_ERR(f_ent)) {
2445 pr_err("Failed to create debug_fs basic_perf file\n");
2449 f_ent = debugfs_create_file("write_hist", 0400, blk_perf_debug_dir,
2450 NULL, &write_hist_ops);
2451 if (IS_ERR(f_ent)) {
2452 pr_err("Failed to create debug_fs write_hist file\n");
2456 f_ent = debugfs_create_file("read_hist", 0400, blk_perf_debug_dir,
2457 NULL, &read_hist_ops);
2458 if (IS_ERR(f_ent)) {
2459 pr_err("Failed to create debug_fs read_hist file\n");
2463 f_ent = debugfs_create_file("flush_hist", 0400, blk_perf_debug_dir,
2464 NULL, &flush_hist_ops);
2465 if (IS_ERR(f_ent)) {
2466 pr_err("Failed to create debug_fs flush_hist file\n");
2470 f_ent = debugfs_create_file("enable_perf", 0600, blk_perf_debug_dir,
2471 NULL, &enable_perf_fops);
2472 if (IS_ERR(f_ent)) {
2473 pr_err("Failed to create debug_fs enable_perf file\n");
2477 f_ent = debugfs_create_file("clear_perf_stats", 0200,
2478 blk_perf_debug_dir, NULL,
2479 &clear_perf_stats_fops);
2480 if (IS_ERR(f_ent)) {
2481 pr_err("Failed to create debug_fs clear_perf_stats file\n");
2486 static void blk_init_perf(void)
2489 spin_lock_init(&blk_perf.lock);
2491 clear_perf_stats_helper();
2495 static void set_submit_info(struct bio *bio, unsigned int count)
2497 ktime_t submit_time;
2499 if (unlikely(blk_perf.is_enabled)) {
2500 submit_time = ktime_get();
2501 bio->submit_time.tv64 = submit_time.tv64;
2502 bio->blk_sector_count = count;
2506 bio->submit_time.tv64 = 0;
2507 bio->blk_sector_count = 0;
2510 void blk_update_perf_read_write_stats(ktime_t bio_process_time, int is_write,
2513 u32 bio_process_time_ms;
2515 bio_process_time_ms = ktime_to_ms(bio_process_time);
2516 if (bio_process_time_ms >= BLK_PERF_SIZE)
2517 bio_process_time_ms = BLK_PERF_SIZE - 1;
2520 if (ktime_after(bio_process_time, blk_perf.max_write_time))
2521 blk_perf.max_write_time = bio_process_time;
2523 if (ktime_before(bio_process_time, blk_perf.min_write_time))
2524 blk_perf.min_write_time = bio_process_time;
2525 blk_perf.total_write_time =
2526 ktime_add(blk_perf.total_write_time, bio_process_time);
2527 blk_perf.total_write_size += count;
2528 blk_perf.write_hist[bio_process_time_ms] += count;
2531 if (ktime_after(bio_process_time, blk_perf.max_read_time))
2532 blk_perf.max_read_time = bio_process_time;
2534 if (ktime_before(bio_process_time, blk_perf.min_read_time))
2535 blk_perf.min_read_time = bio_process_time;
2536 blk_perf.total_read_time =
2537 ktime_add(blk_perf.total_read_time, bio_process_time);
2538 blk_perf.total_read_size += count;
2539 blk_perf.read_hist[bio_process_time_ms] += count;
2542 void blk_update_perf_stats(struct bio *bio)
2544 ktime_t bio_process_time;
2545 u32 bio_process_time_ms;
2548 spin_lock(&blk_perf.lock);
2549 if (likely(!blk_perf.is_enabled))
2551 if (!bio->submit_time.tv64)
2553 bio_process_time = ktime_sub(ktime_get(), bio->submit_time);
2555 count = bio->blk_sector_count;
2560 if (bio->bi_rw & WRITE ||
2561 unlikely(bio->bi_rw & REQ_WRITE_SAME))
2564 blk_update_perf_read_write_stats(bio_process_time, is_write,
2568 bio_process_time_ms = ktime_to_ms(bio_process_time);
2569 if (bio_process_time_ms >= BLK_PERF_SIZE)
2570 bio_process_time_ms = BLK_PERF_SIZE - 1;
2572 if (ktime_after(bio_process_time, blk_perf.max_flush_time))
2573 blk_perf.max_flush_time = bio_process_time;
2575 if (ktime_before(bio_process_time, blk_perf.min_flush_time))
2576 blk_perf.min_flush_time = bio_process_time;
2578 blk_perf.flush_hist[bio_process_time_ms] += 1;
2581 spin_unlock(&blk_perf.lock);
2585 static inline void set_submit_info(struct bio *bio, unsigned int count)
2591 static inline void blk_init_perf(void)
2594 #endif /* #ifdef CONFIG_BLOCK_PERF_FRAMEWORK */
2597 * submit_bio - submit a bio to the block device layer for I/O
2598 * @rw: whether to %READ or %WRITE, or maybe to %READA (read ahead)
2599 * @bio: The &struct bio which describes the I/O
2601 * submit_bio() is very similar in purpose to generic_make_request(), and
2602 * uses that function to do most of the work. Both are fairly rough
2603 * interfaces; @bio must be presetup and ready for I/O.
2606 blk_qc_t submit_bio(int rw, struct bio *bio)
2608 unsigned int count = 0;
2612 * If it's a regular read/write or a barrier with data attached,
2613 * go through the normal accounting stuff before submission.
2615 if (bio_has_data(bio)) {
2616 if (unlikely(rw & REQ_WRITE_SAME))
2617 count = bdev_logical_block_size(bio->bi_bdev) >> 9;
2619 count = bio_sectors(bio);
2622 count_vm_events(PGPGOUT, count);
2624 task_io_account_read(bio->bi_iter.bi_size);
2625 count_vm_events(PGPGIN, count);
2628 if (unlikely(block_dump)) {
2629 char b[BDEVNAME_SIZE];
2630 struct task_struct *tsk;
2632 tsk = get_dirty_task(bio);
2633 printk(KERN_DEBUG "%s(%d): %s block %Lu on %s (%u sectors)\n",
2634 tsk->comm, task_pid_nr(tsk),
2635 (rw & WRITE) ? "WRITE" : "READ",
2636 (unsigned long long)bio->bi_iter.bi_sector,
2637 bdevname(bio->bi_bdev, b),
2642 set_submit_info(bio, count);
2643 return generic_make_request(bio);
2645 EXPORT_SYMBOL(submit_bio);
2648 * blk_cloned_rq_check_limits - Helper function to check a cloned request
2649 * for new the queue limits
2651 * @rq: the request being checked
2654 * @rq may have been made based on weaker limitations of upper-level queues
2655 * in request stacking drivers, and it may violate the limitation of @q.
2656 * Since the block layer and the underlying device driver trust @rq
2657 * after it is inserted to @q, it should be checked against @q before
2658 * the insertion using this generic function.
2660 * Request stacking drivers like request-based dm may change the queue
2661 * limits when retrying requests on other queues. Those requests need
2662 * to be checked against the new queue limits again during dispatch.
2664 static int blk_cloned_rq_check_limits(struct request_queue *q,
2667 if (blk_rq_sectors(rq) > blk_queue_get_max_sectors(q, rq->cmd_flags)) {
2668 printk(KERN_ERR "%s: over max size limit.\n", __func__);
2673 * queue's settings related to segment counting like q->bounce_pfn
2674 * may differ from that of other stacking queues.
2675 * Recalculate it to check the request correctly on this queue's
2678 blk_recalc_rq_segments(rq);
2679 if (rq->nr_phys_segments > queue_max_segments(q)) {
2680 printk(KERN_ERR "%s: over max segments limit.\n", __func__);
2688 * blk_insert_cloned_request - Helper for stacking drivers to submit a request
2689 * @q: the queue to submit the request
2690 * @rq: the request being queued
2692 int blk_insert_cloned_request(struct request_queue *q, struct request *rq)
2694 unsigned long flags;
2695 int where = ELEVATOR_INSERT_BACK;
2697 if (blk_cloned_rq_check_limits(q, rq))
2701 should_fail_request(&rq->rq_disk->part0, blk_rq_bytes(rq)))
2705 if (blk_queue_io_stat(q))
2706 blk_account_io_start(rq, true);
2707 blk_mq_insert_request(rq, false, true, false);
2711 spin_lock_irqsave(q->queue_lock, flags);
2712 if (unlikely(blk_queue_dying(q))) {
2713 spin_unlock_irqrestore(q->queue_lock, flags);
2718 * Submitting request must be dequeued before calling this function
2719 * because it will be linked to another request_queue
2721 BUG_ON(blk_queued_rq(rq));
2723 if (rq->cmd_flags & (REQ_FLUSH|REQ_FUA))
2724 where = ELEVATOR_INSERT_FLUSH;
2726 add_acct_request(q, rq, where);
2727 if (where == ELEVATOR_INSERT_FLUSH)
2729 spin_unlock_irqrestore(q->queue_lock, flags);
2733 EXPORT_SYMBOL_GPL(blk_insert_cloned_request);
2736 * blk_rq_err_bytes - determine number of bytes till the next failure boundary
2737 * @rq: request to examine
2740 * A request could be merge of IOs which require different failure
2741 * handling. This function determines the number of bytes which
2742 * can be failed from the beginning of the request without
2743 * crossing into area which need to be retried further.
2746 * The number of bytes to fail.
2749 * queue_lock must be held.
2751 unsigned int blk_rq_err_bytes(const struct request *rq)
2753 unsigned int ff = rq->cmd_flags & REQ_FAILFAST_MASK;
2754 unsigned int bytes = 0;
2757 if (!(rq->cmd_flags & REQ_MIXED_MERGE))
2758 return blk_rq_bytes(rq);
2761 * Currently the only 'mixing' which can happen is between
2762 * different fastfail types. We can safely fail portions
2763 * which have all the failfast bits that the first one has -
2764 * the ones which are at least as eager to fail as the first
2767 for (bio = rq->bio; bio; bio = bio->bi_next) {
2768 if ((bio->bi_rw & ff) != ff)
2770 bytes += bio->bi_iter.bi_size;
2773 /* this could lead to infinite loop */
2774 BUG_ON(blk_rq_bytes(rq) && !bytes);
2777 EXPORT_SYMBOL_GPL(blk_rq_err_bytes);
2779 void blk_account_io_completion(struct request *req, unsigned int bytes)
2781 if (blk_do_io_stat(req)) {
2782 const int rw = rq_data_dir(req);
2783 struct hd_struct *part;
2786 cpu = part_stat_lock();
2788 part_stat_add(cpu, part, sectors[rw], bytes >> 9);
2793 void blk_account_io_done(struct request *req)
2796 * Account IO completion. flush_rq isn't accounted as a
2797 * normal IO on queueing nor completion. Accounting the
2798 * containing request is enough.
2800 if (blk_do_io_stat(req) && !(req->cmd_flags & REQ_FLUSH_SEQ)) {
2801 unsigned long duration = jiffies - req->start_time;
2802 const int rw = rq_data_dir(req);
2803 struct hd_struct *part;
2806 cpu = part_stat_lock();
2809 part_stat_inc(cpu, part, ios[rw]);
2810 part_stat_add(cpu, part, ticks[rw], duration);
2811 part_round_stats(cpu, part);
2812 part_dec_in_flight(part, rw);
2814 hd_struct_put(part);
2821 * Don't process normal requests when queue is suspended
2822 * or in the process of suspending/resuming
2824 static struct request *blk_pm_peek_request(struct request_queue *q,
2827 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
2828 (q->rpm_status != RPM_ACTIVE && !(rq->cmd_flags & REQ_PM))))
2834 static inline struct request *blk_pm_peek_request(struct request_queue *q,
2841 void blk_account_io_start(struct request *rq, bool new_io)
2843 struct hd_struct *part;
2844 int rw = rq_data_dir(rq);
2847 if (!blk_do_io_stat(rq))
2850 cpu = part_stat_lock();
2854 part_stat_inc(cpu, part, merges[rw]);
2856 part = disk_map_sector_rcu(rq->rq_disk, blk_rq_pos(rq));
2857 if (!hd_struct_try_get(part)) {
2859 * The partition is already being removed,
2860 * the request will be accounted on the disk only
2862 * We take a reference on disk->part0 although that
2863 * partition will never be deleted, so we can treat
2864 * it as any other partition.
2866 part = &rq->rq_disk->part0;
2867 hd_struct_get(part);
2869 part_round_stats(cpu, part);
2870 part_inc_in_flight(part, rw);
2878 * blk_peek_request - peek at the top of a request queue
2879 * @q: request queue to peek at
2882 * Return the request at the top of @q. The returned request
2883 * should be started using blk_start_request() before LLD starts
2887 * Pointer to the request at the top of @q if available. Null
2891 * queue_lock must be held.
2893 struct request *blk_peek_request(struct request_queue *q)
2898 while ((rq = __elv_next_request(q)) != NULL) {
2900 rq = blk_pm_peek_request(q, rq);
2904 if (!(rq->cmd_flags & REQ_STARTED)) {
2906 * This is the first time the device driver
2907 * sees this request (possibly after
2908 * requeueing). Notify IO scheduler.
2910 if (rq->cmd_flags & REQ_SORTED)
2911 elv_activate_rq(q, rq);
2914 * just mark as started even if we don't start
2915 * it, a request that has been delayed should
2916 * not be passed by new incoming requests
2918 rq->cmd_flags |= REQ_STARTED;
2919 trace_block_rq_issue(q, rq);
2922 if (!q->boundary_rq || q->boundary_rq == rq) {
2923 q->end_sector = rq_end_sector(rq);
2924 q->boundary_rq = NULL;
2927 if (rq->cmd_flags & REQ_DONTPREP)
2930 if (q->dma_drain_size && blk_rq_bytes(rq)) {
2932 * make sure space for the drain appears we
2933 * know we can do this because max_hw_segments
2934 * has been adjusted to be one fewer than the
2937 rq->nr_phys_segments++;
2943 ret = q->prep_rq_fn(q, rq);
2944 if (ret == BLKPREP_OK) {
2946 } else if (ret == BLKPREP_DEFER) {
2948 * the request may have been (partially) prepped.
2949 * we need to keep this request in the front to
2950 * avoid resource deadlock. REQ_STARTED will
2951 * prevent other fs requests from passing this one.
2953 if (q->dma_drain_size && blk_rq_bytes(rq) &&
2954 !(rq->cmd_flags & REQ_DONTPREP)) {
2956 * remove the space for the drain we added
2957 * so that we don't add it again
2959 --rq->nr_phys_segments;
2964 } else if (ret == BLKPREP_KILL) {
2965 rq->cmd_flags |= REQ_QUIET;
2967 * Mark this request as started so we don't trigger
2968 * any debug logic in the end I/O path.
2970 blk_start_request(rq);
2971 __blk_end_request_all(rq, -EIO);
2973 printk(KERN_ERR "%s: bad return=%d\n", __func__, ret);
2980 EXPORT_SYMBOL(blk_peek_request);
2982 void blk_dequeue_request(struct request *rq)
2984 struct request_queue *q = rq->q;
2986 BUG_ON(list_empty(&rq->queuelist));
2987 BUG_ON(ELV_ON_HASH(rq));
2989 list_del_init(&rq->queuelist);
2992 * the time frame between a request being removed from the lists
2993 * and to it is freed is accounted as io that is in progress at
2996 if (blk_account_rq(rq)) {
2997 q->in_flight[rq_is_sync(rq)]++;
2998 set_io_start_time_ns(rq);
3003 * blk_start_request - start request processing on the driver
3004 * @req: request to dequeue
3007 * Dequeue @req and start timeout timer on it. This hands off the
3008 * request to the driver.
3010 * Block internal functions which don't want to start timer should
3011 * call blk_dequeue_request().
3014 * queue_lock must be held.
3016 void blk_start_request(struct request *req)
3018 blk_dequeue_request(req);
3021 * We are now handing the request to the hardware, initialize
3022 * resid_len to full count and add the timeout handler.
3024 req->resid_len = blk_rq_bytes(req);
3025 if (unlikely(blk_bidi_rq(req)))
3026 req->next_rq->resid_len = blk_rq_bytes(req->next_rq);
3028 BUG_ON(test_bit(REQ_ATOM_COMPLETE, &req->atomic_flags));
3031 EXPORT_SYMBOL(blk_start_request);
3034 * blk_fetch_request - fetch a request from a request queue
3035 * @q: request queue to fetch a request from
3038 * Return the request at the top of @q. The request is started on
3039 * return and LLD can start processing it immediately.
3042 * Pointer to the request at the top of @q if available. Null
3046 * queue_lock must be held.
3048 struct request *blk_fetch_request(struct request_queue *q)
3052 rq = blk_peek_request(q);
3054 blk_start_request(rq);
3057 EXPORT_SYMBOL(blk_fetch_request);
3060 * blk_update_request - Special helper function for request stacking drivers
3061 * @req: the request being processed
3062 * @error: %0 for success, < %0 for error
3063 * @nr_bytes: number of bytes to complete @req
3066 * Ends I/O on a number of bytes attached to @req, but doesn't complete
3067 * the request structure even if @req doesn't have leftover.
3068 * If @req has leftover, sets it up for the next range of segments.
3070 * This special helper function is only for request stacking drivers
3071 * (e.g. request-based dm) so that they can handle partial completion.
3072 * Actual device drivers should use blk_end_request instead.
3074 * Passing the result of blk_rq_bytes() as @nr_bytes guarantees
3075 * %false return from this function.
3078 * %false - this request doesn't have any more data
3079 * %true - this request has more data
3081 bool blk_update_request(struct request *req, int error, unsigned int nr_bytes)
3085 trace_block_rq_complete(req->q, req, nr_bytes);
3091 * For fs requests, rq is just carrier of independent bio's
3092 * and each partial completion should be handled separately.
3093 * Reset per-request error on each partial completion.
3095 * TODO: tj: This is too subtle. It would be better to let
3096 * low level drivers do what they see fit.
3098 if (req->cmd_type == REQ_TYPE_FS)
3101 if (error && req->cmd_type == REQ_TYPE_FS &&
3102 !(req->cmd_flags & REQ_QUIET)) {
3107 error_type = "recoverable transport";
3110 error_type = "critical target";
3113 error_type = "critical nexus";
3116 error_type = "timeout";
3119 error_type = "critical space allocation";
3122 error_type = "critical medium";
3129 printk_ratelimited(KERN_ERR "%s: %s error, dev %s, sector %llu\n",
3130 __func__, error_type, req->rq_disk ?
3131 req->rq_disk->disk_name : "?",
3132 (unsigned long long)blk_rq_pos(req));
3136 blk_account_io_completion(req, nr_bytes);
3141 * Check for this if flagged, Req based dm needs to perform
3142 * post processing, hence dont end bios or request.DM
3145 if (bio_flagged(req->bio, BIO_DONTFREE))
3149 struct bio *bio = req->bio;
3150 unsigned bio_bytes = min(bio->bi_iter.bi_size, nr_bytes);
3152 if (bio_bytes == bio->bi_iter.bi_size)
3153 req->bio = bio->bi_next;
3155 req_bio_endio(req, bio, bio_bytes, error);
3157 total_bytes += bio_bytes;
3158 nr_bytes -= bio_bytes;
3169 * Reset counters so that the request stacking driver
3170 * can find how many bytes remain in the request
3173 req->__data_len = 0;
3177 req->__data_len -= total_bytes;
3179 /* update sector only for requests with clear definition of sector */
3180 if (req->cmd_type == REQ_TYPE_FS)
3181 req->__sector += total_bytes >> 9;
3183 /* mixed attributes always follow the first bio */
3184 if (req->cmd_flags & REQ_MIXED_MERGE) {
3185 req->cmd_flags &= ~REQ_FAILFAST_MASK;
3186 req->cmd_flags |= req->bio->bi_rw & REQ_FAILFAST_MASK;
3190 * If total number of sectors is less than the first segment
3191 * size, something has gone terribly wrong.
3193 if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {
3194 blk_dump_rq_flags(req, "request botched");
3195 req->__data_len = blk_rq_cur_bytes(req);
3198 /* recalculate the number of segments */
3199 blk_recalc_rq_segments(req);
3203 EXPORT_SYMBOL_GPL(blk_update_request);
3205 static bool blk_update_bidi_request(struct request *rq, int error,
3206 unsigned int nr_bytes,
3207 unsigned int bidi_bytes)
3209 if (blk_update_request(rq, error, nr_bytes))
3212 /* Bidi request must be completed as a whole */
3213 if (unlikely(blk_bidi_rq(rq)) &&
3214 blk_update_request(rq->next_rq, error, bidi_bytes))
3217 if (blk_queue_add_random(rq->q))
3218 add_disk_randomness(rq->rq_disk);
3224 * blk_unprep_request - unprepare a request
3227 * This function makes a request ready for complete resubmission (or
3228 * completion). It happens only after all error handling is complete,
3229 * so represents the appropriate moment to deallocate any resources
3230 * that were allocated to the request in the prep_rq_fn. The queue
3231 * lock is held when calling this.
3233 void blk_unprep_request(struct request *req)
3235 struct request_queue *q = req->q;
3237 req->cmd_flags &= ~REQ_DONTPREP;
3238 if (q->unprep_rq_fn)
3239 q->unprep_rq_fn(q, req);
3241 EXPORT_SYMBOL_GPL(blk_unprep_request);
3244 * queue lock must be held
3246 void blk_finish_request(struct request *req, int error)
3248 if (req->cmd_flags & REQ_QUEUED)
3249 blk_queue_end_tag(req->q, req);
3251 BUG_ON(blk_queued_rq(req));
3253 if (unlikely(laptop_mode) && req->cmd_type == REQ_TYPE_FS)
3254 laptop_io_completion(&req->q->backing_dev_info);
3256 blk_delete_timer(req);
3258 if (req->cmd_flags & REQ_DONTPREP)
3259 blk_unprep_request(req);
3261 blk_account_io_done(req);
3264 req->end_io(req, error);
3266 if (blk_bidi_rq(req))
3267 __blk_put_request(req->next_rq->q, req->next_rq);
3269 __blk_put_request(req->q, req);
3272 EXPORT_SYMBOL(blk_finish_request);
3275 * blk_end_bidi_request - Complete a bidi request
3276 * @rq: the request to complete
3277 * @error: %0 for success, < %0 for error
3278 * @nr_bytes: number of bytes to complete @rq
3279 * @bidi_bytes: number of bytes to complete @rq->next_rq
3282 * Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
3283 * Drivers that supports bidi can safely call this member for any
3284 * type of request, bidi or uni. In the later case @bidi_bytes is
3288 * %false - we are done with this request
3289 * %true - still buffers pending for this request
3291 static bool blk_end_bidi_request(struct request *rq, int error,
3292 unsigned int nr_bytes, unsigned int bidi_bytes)
3294 struct request_queue *q = rq->q;
3295 unsigned long flags;
3297 if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
3300 spin_lock_irqsave(q->queue_lock, flags);
3301 blk_finish_request(rq, error);
3302 spin_unlock_irqrestore(q->queue_lock, flags);
3308 * __blk_end_bidi_request - Complete a bidi request with queue lock held
3309 * @rq: the request to complete
3310 * @error: %0 for success, < %0 for error
3311 * @nr_bytes: number of bytes to complete @rq
3312 * @bidi_bytes: number of bytes to complete @rq->next_rq
3315 * Identical to blk_end_bidi_request() except that queue lock is
3316 * assumed to be locked on entry and remains so on return.
3319 * %false - we are done with this request
3320 * %true - still buffers pending for this request
3322 bool __blk_end_bidi_request(struct request *rq, int error,
3323 unsigned int nr_bytes, unsigned int bidi_bytes)
3325 if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
3328 blk_finish_request(rq, error);
3334 * blk_end_request - Helper function for drivers to complete the request.
3335 * @rq: the request being processed
3336 * @error: %0 for success, < %0 for error
3337 * @nr_bytes: number of bytes to complete
3340 * Ends I/O on a number of bytes attached to @rq.
3341 * If @rq has leftover, sets it up for the next range of segments.
3344 * %false - we are done with this request
3345 * %true - still buffers pending for this request
3347 bool blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
3349 return blk_end_bidi_request(rq, error, nr_bytes, 0);
3351 EXPORT_SYMBOL(blk_end_request);
3354 * blk_end_request_all - Helper function for drives to finish the request.
3355 * @rq: the request to finish
3356 * @error: %0 for success, < %0 for error
3359 * Completely finish @rq.
3361 void blk_end_request_all(struct request *rq, int error)
3364 unsigned int bidi_bytes = 0;
3366 if (unlikely(blk_bidi_rq(rq)))
3367 bidi_bytes = blk_rq_bytes(rq->next_rq);
3369 pending = blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
3372 EXPORT_SYMBOL(blk_end_request_all);
3375 * blk_end_request_cur - Helper function to finish the current request chunk.
3376 * @rq: the request to finish the current chunk for
3377 * @error: %0 for success, < %0 for error
3380 * Complete the current consecutively mapped chunk from @rq.
3383 * %false - we are done with this request
3384 * %true - still buffers pending for this request
3386 bool blk_end_request_cur(struct request *rq, int error)
3388 return blk_end_request(rq, error, blk_rq_cur_bytes(rq));
3390 EXPORT_SYMBOL(blk_end_request_cur);
3393 * blk_end_request_err - Finish a request till the next failure boundary.
3394 * @rq: the request to finish till the next failure boundary for
3395 * @error: must be negative errno
3398 * Complete @rq till the next failure boundary.
3401 * %false - we are done with this request
3402 * %true - still buffers pending for this request
3404 bool blk_end_request_err(struct request *rq, int error)
3406 WARN_ON(error >= 0);
3407 return blk_end_request(rq, error, blk_rq_err_bytes(rq));
3409 EXPORT_SYMBOL_GPL(blk_end_request_err);
3412 * __blk_end_request - Helper function for drivers to complete the request.
3413 * @rq: the request being processed
3414 * @error: %0 for success, < %0 for error
3415 * @nr_bytes: number of bytes to complete
3418 * Must be called with queue lock held unlike blk_end_request().
3421 * %false - we are done with this request
3422 * %true - still buffers pending for this request
3424 bool __blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
3426 return __blk_end_bidi_request(rq, error, nr_bytes, 0);
3428 EXPORT_SYMBOL(__blk_end_request);
3431 * __blk_end_request_all - Helper function for drives to finish the request.
3432 * @rq: the request to finish
3433 * @error: %0 for success, < %0 for error
3436 * Completely finish @rq. Must be called with queue lock held.
3438 void __blk_end_request_all(struct request *rq, int error)
3441 unsigned int bidi_bytes = 0;
3443 if (unlikely(blk_bidi_rq(rq)))
3444 bidi_bytes = blk_rq_bytes(rq->next_rq);
3446 pending = __blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
3449 EXPORT_SYMBOL(__blk_end_request_all);
3452 * __blk_end_request_cur - Helper function to finish the current request chunk.
3453 * @rq: the request to finish the current chunk for
3454 * @error: %0 for success, < %0 for error
3457 * Complete the current consecutively mapped chunk from @rq. Must
3458 * be called with queue lock held.
3461 * %false - we are done with this request
3462 * %true - still buffers pending for this request
3464 bool __blk_end_request_cur(struct request *rq, int error)
3466 return __blk_end_request(rq, error, blk_rq_cur_bytes(rq));
3468 EXPORT_SYMBOL(__blk_end_request_cur);
3471 * __blk_end_request_err - Finish a request till the next failure boundary.
3472 * @rq: the request to finish till the next failure boundary for
3473 * @error: must be negative errno
3476 * Complete @rq till the next failure boundary. Must be called
3477 * with queue lock held.
3480 * %false - we are done with this request
3481 * %true - still buffers pending for this request
3483 bool __blk_end_request_err(struct request *rq, int error)
3485 WARN_ON(error >= 0);
3486 return __blk_end_request(rq, error, blk_rq_err_bytes(rq));
3488 EXPORT_SYMBOL_GPL(__blk_end_request_err);
3490 void blk_rq_bio_prep(struct request_queue *q, struct request *rq,
3493 /* Bit 0 (R/W) is identical in rq->cmd_flags and bio->bi_rw */
3494 rq->cmd_flags |= bio->bi_rw & REQ_WRITE;
3496 if (bio_has_data(bio))
3497 rq->nr_phys_segments = bio_phys_segments(q, bio);
3499 rq->__data_len = bio->bi_iter.bi_size;
3500 rq->bio = rq->biotail = bio;
3503 rq->rq_disk = bio->bi_bdev->bd_disk;
3506 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE
3508 * rq_flush_dcache_pages - Helper function to flush all pages in a request
3509 * @rq: the request to be flushed
3512 * Flush all pages in @rq.
3514 void rq_flush_dcache_pages(struct request *rq)
3516 struct req_iterator iter;
3517 struct bio_vec bvec;
3519 rq_for_each_segment(bvec, rq, iter)
3520 flush_dcache_page(bvec.bv_page);
3522 EXPORT_SYMBOL_GPL(rq_flush_dcache_pages);
3526 * blk_lld_busy - Check if underlying low-level drivers of a device are busy
3527 * @q : the queue of the device being checked
3530 * Check if underlying low-level drivers of a device are busy.
3531 * If the drivers want to export their busy state, they must set own
3532 * exporting function using blk_queue_lld_busy() first.
3534 * Basically, this function is used only by request stacking drivers
3535 * to stop dispatching requests to underlying devices when underlying
3536 * devices are busy. This behavior helps more I/O merging on the queue
3537 * of the request stacking driver and prevents I/O throughput regression
3538 * on burst I/O load.
3541 * 0 - Not busy (The request stacking driver should dispatch request)
3542 * 1 - Busy (The request stacking driver should stop dispatching request)
3544 int blk_lld_busy(struct request_queue *q)
3547 return q->lld_busy_fn(q);
3551 EXPORT_SYMBOL_GPL(blk_lld_busy);
3554 * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
3555 * @rq: the clone request to be cleaned up
3558 * Free all bios in @rq for a cloned request.
3560 void blk_rq_unprep_clone(struct request *rq)
3564 while ((bio = rq->bio) != NULL) {
3565 rq->bio = bio->bi_next;
3570 EXPORT_SYMBOL_GPL(blk_rq_unprep_clone);
3573 * Copy attributes of the original request to the clone request.
3574 * The actual data parts (e.g. ->cmd, ->sense) are not copied.
3576 static void __blk_rq_prep_clone(struct request *dst, struct request *src)
3578 dst->cpu = src->cpu;
3579 dst->cmd_flags |= (src->cmd_flags & REQ_CLONE_MASK) | REQ_NOMERGE;
3580 dst->cmd_type = src->cmd_type;
3581 dst->__sector = blk_rq_pos(src);
3582 dst->__data_len = blk_rq_bytes(src);
3583 dst->nr_phys_segments = src->nr_phys_segments;
3584 dst->ioprio = src->ioprio;
3585 dst->extra_len = src->extra_len;
3589 * blk_rq_prep_clone - Helper function to setup clone request
3590 * @rq: the request to be setup
3591 * @rq_src: original request to be cloned
3592 * @bs: bio_set that bios for clone are allocated from
3593 * @gfp_mask: memory allocation mask for bio
3594 * @bio_ctr: setup function to be called for each clone bio.
3595 * Returns %0 for success, non %0 for failure.
3596 * @data: private data to be passed to @bio_ctr
3599 * Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
3600 * The actual data parts of @rq_src (e.g. ->cmd, ->sense)
3601 * are not copied, and copying such parts is the caller's responsibility.
3602 * Also, pages which the original bios are pointing to are not copied
3603 * and the cloned bios just point same pages.
3604 * So cloned bios must be completed before original bios, which means
3605 * the caller must complete @rq before @rq_src.
3607 int blk_rq_prep_clone(struct request *rq, struct request *rq_src,
3608 struct bio_set *bs, gfp_t gfp_mask,
3609 int (*bio_ctr)(struct bio *, struct bio *, void *),
3612 struct bio *bio, *bio_src;
3617 __rq_for_each_bio(bio_src, rq_src) {
3618 bio = bio_clone_fast(bio_src, gfp_mask, bs);
3622 if (bio_ctr && bio_ctr(bio, bio_src, data))
3626 rq->biotail->bi_next = bio;
3629 rq->bio = rq->biotail = bio;
3632 __blk_rq_prep_clone(rq, rq_src);
3639 blk_rq_unprep_clone(rq);
3643 EXPORT_SYMBOL_GPL(blk_rq_prep_clone);
3645 int kblockd_schedule_work(struct work_struct *work)
3647 return queue_work(kblockd_workqueue, work);
3649 EXPORT_SYMBOL(kblockd_schedule_work);
3651 int kblockd_schedule_delayed_work(struct delayed_work *dwork,
3652 unsigned long delay)
3654 return queue_delayed_work(kblockd_workqueue, dwork, delay);
3656 EXPORT_SYMBOL(kblockd_schedule_delayed_work);
3658 int kblockd_schedule_delayed_work_on(int cpu, struct delayed_work *dwork,
3659 unsigned long delay)
3661 return queue_delayed_work_on(cpu, kblockd_workqueue, dwork, delay);
3663 EXPORT_SYMBOL(kblockd_schedule_delayed_work_on);
3666 * blk_start_plug - initialize blk_plug and track it inside the task_struct
3667 * @plug: The &struct blk_plug that needs to be initialized
3670 * Tracking blk_plug inside the task_struct will help with auto-flushing the
3671 * pending I/O should the task end up blocking between blk_start_plug() and
3672 * blk_finish_plug(). This is important from a performance perspective, but
3673 * also ensures that we don't deadlock. For instance, if the task is blocking
3674 * for a memory allocation, memory reclaim could end up wanting to free a
3675 * page belonging to that request that is currently residing in our private
3676 * plug. By flushing the pending I/O when the process goes to sleep, we avoid
3677 * this kind of deadlock.
3679 void blk_start_plug(struct blk_plug *plug)
3681 struct task_struct *tsk = current;
3684 * If this is a nested plug, don't actually assign it.
3689 INIT_LIST_HEAD(&plug->list);
3690 INIT_LIST_HEAD(&plug->mq_list);
3691 INIT_LIST_HEAD(&plug->cb_list);
3693 * Store ordering should not be needed here, since a potential
3694 * preempt will imply a full memory barrier
3698 EXPORT_SYMBOL(blk_start_plug);
3700 static int plug_rq_cmp(void *priv, struct list_head *a, struct list_head *b)
3702 struct request *rqa = container_of(a, struct request, queuelist);
3703 struct request *rqb = container_of(b, struct request, queuelist);
3705 return !(rqa->q < rqb->q ||
3706 (rqa->q == rqb->q && blk_rq_pos(rqa) < blk_rq_pos(rqb)));
3710 * If 'from_schedule' is true, then postpone the dispatch of requests
3711 * until a safe kblockd context. We due this to avoid accidental big
3712 * additional stack usage in driver dispatch, in places where the originally
3713 * plugger did not intend it.
3715 static void queue_unplugged(struct request_queue *q, unsigned int depth,
3717 __releases(q->queue_lock)
3719 trace_block_unplug(q, depth, !from_schedule);
3722 blk_run_queue_async(q);
3725 spin_unlock(q->queue_lock);
3728 static void flush_plug_callbacks(struct blk_plug *plug, bool from_schedule)
3730 LIST_HEAD(callbacks);
3732 while (!list_empty(&plug->cb_list)) {
3733 list_splice_init(&plug->cb_list, &callbacks);
3735 while (!list_empty(&callbacks)) {
3736 struct blk_plug_cb *cb = list_first_entry(&callbacks,
3739 list_del(&cb->list);
3740 cb->callback(cb, from_schedule);
3745 struct blk_plug_cb *blk_check_plugged(blk_plug_cb_fn unplug, void *data,
3748 struct blk_plug *plug = current->plug;
3749 struct blk_plug_cb *cb;
3754 list_for_each_entry(cb, &plug->cb_list, list)
3755 if (cb->callback == unplug && cb->data == data)
3758 /* Not currently on the callback list */
3759 BUG_ON(size < sizeof(*cb));
3760 cb = kzalloc(size, GFP_ATOMIC);
3763 cb->callback = unplug;
3764 list_add(&cb->list, &plug->cb_list);
3768 EXPORT_SYMBOL(blk_check_plugged);
3770 void blk_flush_plug_list(struct blk_plug *plug, bool from_schedule)
3772 struct request_queue *q;
3773 unsigned long flags;
3778 flush_plug_callbacks(plug, from_schedule);
3780 if (!list_empty(&plug->mq_list))
3781 blk_mq_flush_plug_list(plug, from_schedule);
3783 if (list_empty(&plug->list))
3786 list_splice_init(&plug->list, &list);
3788 list_sort(NULL, &list, plug_rq_cmp);
3794 * Save and disable interrupts here, to avoid doing it for every
3795 * queue lock we have to take.
3797 local_irq_save(flags);
3798 while (!list_empty(&list)) {
3799 rq = list_entry_rq(list.next);
3800 list_del_init(&rq->queuelist);
3804 * This drops the queue lock
3807 queue_unplugged(q, depth, from_schedule);
3810 spin_lock(q->queue_lock);
3814 * Short-circuit if @q is dead
3816 if (unlikely(blk_queue_dying(q))) {
3817 __blk_end_request_all(rq, -ENODEV);
3822 * rq is already accounted, so use raw insert
3824 if (rq->cmd_flags & (REQ_FLUSH | REQ_FUA))
3825 __elv_add_request(q, rq, ELEVATOR_INSERT_FLUSH);
3827 __elv_add_request(q, rq, ELEVATOR_INSERT_SORT_MERGE);
3833 * This drops the queue lock
3836 queue_unplugged(q, depth, from_schedule);
3838 local_irq_restore(flags);
3841 void blk_finish_plug(struct blk_plug *plug)
3843 if (plug != current->plug)
3845 blk_flush_plug_list(plug, false);
3847 current->plug = NULL;
3849 EXPORT_SYMBOL(blk_finish_plug);
3851 bool blk_poll(struct request_queue *q, blk_qc_t cookie)
3853 struct blk_plug *plug;
3856 if (!q->mq_ops || !q->mq_ops->poll || !blk_qc_t_valid(cookie) ||
3857 !test_bit(QUEUE_FLAG_POLL, &q->queue_flags))
3860 plug = current->plug;
3862 blk_flush_plug_list(plug, false);
3864 state = current->state;
3865 while (!need_resched()) {
3866 unsigned int queue_num = blk_qc_t_to_queue_num(cookie);
3867 struct blk_mq_hw_ctx *hctx = q->queue_hw_ctx[queue_num];
3870 hctx->poll_invoked++;
3872 ret = q->mq_ops->poll(hctx, blk_qc_t_to_tag(cookie));
3874 hctx->poll_success++;
3875 set_current_state(TASK_RUNNING);
3879 if (signal_pending_state(state, current))
3880 set_current_state(TASK_RUNNING);
3882 if (current->state == TASK_RUNNING)
3894 * blk_pm_runtime_init - Block layer runtime PM initialization routine
3895 * @q: the queue of the device
3896 * @dev: the device the queue belongs to
3899 * Initialize runtime-PM-related fields for @q and start auto suspend for
3900 * @dev. Drivers that want to take advantage of request-based runtime PM
3901 * should call this function after @dev has been initialized, and its
3902 * request queue @q has been allocated, and runtime PM for it can not happen
3903 * yet(either due to disabled/forbidden or its usage_count > 0). In most
3904 * cases, driver should call this function before any I/O has taken place.
3906 * This function takes care of setting up using auto suspend for the device,
3907 * the autosuspend delay is set to -1 to make runtime suspend impossible
3908 * until an updated value is either set by user or by driver. Drivers do
3909 * not need to touch other autosuspend settings.
3911 * The block layer runtime PM is request based, so only works for drivers
3912 * that use request as their IO unit instead of those directly use bio's.
3914 void blk_pm_runtime_init(struct request_queue *q, struct device *dev)
3917 q->rpm_status = RPM_ACTIVE;
3918 pm_runtime_set_autosuspend_delay(q->dev, -1);
3919 pm_runtime_use_autosuspend(q->dev);
3921 EXPORT_SYMBOL(blk_pm_runtime_init);
3924 * blk_pre_runtime_suspend - Pre runtime suspend check
3925 * @q: the queue of the device
3928 * This function will check if runtime suspend is allowed for the device
3929 * by examining if there are any requests pending in the queue. If there
3930 * are requests pending, the device can not be runtime suspended; otherwise,
3931 * the queue's status will be updated to SUSPENDING and the driver can
3932 * proceed to suspend the device.
3934 * For the not allowed case, we mark last busy for the device so that
3935 * runtime PM core will try to autosuspend it some time later.
3937 * This function should be called near the start of the device's
3938 * runtime_suspend callback.
3941 * 0 - OK to runtime suspend the device
3942 * -EBUSY - Device should not be runtime suspended
3944 int blk_pre_runtime_suspend(struct request_queue *q)
3951 spin_lock_irq(q->queue_lock);
3952 if (q->nr_pending) {
3954 pm_runtime_mark_last_busy(q->dev);
3956 q->rpm_status = RPM_SUSPENDING;
3958 spin_unlock_irq(q->queue_lock);
3961 EXPORT_SYMBOL(blk_pre_runtime_suspend);
3964 * blk_post_runtime_suspend - Post runtime suspend processing
3965 * @q: the queue of the device
3966 * @err: return value of the device's runtime_suspend function
3969 * Update the queue's runtime status according to the return value of the
3970 * device's runtime suspend function and mark last busy for the device so
3971 * that PM core will try to auto suspend the device at a later time.
3973 * This function should be called near the end of the device's
3974 * runtime_suspend callback.
3976 void blk_post_runtime_suspend(struct request_queue *q, int err)
3981 spin_lock_irq(q->queue_lock);
3983 q->rpm_status = RPM_SUSPENDED;
3985 q->rpm_status = RPM_ACTIVE;
3986 pm_runtime_mark_last_busy(q->dev);
3988 spin_unlock_irq(q->queue_lock);
3990 EXPORT_SYMBOL(blk_post_runtime_suspend);
3993 * blk_pre_runtime_resume - Pre runtime resume processing
3994 * @q: the queue of the device
3997 * Update the queue's runtime status to RESUMING in preparation for the
3998 * runtime resume of the device.
4000 * This function should be called near the start of the device's
4001 * runtime_resume callback.
4003 void blk_pre_runtime_resume(struct request_queue *q)
4008 spin_lock_irq(q->queue_lock);
4009 q->rpm_status = RPM_RESUMING;
4010 spin_unlock_irq(q->queue_lock);
4012 EXPORT_SYMBOL(blk_pre_runtime_resume);
4015 * blk_post_runtime_resume - Post runtime resume processing
4016 * @q: the queue of the device
4017 * @err: return value of the device's runtime_resume function
4020 * Update the queue's runtime status according to the return value of the
4021 * device's runtime_resume function. If it is successfully resumed, process
4022 * the requests that are queued into the device's queue when it is resuming
4023 * and then mark last busy and initiate autosuspend for it.
4025 * This function should be called near the end of the device's
4026 * runtime_resume callback.
4028 void blk_post_runtime_resume(struct request_queue *q, int err)
4033 spin_lock_irq(q->queue_lock);
4035 q->rpm_status = RPM_ACTIVE;
4037 pm_runtime_mark_last_busy(q->dev);
4038 pm_request_autosuspend(q->dev);
4040 q->rpm_status = RPM_SUSPENDED;
4042 spin_unlock_irq(q->queue_lock);
4044 EXPORT_SYMBOL(blk_post_runtime_resume);
4047 int __init blk_dev_init(void)
4049 BUILD_BUG_ON(__REQ_NR_BITS > 8 *
4050 FIELD_SIZEOF(struct request, cmd_flags));
4052 /* used for unplugging and affects IO latency/throughput - HIGHPRI */
4053 kblockd_workqueue = alloc_workqueue("kblockd",
4054 WQ_MEM_RECLAIM | WQ_HIGHPRI, 0);
4055 if (!kblockd_workqueue)
4056 panic("Failed to create kblockd\n");
4058 request_cachep = kmem_cache_create("blkdev_requests",
4059 sizeof(struct request), 0, SLAB_PANIC, NULL);
4061 blk_requestq_cachep = kmem_cache_create("blkdev_queue",
4062 sizeof(struct request_queue), 0, SLAB_PANIC, NULL);
4068 * Blk IO latency support. We want this to be as cheap as possible, so doing
4069 * this lockless (and avoiding atomics), a few off by a few errors in this
4070 * code is not harmful, and we don't want to do anything that is
4072 * TODO : If necessary, we can make the histograms per-cpu and aggregate
4073 * them when printing them out.
4076 blk_zero_latency_hist(struct io_latency_state *s)
4078 memset(s->latency_y_axis_read, 0,
4079 sizeof(s->latency_y_axis_read));
4080 memset(s->latency_y_axis_write, 0,
4081 sizeof(s->latency_y_axis_write));
4082 s->latency_reads_elems = 0;
4083 s->latency_writes_elems = 0;
4085 EXPORT_SYMBOL(blk_zero_latency_hist);
4088 blk_latency_hist_show(struct io_latency_state *s, char *buf)
4091 int bytes_written = 0;
4092 u_int64_t num_elem, elem;
4095 num_elem = s->latency_reads_elems;
4097 bytes_written += scnprintf(buf + bytes_written,
4098 PAGE_SIZE - bytes_written,
4099 "IO svc_time Read Latency Histogram (n = %llu):\n",
4102 i < ARRAY_SIZE(latency_x_axis_us);
4104 elem = s->latency_y_axis_read[i];
4105 pct = div64_u64(elem * 100, num_elem);
4106 bytes_written += scnprintf(buf + bytes_written,
4107 PAGE_SIZE - bytes_written,
4108 "\t< %5lluus%15llu%15d%%\n",
4109 latency_x_axis_us[i],
4112 /* Last element in y-axis table is overflow */
4113 elem = s->latency_y_axis_read[i];
4114 pct = div64_u64(elem * 100, num_elem);
4115 bytes_written += scnprintf(buf + bytes_written,
4116 PAGE_SIZE - bytes_written,
4117 "\t> %5dms%15llu%15d%%\n", 10,
4120 num_elem = s->latency_writes_elems;
4122 bytes_written += scnprintf(buf + bytes_written,
4123 PAGE_SIZE - bytes_written,
4124 "IO svc_time Write Latency Histogram (n = %llu):\n",
4127 i < ARRAY_SIZE(latency_x_axis_us);
4129 elem = s->latency_y_axis_write[i];
4130 pct = div64_u64(elem * 100, num_elem);
4131 bytes_written += scnprintf(buf + bytes_written,
4132 PAGE_SIZE - bytes_written,
4133 "\t< %5lluus%15llu%15d%%\n",
4134 latency_x_axis_us[i],
4137 /* Last element in y-axis table is overflow */
4138 elem = s->latency_y_axis_write[i];
4139 pct = div64_u64(elem * 100, num_elem);
4140 bytes_written += scnprintf(buf + bytes_written,
4141 PAGE_SIZE - bytes_written,
4142 "\t> %5dms%15llu%15d%%\n", 10,
4145 return bytes_written;
4147 EXPORT_SYMBOL(blk_latency_hist_show);