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
14 #include <linux/kernel.h>
15 #include <linux/module.h>
16 #include <linux/backing-dev.h>
17 #include <linux/bio.h>
18 #include <linux/blkdev.h>
19 #include <linux/blk-mq.h>
20 #include <linux/highmem.h>
22 #include <linux/kernel_stat.h>
23 #include <linux/string.h>
24 #include <linux/init.h>
25 #include <linux/completion.h>
26 #include <linux/slab.h>
27 #include <linux/swap.h>
28 #include <linux/writeback.h>
29 #include <linux/task_io_accounting_ops.h>
30 #include <linux/fault-inject.h>
31 #include <linux/list_sort.h>
32 #include <linux/delay.h>
33 #include <linux/ratelimit.h>
34 #include <linux/pm_runtime.h>
35 #include <linux/blk-cgroup.h>
37 #define CREATE_TRACE_POINTS
38 #include <trace/events/block.h>
43 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_remap);
44 EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_remap);
45 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_complete);
46 EXPORT_TRACEPOINT_SYMBOL_GPL(block_split);
47 EXPORT_TRACEPOINT_SYMBOL_GPL(block_unplug);
49 DEFINE_IDA(blk_queue_ida);
52 * For the allocated request tables
54 struct kmem_cache *request_cachep;
57 * For queue allocation
59 struct kmem_cache *blk_requestq_cachep;
62 * Controlling structure to kblockd
64 static struct workqueue_struct *kblockd_workqueue;
66 static void blk_clear_congested(struct request_list *rl, int sync)
68 #ifdef CONFIG_CGROUP_WRITEBACK
69 clear_wb_congested(rl->blkg->wb_congested, sync);
72 * If !CGROUP_WRITEBACK, all blkg's map to bdi->wb and we shouldn't
73 * flip its congestion state for events on other blkcgs.
75 if (rl == &rl->q->root_rl)
76 clear_wb_congested(rl->q->backing_dev_info.wb.congested, sync);
80 static void blk_set_congested(struct request_list *rl, int sync)
82 #ifdef CONFIG_CGROUP_WRITEBACK
83 set_wb_congested(rl->blkg->wb_congested, sync);
85 /* see blk_clear_congested() */
86 if (rl == &rl->q->root_rl)
87 set_wb_congested(rl->q->backing_dev_info.wb.congested, sync);
91 void blk_queue_congestion_threshold(struct request_queue *q)
95 nr = q->nr_requests - (q->nr_requests / 8) + 1;
96 if (nr > q->nr_requests)
98 q->nr_congestion_on = nr;
100 nr = q->nr_requests - (q->nr_requests / 8) - (q->nr_requests / 16) - 1;
103 q->nr_congestion_off = nr;
107 * blk_get_backing_dev_info - get the address of a queue's backing_dev_info
110 * Locates the passed device's request queue and returns the address of its
111 * backing_dev_info. This function can only be called if @bdev is opened
112 * and the return value is never NULL.
114 struct backing_dev_info *blk_get_backing_dev_info(struct block_device *bdev)
116 struct request_queue *q = bdev_get_queue(bdev);
118 return &q->backing_dev_info;
120 EXPORT_SYMBOL(blk_get_backing_dev_info);
122 void blk_rq_init(struct request_queue *q, struct request *rq)
124 memset(rq, 0, sizeof(*rq));
126 INIT_LIST_HEAD(&rq->queuelist);
127 INIT_LIST_HEAD(&rq->timeout_list);
130 rq->__sector = (sector_t) -1;
131 INIT_HLIST_NODE(&rq->hash);
132 RB_CLEAR_NODE(&rq->rb_node);
134 rq->cmd_len = BLK_MAX_CDB;
136 rq->start_time = jiffies;
137 set_start_time_ns(rq);
140 EXPORT_SYMBOL(blk_rq_init);
142 static void req_bio_endio(struct request *rq, struct bio *bio,
143 unsigned int nbytes, int error)
146 bio->bi_error = error;
148 if (unlikely(rq->cmd_flags & REQ_QUIET))
149 bio_set_flag(bio, BIO_QUIET);
151 bio_advance(bio, nbytes);
153 /* don't actually finish bio if it's part of flush sequence */
154 if (bio->bi_iter.bi_size == 0 && !(rq->cmd_flags & REQ_FLUSH_SEQ))
158 void blk_dump_rq_flags(struct request *rq, char *msg)
162 printk(KERN_INFO "%s: dev %s: type=%x, flags=%llx\n", msg,
163 rq->rq_disk ? rq->rq_disk->disk_name : "?", rq->cmd_type,
164 (unsigned long long) rq->cmd_flags);
166 printk(KERN_INFO " sector %llu, nr/cnr %u/%u\n",
167 (unsigned long long)blk_rq_pos(rq),
168 blk_rq_sectors(rq), blk_rq_cur_sectors(rq));
169 printk(KERN_INFO " bio %p, biotail %p, len %u\n",
170 rq->bio, rq->biotail, blk_rq_bytes(rq));
172 if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
173 printk(KERN_INFO " cdb: ");
174 for (bit = 0; bit < BLK_MAX_CDB; bit++)
175 printk("%02x ", rq->cmd[bit]);
179 EXPORT_SYMBOL(blk_dump_rq_flags);
181 static void blk_delay_work(struct work_struct *work)
183 struct request_queue *q;
185 q = container_of(work, struct request_queue, delay_work.work);
186 spin_lock_irq(q->queue_lock);
188 spin_unlock_irq(q->queue_lock);
192 * blk_delay_queue - restart queueing after defined interval
193 * @q: The &struct request_queue in question
194 * @msecs: Delay in msecs
197 * Sometimes queueing needs to be postponed for a little while, to allow
198 * resources to come back. This function will make sure that queueing is
199 * restarted around the specified time. Queue lock must be held.
201 void blk_delay_queue(struct request_queue *q, unsigned long msecs)
203 if (likely(!blk_queue_dead(q)))
204 queue_delayed_work(kblockd_workqueue, &q->delay_work,
205 msecs_to_jiffies(msecs));
207 EXPORT_SYMBOL(blk_delay_queue);
210 * blk_start_queue_async - asynchronously restart a previously stopped queue
211 * @q: The &struct request_queue in question
214 * blk_start_queue_async() will clear the stop flag on the queue, and
215 * ensure that the request_fn for the queue is run from an async
218 void blk_start_queue_async(struct request_queue *q)
220 queue_flag_clear(QUEUE_FLAG_STOPPED, q);
221 blk_run_queue_async(q);
223 EXPORT_SYMBOL(blk_start_queue_async);
226 * blk_start_queue - restart a previously stopped queue
227 * @q: The &struct request_queue in question
230 * blk_start_queue() will clear the stop flag on the queue, and call
231 * the request_fn for the queue if it was in a stopped state when
232 * entered. Also see blk_stop_queue(). Queue lock must be held.
234 void blk_start_queue(struct request_queue *q)
236 WARN_ON(!in_interrupt() && !irqs_disabled());
238 queue_flag_clear(QUEUE_FLAG_STOPPED, q);
241 EXPORT_SYMBOL(blk_start_queue);
244 * blk_stop_queue - stop a queue
245 * @q: The &struct request_queue in question
248 * The Linux block layer assumes that a block driver will consume all
249 * entries on the request queue when the request_fn strategy is called.
250 * Often this will not happen, because of hardware limitations (queue
251 * depth settings). If a device driver gets a 'queue full' response,
252 * or if it simply chooses not to queue more I/O at one point, it can
253 * call this function to prevent the request_fn from being called until
254 * the driver has signalled it's ready to go again. This happens by calling
255 * blk_start_queue() to restart queue operations. Queue lock must be held.
257 void blk_stop_queue(struct request_queue *q)
259 cancel_delayed_work(&q->delay_work);
260 queue_flag_set(QUEUE_FLAG_STOPPED, q);
262 EXPORT_SYMBOL(blk_stop_queue);
265 * blk_sync_queue - cancel any pending callbacks on a queue
269 * The block layer may perform asynchronous callback activity
270 * on a queue, such as calling the unplug function after a timeout.
271 * A block device may call blk_sync_queue to ensure that any
272 * such activity is cancelled, thus allowing it to release resources
273 * that the callbacks might use. The caller must already have made sure
274 * that its ->make_request_fn will not re-add plugging prior to calling
277 * This function does not cancel any asynchronous activity arising
278 * out of elevator or throttling code. That would require elevator_exit()
279 * and blkcg_exit_queue() to be called with queue lock initialized.
282 void blk_sync_queue(struct request_queue *q)
284 del_timer_sync(&q->timeout);
285 cancel_work_sync(&q->timeout_work);
288 struct blk_mq_hw_ctx *hctx;
291 queue_for_each_hw_ctx(q, hctx, i) {
292 cancel_work_sync(&hctx->run_work);
293 cancel_delayed_work_sync(&hctx->delay_work);
296 cancel_delayed_work_sync(&q->delay_work);
299 EXPORT_SYMBOL(blk_sync_queue);
302 * __blk_run_queue_uncond - run a queue whether or not it has been stopped
303 * @q: The queue to run
306 * Invoke request handling on a queue if there are any pending requests.
307 * May be used to restart request handling after a request has completed.
308 * This variant runs the queue whether or not the queue has been
309 * stopped. Must be called with the queue lock held and interrupts
310 * disabled. See also @blk_run_queue.
312 inline void __blk_run_queue_uncond(struct request_queue *q)
314 if (unlikely(blk_queue_dead(q)))
318 * Some request_fn implementations, e.g. scsi_request_fn(), unlock
319 * the queue lock internally. As a result multiple threads may be
320 * running such a request function concurrently. Keep track of the
321 * number of active request_fn invocations such that blk_drain_queue()
322 * can wait until all these request_fn calls have finished.
324 q->request_fn_active++;
326 q->request_fn_active--;
328 EXPORT_SYMBOL_GPL(__blk_run_queue_uncond);
331 * __blk_run_queue - run a single device queue
332 * @q: The queue to run
335 * See @blk_run_queue. This variant must be called with the queue lock
336 * held and interrupts disabled.
338 void __blk_run_queue(struct request_queue *q)
340 if (unlikely(blk_queue_stopped(q)))
343 __blk_run_queue_uncond(q);
345 EXPORT_SYMBOL(__blk_run_queue);
348 * blk_run_queue_async - run a single device queue in workqueue context
349 * @q: The queue to run
352 * Tells kblockd to perform the equivalent of @blk_run_queue on behalf
353 * of us. The caller must hold the queue lock.
355 void blk_run_queue_async(struct request_queue *q)
357 if (likely(!blk_queue_stopped(q) && !blk_queue_dead(q)))
358 mod_delayed_work(kblockd_workqueue, &q->delay_work, 0);
360 EXPORT_SYMBOL(blk_run_queue_async);
363 * blk_run_queue - run a single device queue
364 * @q: The queue to run
367 * Invoke request handling on this queue, if it has pending work to do.
368 * May be used to restart queueing when a request has completed.
370 void blk_run_queue(struct request_queue *q)
374 spin_lock_irqsave(q->queue_lock, flags);
376 spin_unlock_irqrestore(q->queue_lock, flags);
378 EXPORT_SYMBOL(blk_run_queue);
380 void blk_put_queue(struct request_queue *q)
382 kobject_put(&q->kobj);
384 EXPORT_SYMBOL(blk_put_queue);
387 * __blk_drain_queue - drain requests from request_queue
389 * @drain_all: whether to drain all requests or only the ones w/ ELVPRIV
391 * Drain requests from @q. If @drain_all is set, all requests are drained.
392 * If not, only ELVPRIV requests are drained. The caller is responsible
393 * for ensuring that no new requests which need to be drained are queued.
395 static void __blk_drain_queue(struct request_queue *q, bool drain_all)
396 __releases(q->queue_lock)
397 __acquires(q->queue_lock)
401 lockdep_assert_held(q->queue_lock);
407 * The caller might be trying to drain @q before its
408 * elevator is initialized.
411 elv_drain_elevator(q);
413 blkcg_drain_queue(q);
416 * This function might be called on a queue which failed
417 * driver init after queue creation or is not yet fully
418 * active yet. Some drivers (e.g. fd and loop) get unhappy
419 * in such cases. Kick queue iff dispatch queue has
420 * something on it and @q has request_fn set.
422 if (!list_empty(&q->queue_head) && q->request_fn)
425 drain |= q->nr_rqs_elvpriv;
426 drain |= q->request_fn_active;
429 * Unfortunately, requests are queued at and tracked from
430 * multiple places and there's no single counter which can
431 * be drained. Check all the queues and counters.
434 struct blk_flush_queue *fq = blk_get_flush_queue(q, NULL);
435 drain |= !list_empty(&q->queue_head);
436 for (i = 0; i < 2; i++) {
437 drain |= q->nr_rqs[i];
438 drain |= q->in_flight[i];
440 drain |= !list_empty(&fq->flush_queue[i]);
447 spin_unlock_irq(q->queue_lock);
451 spin_lock_irq(q->queue_lock);
455 * With queue marked dead, any woken up waiter will fail the
456 * allocation path, so the wakeup chaining is lost and we're
457 * left with hung waiters. We need to wake up those waiters.
460 struct request_list *rl;
462 blk_queue_for_each_rl(rl, q)
463 for (i = 0; i < ARRAY_SIZE(rl->wait); i++)
464 wake_up_all(&rl->wait[i]);
469 * blk_queue_bypass_start - enter queue bypass mode
470 * @q: queue of interest
472 * In bypass mode, only the dispatch FIFO queue of @q is used. This
473 * function makes @q enter bypass mode and drains all requests which were
474 * throttled or issued before. On return, it's guaranteed that no request
475 * is being throttled or has ELVPRIV set and blk_queue_bypass() %true
476 * inside queue or RCU read lock.
478 void blk_queue_bypass_start(struct request_queue *q)
480 spin_lock_irq(q->queue_lock);
482 queue_flag_set(QUEUE_FLAG_BYPASS, q);
483 spin_unlock_irq(q->queue_lock);
486 * Queues start drained. Skip actual draining till init is
487 * complete. This avoids lenghty delays during queue init which
488 * can happen many times during boot.
490 if (blk_queue_init_done(q)) {
491 spin_lock_irq(q->queue_lock);
492 __blk_drain_queue(q, false);
493 spin_unlock_irq(q->queue_lock);
495 /* ensure blk_queue_bypass() is %true inside RCU read lock */
499 EXPORT_SYMBOL_GPL(blk_queue_bypass_start);
502 * blk_queue_bypass_end - leave queue bypass mode
503 * @q: queue of interest
505 * Leave bypass mode and restore the normal queueing behavior.
507 void blk_queue_bypass_end(struct request_queue *q)
509 spin_lock_irq(q->queue_lock);
510 if (!--q->bypass_depth)
511 queue_flag_clear(QUEUE_FLAG_BYPASS, q);
512 WARN_ON_ONCE(q->bypass_depth < 0);
513 spin_unlock_irq(q->queue_lock);
515 EXPORT_SYMBOL_GPL(blk_queue_bypass_end);
517 void blk_set_queue_dying(struct request_queue *q)
519 spin_lock_irq(q->queue_lock);
520 queue_flag_set(QUEUE_FLAG_DYING, q);
521 spin_unlock_irq(q->queue_lock);
524 blk_mq_wake_waiters(q);
526 struct request_list *rl;
528 blk_queue_for_each_rl(rl, q) {
530 wake_up_all(&rl->wait[BLK_RW_SYNC]);
531 wake_up_all(&rl->wait[BLK_RW_ASYNC]);
536 EXPORT_SYMBOL_GPL(blk_set_queue_dying);
539 * blk_cleanup_queue - shutdown a request queue
540 * @q: request queue to shutdown
542 * Mark @q DYING, drain all pending requests, mark @q DEAD, destroy and
543 * put it. All future requests will be failed immediately with -ENODEV.
545 void blk_cleanup_queue(struct request_queue *q)
547 spinlock_t *lock = q->queue_lock;
549 /* mark @q DYING, no new request or merges will be allowed afterwards */
550 mutex_lock(&q->sysfs_lock);
551 blk_set_queue_dying(q);
555 * A dying queue is permanently in bypass mode till released. Note
556 * that, unlike blk_queue_bypass_start(), we aren't performing
557 * synchronize_rcu() after entering bypass mode to avoid the delay
558 * as some drivers create and destroy a lot of queues while
559 * probing. This is still safe because blk_release_queue() will be
560 * called only after the queue refcnt drops to zero and nothing,
561 * RCU or not, would be traversing the queue by then.
564 queue_flag_set(QUEUE_FLAG_BYPASS, q);
566 queue_flag_set(QUEUE_FLAG_NOMERGES, q);
567 queue_flag_set(QUEUE_FLAG_NOXMERGES, q);
568 queue_flag_set(QUEUE_FLAG_DYING, q);
569 spin_unlock_irq(lock);
570 mutex_unlock(&q->sysfs_lock);
573 * Drain all requests queued before DYING marking. Set DEAD flag to
574 * prevent that q->request_fn() gets invoked after draining finished.
579 __blk_drain_queue(q, true);
580 queue_flag_set(QUEUE_FLAG_DEAD, q);
581 spin_unlock_irq(lock);
583 /* for synchronous bio-based driver finish in-flight integrity i/o */
584 blk_flush_integrity();
586 /* @q won't process any more request, flush async actions */
587 del_timer_sync(&q->backing_dev_info.laptop_mode_wb_timer);
591 blk_mq_free_queue(q);
592 percpu_ref_exit(&q->q_usage_counter);
595 if (q->queue_lock != &q->__queue_lock)
596 q->queue_lock = &q->__queue_lock;
597 spin_unlock_irq(lock);
599 bdi_unregister(&q->backing_dev_info);
601 /* @q is and will stay empty, shutdown and put */
604 EXPORT_SYMBOL(blk_cleanup_queue);
606 /* Allocate memory local to the request queue */
607 static void *alloc_request_struct(gfp_t gfp_mask, void *data)
609 int nid = (int)(long)data;
610 return kmem_cache_alloc_node(request_cachep, gfp_mask, nid);
613 static void free_request_struct(void *element, void *unused)
615 kmem_cache_free(request_cachep, element);
618 int blk_init_rl(struct request_list *rl, struct request_queue *q,
621 if (unlikely(rl->rq_pool))
625 rl->count[BLK_RW_SYNC] = rl->count[BLK_RW_ASYNC] = 0;
626 rl->starved[BLK_RW_SYNC] = rl->starved[BLK_RW_ASYNC] = 0;
627 init_waitqueue_head(&rl->wait[BLK_RW_SYNC]);
628 init_waitqueue_head(&rl->wait[BLK_RW_ASYNC]);
630 rl->rq_pool = mempool_create_node(BLKDEV_MIN_RQ, alloc_request_struct,
632 (void *)(long)q->node, gfp_mask,
640 void blk_exit_rl(struct request_list *rl)
643 mempool_destroy(rl->rq_pool);
646 struct request_queue *blk_alloc_queue(gfp_t gfp_mask)
648 return blk_alloc_queue_node(gfp_mask, NUMA_NO_NODE);
650 EXPORT_SYMBOL(blk_alloc_queue);
652 int blk_queue_enter(struct request_queue *q, bool nowait)
656 if (percpu_ref_tryget_live(&q->q_usage_counter))
662 wait_event(q->mq_freeze_wq,
663 !atomic_read(&q->mq_freeze_depth) ||
665 if (blk_queue_dying(q))
670 void blk_queue_exit(struct request_queue *q)
672 percpu_ref_put(&q->q_usage_counter);
675 static void blk_queue_usage_counter_release(struct percpu_ref *ref)
677 struct request_queue *q =
678 container_of(ref, struct request_queue, q_usage_counter);
680 wake_up_all(&q->mq_freeze_wq);
683 static void blk_rq_timed_out_timer(unsigned long data)
685 struct request_queue *q = (struct request_queue *)data;
687 kblockd_schedule_work(&q->timeout_work);
690 struct request_queue *blk_alloc_queue_node(gfp_t gfp_mask, int node_id)
692 struct request_queue *q;
695 q = kmem_cache_alloc_node(blk_requestq_cachep,
696 gfp_mask | __GFP_ZERO, node_id);
700 q->id = ida_simple_get(&blk_queue_ida, 0, 0, gfp_mask);
704 q->bio_split = bioset_create(BIO_POOL_SIZE, 0);
708 q->backing_dev_info.ra_pages =
709 (VM_MAX_READAHEAD * 1024) / PAGE_SIZE;
710 q->backing_dev_info.capabilities = BDI_CAP_CGROUP_WRITEBACK;
711 q->backing_dev_info.name = "block";
714 err = bdi_init(&q->backing_dev_info);
718 setup_timer(&q->backing_dev_info.laptop_mode_wb_timer,
719 laptop_mode_timer_fn, (unsigned long) q);
720 setup_timer(&q->timeout, blk_rq_timed_out_timer, (unsigned long) q);
721 INIT_WORK(&q->timeout_work, NULL);
722 INIT_LIST_HEAD(&q->queue_head);
723 INIT_LIST_HEAD(&q->timeout_list);
724 INIT_LIST_HEAD(&q->icq_list);
725 #ifdef CONFIG_BLK_CGROUP
726 INIT_LIST_HEAD(&q->blkg_list);
728 INIT_DELAYED_WORK(&q->delay_work, blk_delay_work);
730 kobject_init(&q->kobj, &blk_queue_ktype);
732 #ifdef CONFIG_BLK_DEV_IO_TRACE
733 mutex_init(&q->blk_trace_mutex);
735 mutex_init(&q->sysfs_lock);
736 spin_lock_init(&q->__queue_lock);
739 * By default initialize queue_lock to internal lock and driver can
740 * override it later if need be.
742 q->queue_lock = &q->__queue_lock;
745 * A queue starts its life with bypass turned on to avoid
746 * unnecessary bypass on/off overhead and nasty surprises during
747 * init. The initial bypass will be finished when the queue is
748 * registered by blk_register_queue().
751 __set_bit(QUEUE_FLAG_BYPASS, &q->queue_flags);
753 init_waitqueue_head(&q->mq_freeze_wq);
756 * Init percpu_ref in atomic mode so that it's faster to shutdown.
757 * See blk_register_queue() for details.
759 if (percpu_ref_init(&q->q_usage_counter,
760 blk_queue_usage_counter_release,
761 PERCPU_REF_INIT_ATOMIC, GFP_KERNEL))
764 if (blkcg_init_queue(q))
770 percpu_ref_exit(&q->q_usage_counter);
772 bdi_destroy(&q->backing_dev_info);
774 bioset_free(q->bio_split);
776 ida_simple_remove(&blk_queue_ida, q->id);
778 kmem_cache_free(blk_requestq_cachep, q);
781 EXPORT_SYMBOL(blk_alloc_queue_node);
784 * blk_init_queue - prepare a request queue for use with a block device
785 * @rfn: The function to be called to process requests that have been
786 * placed on the queue.
787 * @lock: Request queue spin lock
790 * If a block device wishes to use the standard request handling procedures,
791 * which sorts requests and coalesces adjacent requests, then it must
792 * call blk_init_queue(). The function @rfn will be called when there
793 * are requests on the queue that need to be processed. If the device
794 * supports plugging, then @rfn may not be called immediately when requests
795 * are available on the queue, but may be called at some time later instead.
796 * Plugged queues are generally unplugged when a buffer belonging to one
797 * of the requests on the queue is needed, or due to memory pressure.
799 * @rfn is not required, or even expected, to remove all requests off the
800 * queue, but only as many as it can handle at a time. If it does leave
801 * requests on the queue, it is responsible for arranging that the requests
802 * get dealt with eventually.
804 * The queue spin lock must be held while manipulating the requests on the
805 * request queue; this lock will be taken also from interrupt context, so irq
806 * disabling is needed for it.
808 * Function returns a pointer to the initialized request queue, or %NULL if
812 * blk_init_queue() must be paired with a blk_cleanup_queue() call
813 * when the block device is deactivated (such as at module unload).
816 struct request_queue *blk_init_queue(request_fn_proc *rfn, spinlock_t *lock)
818 return blk_init_queue_node(rfn, lock, NUMA_NO_NODE);
820 EXPORT_SYMBOL(blk_init_queue);
822 struct request_queue *
823 blk_init_queue_node(request_fn_proc *rfn, spinlock_t *lock, int node_id)
825 struct request_queue *uninit_q, *q;
827 uninit_q = blk_alloc_queue_node(GFP_KERNEL, node_id);
831 q = blk_init_allocated_queue(uninit_q, rfn, lock);
833 blk_cleanup_queue(uninit_q);
837 EXPORT_SYMBOL(blk_init_queue_node);
839 static blk_qc_t blk_queue_bio(struct request_queue *q, struct bio *bio);
841 struct request_queue *
842 blk_init_allocated_queue(struct request_queue *q, request_fn_proc *rfn,
848 q->fq = blk_alloc_flush_queue(q, NUMA_NO_NODE, 0);
852 if (blk_init_rl(&q->root_rl, q, GFP_KERNEL))
855 INIT_WORK(&q->timeout_work, blk_timeout_work);
857 q->prep_rq_fn = NULL;
858 q->unprep_rq_fn = NULL;
859 q->queue_flags |= QUEUE_FLAG_DEFAULT;
861 /* Override internal queue lock with supplied lock pointer */
863 q->queue_lock = lock;
866 * This also sets hw/phys segments, boundary and size
868 blk_queue_make_request(q, blk_queue_bio);
870 q->sg_reserved_size = INT_MAX;
872 /* Protect q->elevator from elevator_change */
873 mutex_lock(&q->sysfs_lock);
876 if (elevator_init(q, NULL)) {
877 mutex_unlock(&q->sysfs_lock);
881 mutex_unlock(&q->sysfs_lock);
886 blk_free_flush_queue(q->fq);
890 EXPORT_SYMBOL(blk_init_allocated_queue);
892 bool blk_get_queue(struct request_queue *q)
894 if (likely(!blk_queue_dying(q))) {
901 EXPORT_SYMBOL(blk_get_queue);
903 static inline void blk_free_request(struct request_list *rl, struct request *rq)
905 if (rq->cmd_flags & REQ_ELVPRIV) {
906 elv_put_request(rl->q, rq);
908 put_io_context(rq->elv.icq->ioc);
911 mempool_free(rq, rl->rq_pool);
915 * ioc_batching returns true if the ioc is a valid batching request and
916 * should be given priority access to a request.
918 static inline int ioc_batching(struct request_queue *q, struct io_context *ioc)
924 * Make sure the process is able to allocate at least 1 request
925 * even if the batch times out, otherwise we could theoretically
928 return ioc->nr_batch_requests == q->nr_batching ||
929 (ioc->nr_batch_requests > 0
930 && time_before(jiffies, ioc->last_waited + BLK_BATCH_TIME));
934 * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
935 * will cause the process to be a "batcher" on all queues in the system. This
936 * is the behaviour we want though - once it gets a wakeup it should be given
939 static void ioc_set_batching(struct request_queue *q, struct io_context *ioc)
941 if (!ioc || ioc_batching(q, ioc))
944 ioc->nr_batch_requests = q->nr_batching;
945 ioc->last_waited = jiffies;
948 static void __freed_request(struct request_list *rl, int sync)
950 struct request_queue *q = rl->q;
952 if (rl->count[sync] < queue_congestion_off_threshold(q))
953 blk_clear_congested(rl, sync);
955 if (rl->count[sync] + 1 <= q->nr_requests) {
956 if (waitqueue_active(&rl->wait[sync]))
957 wake_up(&rl->wait[sync]);
959 blk_clear_rl_full(rl, sync);
964 * A request has just been released. Account for it, update the full and
965 * congestion status, wake up any waiters. Called under q->queue_lock.
967 static void freed_request(struct request_list *rl, int op, unsigned int flags)
969 struct request_queue *q = rl->q;
970 int sync = rw_is_sync(op, flags);
974 if (flags & REQ_ELVPRIV)
977 __freed_request(rl, sync);
979 if (unlikely(rl->starved[sync ^ 1]))
980 __freed_request(rl, sync ^ 1);
983 int blk_update_nr_requests(struct request_queue *q, unsigned int nr)
985 struct request_list *rl;
986 int on_thresh, off_thresh;
988 spin_lock_irq(q->queue_lock);
990 blk_queue_congestion_threshold(q);
991 on_thresh = queue_congestion_on_threshold(q);
992 off_thresh = queue_congestion_off_threshold(q);
994 blk_queue_for_each_rl(rl, q) {
995 if (rl->count[BLK_RW_SYNC] >= on_thresh)
996 blk_set_congested(rl, BLK_RW_SYNC);
997 else if (rl->count[BLK_RW_SYNC] < off_thresh)
998 blk_clear_congested(rl, BLK_RW_SYNC);
1000 if (rl->count[BLK_RW_ASYNC] >= on_thresh)
1001 blk_set_congested(rl, BLK_RW_ASYNC);
1002 else if (rl->count[BLK_RW_ASYNC] < off_thresh)
1003 blk_clear_congested(rl, BLK_RW_ASYNC);
1005 if (rl->count[BLK_RW_SYNC] >= q->nr_requests) {
1006 blk_set_rl_full(rl, BLK_RW_SYNC);
1008 blk_clear_rl_full(rl, BLK_RW_SYNC);
1009 wake_up(&rl->wait[BLK_RW_SYNC]);
1012 if (rl->count[BLK_RW_ASYNC] >= q->nr_requests) {
1013 blk_set_rl_full(rl, BLK_RW_ASYNC);
1015 blk_clear_rl_full(rl, BLK_RW_ASYNC);
1016 wake_up(&rl->wait[BLK_RW_ASYNC]);
1020 spin_unlock_irq(q->queue_lock);
1025 * Determine if elevator data should be initialized when allocating the
1026 * request associated with @bio.
1028 static bool blk_rq_should_init_elevator(struct bio *bio)
1034 * Flush requests do not use the elevator so skip initialization.
1035 * This allows a request to share the flush and elevator data.
1037 if (bio->bi_opf & (REQ_PREFLUSH | REQ_FUA))
1044 * rq_ioc - determine io_context for request allocation
1045 * @bio: request being allocated is for this bio (can be %NULL)
1047 * Determine io_context to use for request allocation for @bio. May return
1048 * %NULL if %current->io_context doesn't exist.
1050 static struct io_context *rq_ioc(struct bio *bio)
1052 #ifdef CONFIG_BLK_CGROUP
1053 if (bio && bio->bi_ioc)
1056 return current->io_context;
1060 * __get_request - get a free request
1061 * @rl: request list to allocate from
1062 * @op: REQ_OP_READ/REQ_OP_WRITE
1063 * @op_flags: rq_flag_bits
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 op,
1075 int op_flags, struct bio *bio,
1078 struct request_queue *q = rl->q;
1080 struct elevator_type *et = q->elevator->type;
1081 struct io_context *ioc = rq_ioc(bio);
1082 struct io_cq *icq = NULL;
1083 const bool is_sync = rw_is_sync(op, op_flags) != 0;
1086 if (unlikely(blk_queue_dying(q)))
1087 return ERR_PTR(-ENODEV);
1089 may_queue = elv_may_queue(q, op, op_flags);
1090 if (may_queue == ELV_MQUEUE_NO)
1093 if (rl->count[is_sync]+1 >= queue_congestion_on_threshold(q)) {
1094 if (rl->count[is_sync]+1 >= q->nr_requests) {
1096 * The queue will fill after this allocation, so set
1097 * it as full, and mark this process as "batching".
1098 * This process will be allowed to complete a batch of
1099 * requests, others will be blocked.
1101 if (!blk_rl_full(rl, is_sync)) {
1102 ioc_set_batching(q, ioc);
1103 blk_set_rl_full(rl, is_sync);
1105 if (may_queue != ELV_MQUEUE_MUST
1106 && !ioc_batching(q, ioc)) {
1108 * The queue is full and the allocating
1109 * process is not a "batcher", and not
1110 * exempted by the IO scheduler
1112 return ERR_PTR(-ENOMEM);
1116 blk_set_congested(rl, is_sync);
1120 * Only allow batching queuers to allocate up to 50% over the defined
1121 * limit of requests, otherwise we could have thousands of requests
1122 * allocated with any setting of ->nr_requests
1124 if (rl->count[is_sync] >= (3 * q->nr_requests / 2))
1125 return ERR_PTR(-ENOMEM);
1127 q->nr_rqs[is_sync]++;
1128 rl->count[is_sync]++;
1129 rl->starved[is_sync] = 0;
1132 * Decide whether the new request will be managed by elevator. If
1133 * so, mark @op_flags and increment elvpriv. Non-zero elvpriv will
1134 * prevent the current elevator from being destroyed until the new
1135 * request is freed. This guarantees icq's won't be destroyed and
1136 * makes creating new ones safe.
1138 * Also, lookup icq while holding queue_lock. If it doesn't exist,
1139 * it will be created after releasing queue_lock.
1141 if (blk_rq_should_init_elevator(bio) && !blk_queue_bypass(q)) {
1142 op_flags |= REQ_ELVPRIV;
1143 q->nr_rqs_elvpriv++;
1144 if (et->icq_cache && ioc)
1145 icq = ioc_lookup_icq(ioc, q);
1148 if (blk_queue_io_stat(q))
1149 op_flags |= REQ_IO_STAT;
1150 spin_unlock_irq(q->queue_lock);
1152 /* allocate and init request */
1153 rq = mempool_alloc(rl->rq_pool, gfp_mask);
1158 blk_rq_set_rl(rq, rl);
1159 req_set_op_attrs(rq, op, op_flags | REQ_ALLOCED);
1162 if (op_flags & REQ_ELVPRIV) {
1163 if (unlikely(et->icq_cache && !icq)) {
1165 icq = ioc_create_icq(ioc, q, gfp_mask);
1171 if (unlikely(elv_set_request(q, rq, bio, gfp_mask)))
1174 /* @rq->elv.icq holds io_context until @rq is freed */
1176 get_io_context(icq->ioc);
1180 * ioc may be NULL here, and ioc_batching will be false. That's
1181 * OK, if the queue is under the request limit then requests need
1182 * not count toward the nr_batch_requests limit. There will always
1183 * be some limit enforced by BLK_BATCH_TIME.
1185 if (ioc_batching(q, ioc))
1186 ioc->nr_batch_requests--;
1188 trace_block_getrq(q, bio, op);
1193 * elvpriv init failed. ioc, icq and elvpriv aren't mempool backed
1194 * and may fail indefinitely under memory pressure and thus
1195 * shouldn't stall IO. Treat this request as !elvpriv. This will
1196 * disturb iosched and blkcg but weird is bettern than dead.
1198 printk_ratelimited(KERN_WARNING "%s: dev %s: request aux data allocation failed, iosched may be disturbed\n",
1199 __func__, dev_name(q->backing_dev_info.dev));
1201 rq->cmd_flags &= ~REQ_ELVPRIV;
1204 spin_lock_irq(q->queue_lock);
1205 q->nr_rqs_elvpriv--;
1206 spin_unlock_irq(q->queue_lock);
1211 * Allocation failed presumably due to memory. Undo anything we
1212 * might have messed up.
1214 * Allocating task should really be put onto the front of the wait
1215 * queue, but this is pretty rare.
1217 spin_lock_irq(q->queue_lock);
1218 freed_request(rl, op, op_flags);
1221 * in the very unlikely event that allocation failed and no
1222 * requests for this direction was pending, mark us starved so that
1223 * freeing of a request in the other direction will notice
1224 * us. another possible fix would be to split the rq mempool into
1228 if (unlikely(rl->count[is_sync] == 0))
1229 rl->starved[is_sync] = 1;
1230 return ERR_PTR(-ENOMEM);
1234 * get_request - get a free request
1235 * @q: request_queue to allocate request from
1236 * @op: REQ_OP_READ/REQ_OP_WRITE
1237 * @op_flags: rq_flag_bits
1238 * @bio: bio to allocate request for (can be %NULL)
1239 * @gfp_mask: allocation mask
1241 * Get a free request from @q. If %__GFP_DIRECT_RECLAIM is set in @gfp_mask,
1242 * this function keeps retrying under memory pressure and fails iff @q is dead.
1244 * Must be called with @q->queue_lock held and,
1245 * Returns ERR_PTR on failure, with @q->queue_lock held.
1246 * Returns request pointer on success, with @q->queue_lock *not held*.
1248 static struct request *get_request(struct request_queue *q, int op,
1249 int op_flags, struct bio *bio,
1252 const bool is_sync = rw_is_sync(op, op_flags) != 0;
1254 struct request_list *rl;
1257 rl = blk_get_rl(q, bio); /* transferred to @rq on success */
1259 rq = __get_request(rl, op, op_flags, bio, gfp_mask);
1263 if (!gfpflags_allow_blocking(gfp_mask) || unlikely(blk_queue_dying(q))) {
1268 /* wait on @rl and retry */
1269 prepare_to_wait_exclusive(&rl->wait[is_sync], &wait,
1270 TASK_UNINTERRUPTIBLE);
1272 trace_block_sleeprq(q, bio, op);
1274 spin_unlock_irq(q->queue_lock);
1278 * After sleeping, we become a "batching" process and will be able
1279 * to allocate at least one request, and up to a big batch of them
1280 * for a small period time. See ioc_batching, ioc_set_batching
1282 ioc_set_batching(q, current->io_context);
1284 spin_lock_irq(q->queue_lock);
1285 finish_wait(&rl->wait[is_sync], &wait);
1290 static struct request *blk_old_get_request(struct request_queue *q, int rw,
1295 BUG_ON(rw != READ && rw != WRITE);
1297 /* create ioc upfront */
1298 create_io_context(gfp_mask, q->node);
1300 spin_lock_irq(q->queue_lock);
1301 rq = get_request(q, rw, 0, NULL, gfp_mask);
1303 spin_unlock_irq(q->queue_lock);
1307 /* q->queue_lock is unlocked at this point */
1309 rq->__sector = (sector_t) -1;
1310 rq->bio = rq->biotail = NULL;
1314 struct request *blk_get_request(struct request_queue *q, int rw, gfp_t gfp_mask)
1317 return blk_mq_alloc_request(q, rw,
1318 (gfp_mask & __GFP_DIRECT_RECLAIM) ?
1319 0 : BLK_MQ_REQ_NOWAIT);
1321 return blk_old_get_request(q, rw, gfp_mask);
1323 EXPORT_SYMBOL(blk_get_request);
1326 * blk_rq_set_block_pc - initialize a request to type BLOCK_PC
1327 * @rq: request to be initialized
1330 void blk_rq_set_block_pc(struct request *rq)
1332 rq->cmd_type = REQ_TYPE_BLOCK_PC;
1333 memset(rq->__cmd, 0, sizeof(rq->__cmd));
1335 EXPORT_SYMBOL(blk_rq_set_block_pc);
1338 * blk_requeue_request - put a request back on queue
1339 * @q: request queue where request should be inserted
1340 * @rq: request to be inserted
1343 * Drivers often keep queueing requests until the hardware cannot accept
1344 * more, when that condition happens we need to put the request back
1345 * on the queue. Must be called with queue lock held.
1347 void blk_requeue_request(struct request_queue *q, struct request *rq)
1349 blk_delete_timer(rq);
1350 blk_clear_rq_complete(rq);
1351 trace_block_rq_requeue(q, rq);
1353 if (rq->cmd_flags & REQ_QUEUED)
1354 blk_queue_end_tag(q, rq);
1356 BUG_ON(blk_queued_rq(rq));
1358 elv_requeue_request(q, rq);
1360 EXPORT_SYMBOL(blk_requeue_request);
1362 static void add_acct_request(struct request_queue *q, struct request *rq,
1365 blk_account_io_start(rq, true);
1366 __elv_add_request(q, rq, where);
1369 static void part_round_stats_single(int cpu, struct hd_struct *part,
1374 if (now == part->stamp)
1377 inflight = part_in_flight(part);
1379 __part_stat_add(cpu, part, time_in_queue,
1380 inflight * (now - part->stamp));
1381 __part_stat_add(cpu, part, io_ticks, (now - part->stamp));
1387 * part_round_stats() - Round off the performance stats on a struct disk_stats.
1388 * @cpu: cpu number for stats access
1389 * @part: target partition
1391 * The average IO queue length and utilisation statistics are maintained
1392 * by observing the current state of the queue length and the amount of
1393 * time it has been in this state for.
1395 * Normally, that accounting is done on IO completion, but that can result
1396 * in more than a second's worth of IO being accounted for within any one
1397 * second, leading to >100% utilisation. To deal with that, we call this
1398 * function to do a round-off before returning the results when reading
1399 * /proc/diskstats. This accounts immediately for all queue usage up to
1400 * the current jiffies and restarts the counters again.
1402 void part_round_stats(int cpu, struct hd_struct *part)
1404 unsigned long now = jiffies;
1407 part_round_stats_single(cpu, &part_to_disk(part)->part0, now);
1408 part_round_stats_single(cpu, part, now);
1410 EXPORT_SYMBOL_GPL(part_round_stats);
1413 static void blk_pm_put_request(struct request *rq)
1415 if (rq->q->dev && !(rq->cmd_flags & REQ_PM) && !--rq->q->nr_pending)
1416 pm_runtime_mark_last_busy(rq->q->dev);
1419 static inline void blk_pm_put_request(struct request *rq) {}
1423 * queue lock must be held
1425 void __blk_put_request(struct request_queue *q, struct request *req)
1431 blk_mq_free_request(req);
1435 blk_pm_put_request(req);
1437 elv_completed_request(q, req);
1439 /* this is a bio leak */
1440 WARN_ON(req->bio != NULL);
1443 * Request may not have originated from ll_rw_blk. if not,
1444 * it didn't come out of our reserved rq pools
1446 if (req->cmd_flags & REQ_ALLOCED) {
1447 unsigned int flags = req->cmd_flags;
1448 int op = req_op(req);
1449 struct request_list *rl = blk_rq_rl(req);
1451 BUG_ON(!list_empty(&req->queuelist));
1452 BUG_ON(ELV_ON_HASH(req));
1454 blk_free_request(rl, req);
1455 freed_request(rl, op, flags);
1459 EXPORT_SYMBOL_GPL(__blk_put_request);
1461 void blk_put_request(struct request *req)
1463 struct request_queue *q = req->q;
1466 blk_mq_free_request(req);
1468 unsigned long flags;
1470 spin_lock_irqsave(q->queue_lock, flags);
1471 __blk_put_request(q, req);
1472 spin_unlock_irqrestore(q->queue_lock, flags);
1475 EXPORT_SYMBOL(blk_put_request);
1478 * blk_add_request_payload - add a payload to a request
1479 * @rq: request to update
1480 * @page: page backing the payload
1481 * @offset: offset in page
1482 * @len: length of the payload.
1484 * This allows to later add a payload to an already submitted request by
1485 * a block driver. The driver needs to take care of freeing the payload
1488 * Note that this is a quite horrible hack and nothing but handling of
1489 * discard requests should ever use it.
1491 void blk_add_request_payload(struct request *rq, struct page *page,
1492 int offset, unsigned int len)
1494 struct bio *bio = rq->bio;
1496 bio->bi_io_vec->bv_page = page;
1497 bio->bi_io_vec->bv_offset = offset;
1498 bio->bi_io_vec->bv_len = len;
1500 bio->bi_iter.bi_size = len;
1502 bio->bi_phys_segments = 1;
1504 rq->__data_len = rq->resid_len = len;
1505 rq->nr_phys_segments = 1;
1507 EXPORT_SYMBOL_GPL(blk_add_request_payload);
1509 bool bio_attempt_back_merge(struct request_queue *q, struct request *req,
1512 const int ff = bio->bi_opf & REQ_FAILFAST_MASK;
1514 if (!ll_back_merge_fn(q, req, bio))
1517 trace_block_bio_backmerge(q, req, bio);
1519 if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
1520 blk_rq_set_mixed_merge(req);
1522 req->biotail->bi_next = bio;
1524 req->__data_len += bio->bi_iter.bi_size;
1525 req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
1527 blk_account_io_start(req, false);
1531 bool bio_attempt_front_merge(struct request_queue *q, struct request *req,
1534 const int ff = bio->bi_opf & REQ_FAILFAST_MASK;
1536 if (!ll_front_merge_fn(q, req, bio))
1539 trace_block_bio_frontmerge(q, req, bio);
1541 if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
1542 blk_rq_set_mixed_merge(req);
1544 bio->bi_next = req->bio;
1547 req->__sector = bio->bi_iter.bi_sector;
1548 req->__data_len += bio->bi_iter.bi_size;
1549 req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
1551 blk_account_io_start(req, false);
1556 * blk_attempt_plug_merge - try to merge with %current's plugged list
1557 * @q: request_queue new bio is being queued at
1558 * @bio: new bio being queued
1559 * @request_count: out parameter for number of traversed plugged requests
1560 * @same_queue_rq: pointer to &struct request that gets filled in when
1561 * another request associated with @q is found on the plug list
1562 * (optional, may be %NULL)
1564 * Determine whether @bio being queued on @q can be merged with a request
1565 * on %current's plugged list. Returns %true if merge was successful,
1568 * Plugging coalesces IOs from the same issuer for the same purpose without
1569 * going through @q->queue_lock. As such it's more of an issuing mechanism
1570 * than scheduling, and the request, while may have elvpriv data, is not
1571 * added on the elevator at this point. In addition, we don't have
1572 * reliable access to the elevator outside queue lock. Only check basic
1573 * merging parameters without querying the elevator.
1575 * Caller must ensure !blk_queue_nomerges(q) beforehand.
1577 bool blk_attempt_plug_merge(struct request_queue *q, struct bio *bio,
1578 unsigned int *request_count,
1579 struct request **same_queue_rq)
1581 struct blk_plug *plug;
1584 struct list_head *plug_list;
1586 plug = current->plug;
1592 plug_list = &plug->mq_list;
1594 plug_list = &plug->list;
1596 list_for_each_entry_reverse(rq, plug_list, queuelist) {
1602 * Only blk-mq multiple hardware queues case checks the
1603 * rq in the same queue, there should be only one such
1607 *same_queue_rq = rq;
1610 if (rq->q != q || !blk_rq_merge_ok(rq, bio))
1613 el_ret = blk_try_merge(rq, bio);
1614 if (el_ret == ELEVATOR_BACK_MERGE) {
1615 ret = bio_attempt_back_merge(q, rq, bio);
1618 } else if (el_ret == ELEVATOR_FRONT_MERGE) {
1619 ret = bio_attempt_front_merge(q, rq, bio);
1628 unsigned int blk_plug_queued_count(struct request_queue *q)
1630 struct blk_plug *plug;
1632 struct list_head *plug_list;
1633 unsigned int ret = 0;
1635 plug = current->plug;
1640 plug_list = &plug->mq_list;
1642 plug_list = &plug->list;
1644 list_for_each_entry(rq, plug_list, queuelist) {
1652 void init_request_from_bio(struct request *req, struct bio *bio)
1654 req->cmd_type = REQ_TYPE_FS;
1656 req->cmd_flags |= bio->bi_opf & REQ_COMMON_MASK;
1657 if (bio->bi_opf & REQ_RAHEAD)
1658 req->cmd_flags |= REQ_FAILFAST_MASK;
1661 req->__sector = bio->bi_iter.bi_sector;
1662 req->ioprio = bio_prio(bio);
1663 blk_rq_bio_prep(req->q, req, bio);
1666 static blk_qc_t blk_queue_bio(struct request_queue *q, struct bio *bio)
1668 const bool sync = !!(bio->bi_opf & REQ_SYNC);
1669 struct blk_plug *plug;
1670 int el_ret, rw_flags = 0, where = ELEVATOR_INSERT_SORT;
1671 struct request *req;
1672 unsigned int request_count = 0;
1675 * low level driver can indicate that it wants pages above a
1676 * certain limit bounced to low memory (ie for highmem, or even
1677 * ISA dma in theory)
1679 blk_queue_bounce(q, &bio);
1681 blk_queue_split(q, &bio, q->bio_split);
1683 if (bio_integrity_enabled(bio) && bio_integrity_prep(bio)) {
1684 bio->bi_error = -EIO;
1686 return BLK_QC_T_NONE;
1689 if (bio->bi_opf & (REQ_PREFLUSH | REQ_FUA)) {
1690 spin_lock_irq(q->queue_lock);
1691 where = ELEVATOR_INSERT_FLUSH;
1696 * Check if we can merge with the plugged list before grabbing
1699 if (!blk_queue_nomerges(q)) {
1700 if (blk_attempt_plug_merge(q, bio, &request_count, NULL))
1701 return BLK_QC_T_NONE;
1703 request_count = blk_plug_queued_count(q);
1705 spin_lock_irq(q->queue_lock);
1707 el_ret = elv_merge(q, &req, bio);
1708 if (el_ret == ELEVATOR_BACK_MERGE) {
1709 if (bio_attempt_back_merge(q, req, bio)) {
1710 elv_bio_merged(q, req, bio);
1711 if (!attempt_back_merge(q, req))
1712 elv_merged_request(q, req, el_ret);
1715 } else if (el_ret == ELEVATOR_FRONT_MERGE) {
1716 if (bio_attempt_front_merge(q, req, bio)) {
1717 elv_bio_merged(q, req, bio);
1718 if (!attempt_front_merge(q, req))
1719 elv_merged_request(q, req, el_ret);
1726 * This sync check and mask will be re-done in init_request_from_bio(),
1727 * but we need to set it earlier to expose the sync flag to the
1728 * rq allocator and io schedulers.
1731 rw_flags |= REQ_SYNC;
1734 * Add in META/PRIO flags, if set, before we get to the IO scheduler
1736 rw_flags |= (bio->bi_opf & (REQ_META | REQ_PRIO));
1739 * Grab a free request. This is might sleep but can not fail.
1740 * Returns with the queue unlocked.
1742 req = get_request(q, bio_data_dir(bio), rw_flags, bio, GFP_NOIO);
1744 bio->bi_error = PTR_ERR(req);
1750 * After dropping the lock and possibly sleeping here, our request
1751 * may now be mergeable after it had proven unmergeable (above).
1752 * We don't worry about that case for efficiency. It won't happen
1753 * often, and the elevators are able to handle it.
1755 init_request_from_bio(req, bio);
1757 if (test_bit(QUEUE_FLAG_SAME_COMP, &q->queue_flags))
1758 req->cpu = raw_smp_processor_id();
1760 plug = current->plug;
1763 * If this is the first request added after a plug, fire
1767 trace_block_plug(q);
1769 if (request_count >= BLK_MAX_REQUEST_COUNT) {
1770 blk_flush_plug_list(plug, false);
1771 trace_block_plug(q);
1774 list_add_tail(&req->queuelist, &plug->list);
1775 blk_account_io_start(req, true);
1777 spin_lock_irq(q->queue_lock);
1778 add_acct_request(q, req, where);
1781 spin_unlock_irq(q->queue_lock);
1784 return BLK_QC_T_NONE;
1788 * If bio->bi_dev is a partition, remap the location
1790 static inline void blk_partition_remap(struct bio *bio)
1792 struct block_device *bdev = bio->bi_bdev;
1794 if (bio_sectors(bio) && bdev != bdev->bd_contains) {
1795 struct hd_struct *p = bdev->bd_part;
1797 bio->bi_iter.bi_sector += p->start_sect;
1798 bio->bi_bdev = bdev->bd_contains;
1800 trace_block_bio_remap(bdev_get_queue(bio->bi_bdev), bio,
1802 bio->bi_iter.bi_sector - p->start_sect);
1806 static void handle_bad_sector(struct bio *bio)
1808 char b[BDEVNAME_SIZE];
1810 printk(KERN_INFO "attempt to access beyond end of device\n");
1811 printk(KERN_INFO "%s: rw=%d, want=%Lu, limit=%Lu\n",
1812 bdevname(bio->bi_bdev, b),
1814 (unsigned long long)bio_end_sector(bio),
1815 (long long)(i_size_read(bio->bi_bdev->bd_inode) >> 9));
1818 #ifdef CONFIG_FAIL_MAKE_REQUEST
1820 static DECLARE_FAULT_ATTR(fail_make_request);
1822 static int __init setup_fail_make_request(char *str)
1824 return setup_fault_attr(&fail_make_request, str);
1826 __setup("fail_make_request=", setup_fail_make_request);
1828 static bool should_fail_request(struct hd_struct *part, unsigned int bytes)
1830 return part->make_it_fail && should_fail(&fail_make_request, bytes);
1833 static int __init fail_make_request_debugfs(void)
1835 struct dentry *dir = fault_create_debugfs_attr("fail_make_request",
1836 NULL, &fail_make_request);
1838 return PTR_ERR_OR_ZERO(dir);
1841 late_initcall(fail_make_request_debugfs);
1843 #else /* CONFIG_FAIL_MAKE_REQUEST */
1845 static inline bool should_fail_request(struct hd_struct *part,
1851 #endif /* CONFIG_FAIL_MAKE_REQUEST */
1854 * Check whether this bio extends beyond the end of the device.
1856 static inline int bio_check_eod(struct bio *bio, unsigned int nr_sectors)
1863 /* Test device or partition size, when known. */
1864 maxsector = i_size_read(bio->bi_bdev->bd_inode) >> 9;
1866 sector_t sector = bio->bi_iter.bi_sector;
1868 if (maxsector < nr_sectors || maxsector - nr_sectors < sector) {
1870 * This may well happen - the kernel calls bread()
1871 * without checking the size of the device, e.g., when
1872 * mounting a device.
1874 handle_bad_sector(bio);
1882 static noinline_for_stack bool
1883 generic_make_request_checks(struct bio *bio)
1885 struct request_queue *q;
1886 int nr_sectors = bio_sectors(bio);
1888 char b[BDEVNAME_SIZE];
1889 struct hd_struct *part;
1893 if (bio_check_eod(bio, nr_sectors))
1896 q = bdev_get_queue(bio->bi_bdev);
1899 "generic_make_request: Trying to access "
1900 "nonexistent block-device %s (%Lu)\n",
1901 bdevname(bio->bi_bdev, b),
1902 (long long) bio->bi_iter.bi_sector);
1906 part = bio->bi_bdev->bd_part;
1907 if (should_fail_request(part, bio->bi_iter.bi_size) ||
1908 should_fail_request(&part_to_disk(part)->part0,
1909 bio->bi_iter.bi_size))
1913 * If this device has partitions, remap block n
1914 * of partition p to block n+start(p) of the disk.
1916 blk_partition_remap(bio);
1918 if (bio_check_eod(bio, nr_sectors))
1922 * Filter flush bio's early so that make_request based
1923 * drivers without flush support don't have to worry
1926 if ((bio->bi_opf & (REQ_PREFLUSH | REQ_FUA)) &&
1927 !test_bit(QUEUE_FLAG_WC, &q->queue_flags)) {
1928 bio->bi_opf &= ~(REQ_PREFLUSH | REQ_FUA);
1935 switch (bio_op(bio)) {
1936 case REQ_OP_DISCARD:
1937 if (!blk_queue_discard(q))
1940 case REQ_OP_SECURE_ERASE:
1941 if (!blk_queue_secure_erase(q))
1944 case REQ_OP_WRITE_SAME:
1945 if (!bdev_write_same(bio->bi_bdev))
1953 * Various block parts want %current->io_context and lazy ioc
1954 * allocation ends up trading a lot of pain for a small amount of
1955 * memory. Just allocate it upfront. This may fail and block
1956 * layer knows how to live with it.
1958 create_io_context(GFP_ATOMIC, q->node);
1960 if (!blkcg_bio_issue_check(q, bio))
1963 trace_block_bio_queue(q, bio);
1969 bio->bi_error = err;
1975 * generic_make_request - hand a buffer to its device driver for I/O
1976 * @bio: The bio describing the location in memory and on the device.
1978 * generic_make_request() is used to make I/O requests of block
1979 * devices. It is passed a &struct bio, which describes the I/O that needs
1982 * generic_make_request() does not return any status. The
1983 * success/failure status of the request, along with notification of
1984 * completion, is delivered asynchronously through the bio->bi_end_io
1985 * function described (one day) else where.
1987 * The caller of generic_make_request must make sure that bi_io_vec
1988 * are set to describe the memory buffer, and that bi_dev and bi_sector are
1989 * set to describe the device address, and the
1990 * bi_end_io and optionally bi_private are set to describe how
1991 * completion notification should be signaled.
1993 * generic_make_request and the drivers it calls may use bi_next if this
1994 * bio happens to be merged with someone else, and may resubmit the bio to
1995 * a lower device by calling into generic_make_request recursively, which
1996 * means the bio should NOT be touched after the call to ->make_request_fn.
1998 blk_qc_t generic_make_request(struct bio *bio)
2001 * bio_list_on_stack[0] contains bios submitted by the current
2003 * bio_list_on_stack[1] contains bios that were submitted before
2004 * the current make_request_fn, but that haven't been processed
2007 struct bio_list bio_list_on_stack[2];
2008 blk_qc_t ret = BLK_QC_T_NONE;
2010 if (!generic_make_request_checks(bio))
2014 * We only want one ->make_request_fn to be active at a time, else
2015 * stack usage with stacked devices could be a problem. So use
2016 * current->bio_list to keep a list of requests submited by a
2017 * make_request_fn function. current->bio_list is also used as a
2018 * flag to say if generic_make_request is currently active in this
2019 * task or not. If it is NULL, then no make_request is active. If
2020 * it is non-NULL, then a make_request is active, and new requests
2021 * should be added at the tail
2023 if (current->bio_list) {
2024 bio_list_add(¤t->bio_list[0], bio);
2028 /* following loop may be a bit non-obvious, and so deserves some
2030 * Before entering the loop, bio->bi_next is NULL (as all callers
2031 * ensure that) so we have a list with a single bio.
2032 * We pretend that we have just taken it off a longer list, so
2033 * we assign bio_list to a pointer to the bio_list_on_stack,
2034 * thus initialising the bio_list of new bios to be
2035 * added. ->make_request() may indeed add some more bios
2036 * through a recursive call to generic_make_request. If it
2037 * did, we find a non-NULL value in bio_list and re-enter the loop
2038 * from the top. In this case we really did just take the bio
2039 * of the top of the list (no pretending) and so remove it from
2040 * bio_list, and call into ->make_request() again.
2042 BUG_ON(bio->bi_next);
2043 bio_list_init(&bio_list_on_stack[0]);
2044 current->bio_list = bio_list_on_stack;
2046 struct request_queue *q = bdev_get_queue(bio->bi_bdev);
2048 if (likely(blk_queue_enter(q, false) == 0)) {
2049 struct bio_list lower, same;
2051 /* Create a fresh bio_list for all subordinate requests */
2052 bio_list_on_stack[1] = bio_list_on_stack[0];
2053 bio_list_init(&bio_list_on_stack[0]);
2054 ret = q->make_request_fn(q, bio);
2058 /* sort new bios into those for a lower level
2059 * and those for the same level
2061 bio_list_init(&lower);
2062 bio_list_init(&same);
2063 while ((bio = bio_list_pop(&bio_list_on_stack[0])) != NULL)
2064 if (q == bdev_get_queue(bio->bi_bdev))
2065 bio_list_add(&same, bio);
2067 bio_list_add(&lower, bio);
2068 /* now assemble so we handle the lowest level first */
2069 bio_list_merge(&bio_list_on_stack[0], &lower);
2070 bio_list_merge(&bio_list_on_stack[0], &same);
2071 bio_list_merge(&bio_list_on_stack[0], &bio_list_on_stack[1]);
2075 bio = bio_list_pop(&bio_list_on_stack[0]);
2077 current->bio_list = NULL; /* deactivate */
2082 EXPORT_SYMBOL(generic_make_request);
2085 * submit_bio - submit a bio to the block device layer for I/O
2086 * @bio: The &struct bio which describes the I/O
2088 * submit_bio() is very similar in purpose to generic_make_request(), and
2089 * uses that function to do most of the work. Both are fairly rough
2090 * interfaces; @bio must be presetup and ready for I/O.
2093 blk_qc_t submit_bio(struct bio *bio)
2096 * If it's a regular read/write or a barrier with data attached,
2097 * go through the normal accounting stuff before submission.
2099 if (bio_has_data(bio)) {
2102 if (unlikely(bio_op(bio) == REQ_OP_WRITE_SAME))
2103 count = bdev_logical_block_size(bio->bi_bdev) >> 9;
2105 count = bio_sectors(bio);
2107 if (op_is_write(bio_op(bio))) {
2108 count_vm_events(PGPGOUT, count);
2110 task_io_account_read(bio->bi_iter.bi_size);
2111 count_vm_events(PGPGIN, count);
2114 if (unlikely(block_dump)) {
2115 char b[BDEVNAME_SIZE];
2116 printk(KERN_DEBUG "%s(%d): %s block %Lu on %s (%u sectors)\n",
2117 current->comm, task_pid_nr(current),
2118 op_is_write(bio_op(bio)) ? "WRITE" : "READ",
2119 (unsigned long long)bio->bi_iter.bi_sector,
2120 bdevname(bio->bi_bdev, b),
2125 return generic_make_request(bio);
2127 EXPORT_SYMBOL(submit_bio);
2130 * blk_cloned_rq_check_limits - Helper function to check a cloned request
2131 * for new the queue limits
2133 * @rq: the request being checked
2136 * @rq may have been made based on weaker limitations of upper-level queues
2137 * in request stacking drivers, and it may violate the limitation of @q.
2138 * Since the block layer and the underlying device driver trust @rq
2139 * after it is inserted to @q, it should be checked against @q before
2140 * the insertion using this generic function.
2142 * Request stacking drivers like request-based dm may change the queue
2143 * limits when retrying requests on other queues. Those requests need
2144 * to be checked against the new queue limits again during dispatch.
2146 static int blk_cloned_rq_check_limits(struct request_queue *q,
2149 if (blk_rq_sectors(rq) > blk_queue_get_max_sectors(q, req_op(rq))) {
2150 printk(KERN_ERR "%s: over max size limit.\n", __func__);
2155 * queue's settings related to segment counting like q->bounce_pfn
2156 * may differ from that of other stacking queues.
2157 * Recalculate it to check the request correctly on this queue's
2160 blk_recalc_rq_segments(rq);
2161 if (rq->nr_phys_segments > queue_max_segments(q)) {
2162 printk(KERN_ERR "%s: over max segments limit.\n", __func__);
2170 * blk_insert_cloned_request - Helper for stacking drivers to submit a request
2171 * @q: the queue to submit the request
2172 * @rq: the request being queued
2174 int blk_insert_cloned_request(struct request_queue *q, struct request *rq)
2176 unsigned long flags;
2177 int where = ELEVATOR_INSERT_BACK;
2179 if (blk_cloned_rq_check_limits(q, rq))
2183 should_fail_request(&rq->rq_disk->part0, blk_rq_bytes(rq)))
2187 if (blk_queue_io_stat(q))
2188 blk_account_io_start(rq, true);
2189 blk_mq_insert_request(rq, false, true, false);
2193 spin_lock_irqsave(q->queue_lock, flags);
2194 if (unlikely(blk_queue_dying(q))) {
2195 spin_unlock_irqrestore(q->queue_lock, flags);
2200 * Submitting request must be dequeued before calling this function
2201 * because it will be linked to another request_queue
2203 BUG_ON(blk_queued_rq(rq));
2205 if (rq->cmd_flags & (REQ_PREFLUSH | REQ_FUA))
2206 where = ELEVATOR_INSERT_FLUSH;
2208 add_acct_request(q, rq, where);
2209 if (where == ELEVATOR_INSERT_FLUSH)
2211 spin_unlock_irqrestore(q->queue_lock, flags);
2215 EXPORT_SYMBOL_GPL(blk_insert_cloned_request);
2218 * blk_rq_err_bytes - determine number of bytes till the next failure boundary
2219 * @rq: request to examine
2222 * A request could be merge of IOs which require different failure
2223 * handling. This function determines the number of bytes which
2224 * can be failed from the beginning of the request without
2225 * crossing into area which need to be retried further.
2228 * The number of bytes to fail.
2231 * queue_lock must be held.
2233 unsigned int blk_rq_err_bytes(const struct request *rq)
2235 unsigned int ff = rq->cmd_flags & REQ_FAILFAST_MASK;
2236 unsigned int bytes = 0;
2239 if (!(rq->cmd_flags & REQ_MIXED_MERGE))
2240 return blk_rq_bytes(rq);
2243 * Currently the only 'mixing' which can happen is between
2244 * different fastfail types. We can safely fail portions
2245 * which have all the failfast bits that the first one has -
2246 * the ones which are at least as eager to fail as the first
2249 for (bio = rq->bio; bio; bio = bio->bi_next) {
2250 if ((bio->bi_opf & ff) != ff)
2252 bytes += bio->bi_iter.bi_size;
2255 /* this could lead to infinite loop */
2256 BUG_ON(blk_rq_bytes(rq) && !bytes);
2259 EXPORT_SYMBOL_GPL(blk_rq_err_bytes);
2261 void blk_account_io_completion(struct request *req, unsigned int bytes)
2263 if (blk_do_io_stat(req)) {
2264 const int rw = rq_data_dir(req);
2265 struct hd_struct *part;
2268 cpu = part_stat_lock();
2270 part_stat_add(cpu, part, sectors[rw], bytes >> 9);
2275 void blk_account_io_done(struct request *req)
2278 * Account IO completion. flush_rq isn't accounted as a
2279 * normal IO on queueing nor completion. Accounting the
2280 * containing request is enough.
2282 if (blk_do_io_stat(req) && !(req->cmd_flags & REQ_FLUSH_SEQ)) {
2283 unsigned long duration = jiffies - req->start_time;
2284 const int rw = rq_data_dir(req);
2285 struct hd_struct *part;
2288 cpu = part_stat_lock();
2291 part_stat_inc(cpu, part, ios[rw]);
2292 part_stat_add(cpu, part, ticks[rw], duration);
2293 part_round_stats(cpu, part);
2294 part_dec_in_flight(part, rw);
2296 hd_struct_put(part);
2303 * Don't process normal requests when queue is suspended
2304 * or in the process of suspending/resuming
2306 static struct request *blk_pm_peek_request(struct request_queue *q,
2309 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
2310 (q->rpm_status != RPM_ACTIVE && !(rq->cmd_flags & REQ_PM))))
2316 static inline struct request *blk_pm_peek_request(struct request_queue *q,
2323 void blk_account_io_start(struct request *rq, bool new_io)
2325 struct hd_struct *part;
2326 int rw = rq_data_dir(rq);
2329 if (!blk_do_io_stat(rq))
2332 cpu = part_stat_lock();
2336 part_stat_inc(cpu, part, merges[rw]);
2338 part = disk_map_sector_rcu(rq->rq_disk, blk_rq_pos(rq));
2339 if (!hd_struct_try_get(part)) {
2341 * The partition is already being removed,
2342 * the request will be accounted on the disk only
2344 * We take a reference on disk->part0 although that
2345 * partition will never be deleted, so we can treat
2346 * it as any other partition.
2348 part = &rq->rq_disk->part0;
2349 hd_struct_get(part);
2351 part_round_stats(cpu, part);
2352 part_inc_in_flight(part, rw);
2360 * blk_peek_request - peek at the top of a request queue
2361 * @q: request queue to peek at
2364 * Return the request at the top of @q. The returned request
2365 * should be started using blk_start_request() before LLD starts
2369 * Pointer to the request at the top of @q if available. Null
2373 * queue_lock must be held.
2375 struct request *blk_peek_request(struct request_queue *q)
2380 while ((rq = __elv_next_request(q)) != NULL) {
2382 rq = blk_pm_peek_request(q, rq);
2386 if (!(rq->cmd_flags & REQ_STARTED)) {
2388 * This is the first time the device driver
2389 * sees this request (possibly after
2390 * requeueing). Notify IO scheduler.
2392 if (rq->cmd_flags & REQ_SORTED)
2393 elv_activate_rq(q, rq);
2396 * just mark as started even if we don't start
2397 * it, a request that has been delayed should
2398 * not be passed by new incoming requests
2400 rq->cmd_flags |= REQ_STARTED;
2401 trace_block_rq_issue(q, rq);
2404 if (!q->boundary_rq || q->boundary_rq == rq) {
2405 q->end_sector = rq_end_sector(rq);
2406 q->boundary_rq = NULL;
2409 if (rq->cmd_flags & REQ_DONTPREP)
2412 if (q->dma_drain_size && blk_rq_bytes(rq)) {
2414 * make sure space for the drain appears we
2415 * know we can do this because max_hw_segments
2416 * has been adjusted to be one fewer than the
2419 rq->nr_phys_segments++;
2425 ret = q->prep_rq_fn(q, rq);
2426 if (ret == BLKPREP_OK) {
2428 } else if (ret == BLKPREP_DEFER) {
2430 * the request may have been (partially) prepped.
2431 * we need to keep this request in the front to
2432 * avoid resource deadlock. REQ_STARTED will
2433 * prevent other fs requests from passing this one.
2435 if (q->dma_drain_size && blk_rq_bytes(rq) &&
2436 !(rq->cmd_flags & REQ_DONTPREP)) {
2438 * remove the space for the drain we added
2439 * so that we don't add it again
2441 --rq->nr_phys_segments;
2446 } else if (ret == BLKPREP_KILL || ret == BLKPREP_INVALID) {
2447 int err = (ret == BLKPREP_INVALID) ? -EREMOTEIO : -EIO;
2449 rq->cmd_flags |= REQ_QUIET;
2451 * Mark this request as started so we don't trigger
2452 * any debug logic in the end I/O path.
2454 blk_start_request(rq);
2455 __blk_end_request_all(rq, err);
2457 printk(KERN_ERR "%s: bad return=%d\n", __func__, ret);
2464 EXPORT_SYMBOL(blk_peek_request);
2466 void blk_dequeue_request(struct request *rq)
2468 struct request_queue *q = rq->q;
2470 BUG_ON(list_empty(&rq->queuelist));
2471 BUG_ON(ELV_ON_HASH(rq));
2473 list_del_init(&rq->queuelist);
2476 * the time frame between a request being removed from the lists
2477 * and to it is freed is accounted as io that is in progress at
2480 if (blk_account_rq(rq)) {
2481 q->in_flight[rq_is_sync(rq)]++;
2482 set_io_start_time_ns(rq);
2487 * blk_start_request - start request processing on the driver
2488 * @req: request to dequeue
2491 * Dequeue @req and start timeout timer on it. This hands off the
2492 * request to the driver.
2494 * Block internal functions which don't want to start timer should
2495 * call blk_dequeue_request().
2498 * queue_lock must be held.
2500 void blk_start_request(struct request *req)
2502 blk_dequeue_request(req);
2505 * We are now handing the request to the hardware, initialize
2506 * resid_len to full count and add the timeout handler.
2508 req->resid_len = blk_rq_bytes(req);
2509 if (unlikely(blk_bidi_rq(req)))
2510 req->next_rq->resid_len = blk_rq_bytes(req->next_rq);
2512 BUG_ON(test_bit(REQ_ATOM_COMPLETE, &req->atomic_flags));
2515 EXPORT_SYMBOL(blk_start_request);
2518 * blk_fetch_request - fetch a request from a request queue
2519 * @q: request queue to fetch a request from
2522 * Return the request at the top of @q. The request is started on
2523 * return and LLD can start processing it immediately.
2526 * Pointer to the request at the top of @q if available. Null
2530 * queue_lock must be held.
2532 struct request *blk_fetch_request(struct request_queue *q)
2536 rq = blk_peek_request(q);
2538 blk_start_request(rq);
2541 EXPORT_SYMBOL(blk_fetch_request);
2544 * blk_update_request - Special helper function for request stacking drivers
2545 * @req: the request being processed
2546 * @error: %0 for success, < %0 for error
2547 * @nr_bytes: number of bytes to complete @req
2550 * Ends I/O on a number of bytes attached to @req, but doesn't complete
2551 * the request structure even if @req doesn't have leftover.
2552 * If @req has leftover, sets it up for the next range of segments.
2554 * This special helper function is only for request stacking drivers
2555 * (e.g. request-based dm) so that they can handle partial completion.
2556 * Actual device drivers should use blk_end_request instead.
2558 * Passing the result of blk_rq_bytes() as @nr_bytes guarantees
2559 * %false return from this function.
2562 * %false - this request doesn't have any more data
2563 * %true - this request has more data
2565 bool blk_update_request(struct request *req, int error, unsigned int nr_bytes)
2569 trace_block_rq_complete(req->q, req, nr_bytes);
2575 * For fs requests, rq is just carrier of independent bio's
2576 * and each partial completion should be handled separately.
2577 * Reset per-request error on each partial completion.
2579 * TODO: tj: This is too subtle. It would be better to let
2580 * low level drivers do what they see fit.
2582 if (req->cmd_type == REQ_TYPE_FS)
2585 if (error && req->cmd_type == REQ_TYPE_FS &&
2586 !(req->cmd_flags & REQ_QUIET)) {
2591 error_type = "recoverable transport";
2594 error_type = "critical target";
2597 error_type = "critical nexus";
2600 error_type = "timeout";
2603 error_type = "critical space allocation";
2606 error_type = "critical medium";
2613 printk_ratelimited(KERN_ERR "%s: %s error, dev %s, sector %llu\n",
2614 __func__, error_type, req->rq_disk ?
2615 req->rq_disk->disk_name : "?",
2616 (unsigned long long)blk_rq_pos(req));
2620 blk_account_io_completion(req, nr_bytes);
2624 struct bio *bio = req->bio;
2625 unsigned bio_bytes = min(bio->bi_iter.bi_size, nr_bytes);
2627 if (bio_bytes == bio->bi_iter.bi_size)
2628 req->bio = bio->bi_next;
2630 req_bio_endio(req, bio, bio_bytes, error);
2632 total_bytes += bio_bytes;
2633 nr_bytes -= bio_bytes;
2644 * Reset counters so that the request stacking driver
2645 * can find how many bytes remain in the request
2648 req->__data_len = 0;
2652 req->__data_len -= total_bytes;
2654 /* update sector only for requests with clear definition of sector */
2655 if (req->cmd_type == REQ_TYPE_FS)
2656 req->__sector += total_bytes >> 9;
2658 /* mixed attributes always follow the first bio */
2659 if (req->cmd_flags & REQ_MIXED_MERGE) {
2660 req->cmd_flags &= ~REQ_FAILFAST_MASK;
2661 req->cmd_flags |= req->bio->bi_opf & REQ_FAILFAST_MASK;
2665 * If total number of sectors is less than the first segment
2666 * size, something has gone terribly wrong.
2668 if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {
2669 blk_dump_rq_flags(req, "request botched");
2670 req->__data_len = blk_rq_cur_bytes(req);
2673 /* recalculate the number of segments */
2674 blk_recalc_rq_segments(req);
2678 EXPORT_SYMBOL_GPL(blk_update_request);
2680 static bool blk_update_bidi_request(struct request *rq, int error,
2681 unsigned int nr_bytes,
2682 unsigned int bidi_bytes)
2684 if (blk_update_request(rq, error, nr_bytes))
2687 /* Bidi request must be completed as a whole */
2688 if (unlikely(blk_bidi_rq(rq)) &&
2689 blk_update_request(rq->next_rq, error, bidi_bytes))
2692 if (blk_queue_add_random(rq->q))
2693 add_disk_randomness(rq->rq_disk);
2699 * blk_unprep_request - unprepare a request
2702 * This function makes a request ready for complete resubmission (or
2703 * completion). It happens only after all error handling is complete,
2704 * so represents the appropriate moment to deallocate any resources
2705 * that were allocated to the request in the prep_rq_fn. The queue
2706 * lock is held when calling this.
2708 void blk_unprep_request(struct request *req)
2710 struct request_queue *q = req->q;
2712 req->cmd_flags &= ~REQ_DONTPREP;
2713 if (q->unprep_rq_fn)
2714 q->unprep_rq_fn(q, req);
2716 EXPORT_SYMBOL_GPL(blk_unprep_request);
2719 * queue lock must be held
2721 void blk_finish_request(struct request *req, int error)
2723 if (req->cmd_flags & REQ_QUEUED)
2724 blk_queue_end_tag(req->q, req);
2726 BUG_ON(blk_queued_rq(req));
2728 if (unlikely(laptop_mode) && req->cmd_type == REQ_TYPE_FS)
2729 laptop_io_completion(&req->q->backing_dev_info);
2731 blk_delete_timer(req);
2733 if (req->cmd_flags & REQ_DONTPREP)
2734 blk_unprep_request(req);
2736 blk_account_io_done(req);
2739 req->end_io(req, error);
2741 if (blk_bidi_rq(req))
2742 __blk_put_request(req->next_rq->q, req->next_rq);
2744 __blk_put_request(req->q, req);
2747 EXPORT_SYMBOL(blk_finish_request);
2750 * blk_end_bidi_request - Complete a bidi request
2751 * @rq: the request to complete
2752 * @error: %0 for success, < %0 for error
2753 * @nr_bytes: number of bytes to complete @rq
2754 * @bidi_bytes: number of bytes to complete @rq->next_rq
2757 * Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
2758 * Drivers that supports bidi can safely call this member for any
2759 * type of request, bidi or uni. In the later case @bidi_bytes is
2763 * %false - we are done with this request
2764 * %true - still buffers pending for this request
2766 static bool blk_end_bidi_request(struct request *rq, int error,
2767 unsigned int nr_bytes, unsigned int bidi_bytes)
2769 struct request_queue *q = rq->q;
2770 unsigned long flags;
2772 if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2775 spin_lock_irqsave(q->queue_lock, flags);
2776 blk_finish_request(rq, error);
2777 spin_unlock_irqrestore(q->queue_lock, flags);
2783 * __blk_end_bidi_request - Complete a bidi request with queue lock held
2784 * @rq: the request to complete
2785 * @error: %0 for success, < %0 for error
2786 * @nr_bytes: number of bytes to complete @rq
2787 * @bidi_bytes: number of bytes to complete @rq->next_rq
2790 * Identical to blk_end_bidi_request() except that queue lock is
2791 * assumed to be locked on entry and remains so on return.
2794 * %false - we are done with this request
2795 * %true - still buffers pending for this request
2797 bool __blk_end_bidi_request(struct request *rq, int error,
2798 unsigned int nr_bytes, unsigned int bidi_bytes)
2800 if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2803 blk_finish_request(rq, error);
2809 * blk_end_request - Helper function for drivers to complete the request.
2810 * @rq: the request being processed
2811 * @error: %0 for success, < %0 for error
2812 * @nr_bytes: number of bytes to complete
2815 * Ends I/O on a number of bytes attached to @rq.
2816 * If @rq has leftover, sets it up for the next range of segments.
2819 * %false - we are done with this request
2820 * %true - still buffers pending for this request
2822 bool blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
2824 return blk_end_bidi_request(rq, error, nr_bytes, 0);
2826 EXPORT_SYMBOL(blk_end_request);
2829 * blk_end_request_all - Helper function for drives to finish the request.
2830 * @rq: the request to finish
2831 * @error: %0 for success, < %0 for error
2834 * Completely finish @rq.
2836 void blk_end_request_all(struct request *rq, int error)
2839 unsigned int bidi_bytes = 0;
2841 if (unlikely(blk_bidi_rq(rq)))
2842 bidi_bytes = blk_rq_bytes(rq->next_rq);
2844 pending = blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2847 EXPORT_SYMBOL(blk_end_request_all);
2850 * blk_end_request_cur - Helper function to finish the current request chunk.
2851 * @rq: the request to finish the current chunk for
2852 * @error: %0 for success, < %0 for error
2855 * Complete the current consecutively mapped chunk from @rq.
2858 * %false - we are done with this request
2859 * %true - still buffers pending for this request
2861 bool blk_end_request_cur(struct request *rq, int error)
2863 return blk_end_request(rq, error, blk_rq_cur_bytes(rq));
2865 EXPORT_SYMBOL(blk_end_request_cur);
2868 * blk_end_request_err - Finish a request till the next failure boundary.
2869 * @rq: the request to finish till the next failure boundary for
2870 * @error: must be negative errno
2873 * Complete @rq till the next failure boundary.
2876 * %false - we are done with this request
2877 * %true - still buffers pending for this request
2879 bool blk_end_request_err(struct request *rq, int error)
2881 WARN_ON(error >= 0);
2882 return blk_end_request(rq, error, blk_rq_err_bytes(rq));
2884 EXPORT_SYMBOL_GPL(blk_end_request_err);
2887 * __blk_end_request - Helper function for drivers to complete the request.
2888 * @rq: the request being processed
2889 * @error: %0 for success, < %0 for error
2890 * @nr_bytes: number of bytes to complete
2893 * Must be called with queue lock held unlike blk_end_request().
2896 * %false - we are done with this request
2897 * %true - still buffers pending for this request
2899 bool __blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
2901 return __blk_end_bidi_request(rq, error, nr_bytes, 0);
2903 EXPORT_SYMBOL(__blk_end_request);
2906 * __blk_end_request_all - Helper function for drives to finish the request.
2907 * @rq: the request to finish
2908 * @error: %0 for success, < %0 for error
2911 * Completely finish @rq. Must be called with queue lock held.
2913 void __blk_end_request_all(struct request *rq, int error)
2916 unsigned int bidi_bytes = 0;
2918 if (unlikely(blk_bidi_rq(rq)))
2919 bidi_bytes = blk_rq_bytes(rq->next_rq);
2921 pending = __blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2924 EXPORT_SYMBOL(__blk_end_request_all);
2927 * __blk_end_request_cur - Helper function to finish the current request chunk.
2928 * @rq: the request to finish the current chunk for
2929 * @error: %0 for success, < %0 for error
2932 * Complete the current consecutively mapped chunk from @rq. Must
2933 * be called with queue lock held.
2936 * %false - we are done with this request
2937 * %true - still buffers pending for this request
2939 bool __blk_end_request_cur(struct request *rq, int error)
2941 return __blk_end_request(rq, error, blk_rq_cur_bytes(rq));
2943 EXPORT_SYMBOL(__blk_end_request_cur);
2946 * __blk_end_request_err - Finish a request till the next failure boundary.
2947 * @rq: the request to finish till the next failure boundary for
2948 * @error: must be negative errno
2951 * Complete @rq till the next failure boundary. Must be called
2952 * with queue lock held.
2955 * %false - we are done with this request
2956 * %true - still buffers pending for this request
2958 bool __blk_end_request_err(struct request *rq, int error)
2960 WARN_ON(error >= 0);
2961 return __blk_end_request(rq, error, blk_rq_err_bytes(rq));
2963 EXPORT_SYMBOL_GPL(__blk_end_request_err);
2965 void blk_rq_bio_prep(struct request_queue *q, struct request *rq,
2968 req_set_op(rq, bio_op(bio));
2970 if (bio_has_data(bio))
2971 rq->nr_phys_segments = bio_phys_segments(q, bio);
2973 rq->__data_len = bio->bi_iter.bi_size;
2974 rq->bio = rq->biotail = bio;
2977 rq->rq_disk = bio->bi_bdev->bd_disk;
2980 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE
2982 * rq_flush_dcache_pages - Helper function to flush all pages in a request
2983 * @rq: the request to be flushed
2986 * Flush all pages in @rq.
2988 void rq_flush_dcache_pages(struct request *rq)
2990 struct req_iterator iter;
2991 struct bio_vec bvec;
2993 rq_for_each_segment(bvec, rq, iter)
2994 flush_dcache_page(bvec.bv_page);
2996 EXPORT_SYMBOL_GPL(rq_flush_dcache_pages);
3000 * blk_lld_busy - Check if underlying low-level drivers of a device are busy
3001 * @q : the queue of the device being checked
3004 * Check if underlying low-level drivers of a device are busy.
3005 * If the drivers want to export their busy state, they must set own
3006 * exporting function using blk_queue_lld_busy() first.
3008 * Basically, this function is used only by request stacking drivers
3009 * to stop dispatching requests to underlying devices when underlying
3010 * devices are busy. This behavior helps more I/O merging on the queue
3011 * of the request stacking driver and prevents I/O throughput regression
3012 * on burst I/O load.
3015 * 0 - Not busy (The request stacking driver should dispatch request)
3016 * 1 - Busy (The request stacking driver should stop dispatching request)
3018 int blk_lld_busy(struct request_queue *q)
3021 return q->lld_busy_fn(q);
3025 EXPORT_SYMBOL_GPL(blk_lld_busy);
3028 * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
3029 * @rq: the clone request to be cleaned up
3032 * Free all bios in @rq for a cloned request.
3034 void blk_rq_unprep_clone(struct request *rq)
3038 while ((bio = rq->bio) != NULL) {
3039 rq->bio = bio->bi_next;
3044 EXPORT_SYMBOL_GPL(blk_rq_unprep_clone);
3047 * Copy attributes of the original request to the clone request.
3048 * The actual data parts (e.g. ->cmd, ->sense) are not copied.
3050 static void __blk_rq_prep_clone(struct request *dst, struct request *src)
3052 dst->cpu = src->cpu;
3053 req_set_op_attrs(dst, req_op(src),
3054 (src->cmd_flags & REQ_CLONE_MASK) | REQ_NOMERGE);
3055 dst->cmd_type = src->cmd_type;
3056 dst->__sector = blk_rq_pos(src);
3057 dst->__data_len = blk_rq_bytes(src);
3058 dst->nr_phys_segments = src->nr_phys_segments;
3059 dst->ioprio = src->ioprio;
3060 dst->extra_len = src->extra_len;
3064 * blk_rq_prep_clone - Helper function to setup clone request
3065 * @rq: the request to be setup
3066 * @rq_src: original request to be cloned
3067 * @bs: bio_set that bios for clone are allocated from
3068 * @gfp_mask: memory allocation mask for bio
3069 * @bio_ctr: setup function to be called for each clone bio.
3070 * Returns %0 for success, non %0 for failure.
3071 * @data: private data to be passed to @bio_ctr
3074 * Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
3075 * The actual data parts of @rq_src (e.g. ->cmd, ->sense)
3076 * are not copied, and copying such parts is the caller's responsibility.
3077 * Also, pages which the original bios are pointing to are not copied
3078 * and the cloned bios just point same pages.
3079 * So cloned bios must be completed before original bios, which means
3080 * the caller must complete @rq before @rq_src.
3082 int blk_rq_prep_clone(struct request *rq, struct request *rq_src,
3083 struct bio_set *bs, gfp_t gfp_mask,
3084 int (*bio_ctr)(struct bio *, struct bio *, void *),
3087 struct bio *bio, *bio_src;
3092 __rq_for_each_bio(bio_src, rq_src) {
3093 bio = bio_clone_fast(bio_src, gfp_mask, bs);
3097 if (bio_ctr && bio_ctr(bio, bio_src, data))
3101 rq->biotail->bi_next = bio;
3104 rq->bio = rq->biotail = bio;
3107 __blk_rq_prep_clone(rq, rq_src);
3114 blk_rq_unprep_clone(rq);
3118 EXPORT_SYMBOL_GPL(blk_rq_prep_clone);
3120 int kblockd_schedule_work(struct work_struct *work)
3122 return queue_work(kblockd_workqueue, work);
3124 EXPORT_SYMBOL(kblockd_schedule_work);
3126 int kblockd_schedule_work_on(int cpu, struct work_struct *work)
3128 return queue_work_on(cpu, kblockd_workqueue, work);
3130 EXPORT_SYMBOL(kblockd_schedule_work_on);
3132 int kblockd_schedule_delayed_work(struct delayed_work *dwork,
3133 unsigned long delay)
3135 return queue_delayed_work(kblockd_workqueue, dwork, delay);
3137 EXPORT_SYMBOL(kblockd_schedule_delayed_work);
3139 int kblockd_schedule_delayed_work_on(int cpu, struct delayed_work *dwork,
3140 unsigned long delay)
3142 return queue_delayed_work_on(cpu, kblockd_workqueue, dwork, delay);
3144 EXPORT_SYMBOL(kblockd_schedule_delayed_work_on);
3147 * blk_start_plug - initialize blk_plug and track it inside the task_struct
3148 * @plug: The &struct blk_plug that needs to be initialized
3151 * Tracking blk_plug inside the task_struct will help with auto-flushing the
3152 * pending I/O should the task end up blocking between blk_start_plug() and
3153 * blk_finish_plug(). This is important from a performance perspective, but
3154 * also ensures that we don't deadlock. For instance, if the task is blocking
3155 * for a memory allocation, memory reclaim could end up wanting to free a
3156 * page belonging to that request that is currently residing in our private
3157 * plug. By flushing the pending I/O when the process goes to sleep, we avoid
3158 * this kind of deadlock.
3160 void blk_start_plug(struct blk_plug *plug)
3162 struct task_struct *tsk = current;
3165 * If this is a nested plug, don't actually assign it.
3170 INIT_LIST_HEAD(&plug->list);
3171 INIT_LIST_HEAD(&plug->mq_list);
3172 INIT_LIST_HEAD(&plug->cb_list);
3174 * Store ordering should not be needed here, since a potential
3175 * preempt will imply a full memory barrier
3179 EXPORT_SYMBOL(blk_start_plug);
3181 static int plug_rq_cmp(void *priv, struct list_head *a, struct list_head *b)
3183 struct request *rqa = container_of(a, struct request, queuelist);
3184 struct request *rqb = container_of(b, struct request, queuelist);
3186 return !(rqa->q < rqb->q ||
3187 (rqa->q == rqb->q && blk_rq_pos(rqa) < blk_rq_pos(rqb)));
3191 * If 'from_schedule' is true, then postpone the dispatch of requests
3192 * until a safe kblockd context. We due this to avoid accidental big
3193 * additional stack usage in driver dispatch, in places where the originally
3194 * plugger did not intend it.
3196 static void queue_unplugged(struct request_queue *q, unsigned int depth,
3198 __releases(q->queue_lock)
3200 trace_block_unplug(q, depth, !from_schedule);
3203 blk_run_queue_async(q);
3206 spin_unlock(q->queue_lock);
3209 static void flush_plug_callbacks(struct blk_plug *plug, bool from_schedule)
3211 LIST_HEAD(callbacks);
3213 while (!list_empty(&plug->cb_list)) {
3214 list_splice_init(&plug->cb_list, &callbacks);
3216 while (!list_empty(&callbacks)) {
3217 struct blk_plug_cb *cb = list_first_entry(&callbacks,
3220 list_del(&cb->list);
3221 cb->callback(cb, from_schedule);
3226 struct blk_plug_cb *blk_check_plugged(blk_plug_cb_fn unplug, void *data,
3229 struct blk_plug *plug = current->plug;
3230 struct blk_plug_cb *cb;
3235 list_for_each_entry(cb, &plug->cb_list, list)
3236 if (cb->callback == unplug && cb->data == data)
3239 /* Not currently on the callback list */
3240 BUG_ON(size < sizeof(*cb));
3241 cb = kzalloc(size, GFP_ATOMIC);
3244 cb->callback = unplug;
3245 list_add(&cb->list, &plug->cb_list);
3249 EXPORT_SYMBOL(blk_check_plugged);
3251 void blk_flush_plug_list(struct blk_plug *plug, bool from_schedule)
3253 struct request_queue *q;
3254 unsigned long flags;
3259 flush_plug_callbacks(plug, from_schedule);
3261 if (!list_empty(&plug->mq_list))
3262 blk_mq_flush_plug_list(plug, from_schedule);
3264 if (list_empty(&plug->list))
3267 list_splice_init(&plug->list, &list);
3269 list_sort(NULL, &list, plug_rq_cmp);
3275 * Save and disable interrupts here, to avoid doing it for every
3276 * queue lock we have to take.
3278 local_irq_save(flags);
3279 while (!list_empty(&list)) {
3280 rq = list_entry_rq(list.next);
3281 list_del_init(&rq->queuelist);
3285 * This drops the queue lock
3288 queue_unplugged(q, depth, from_schedule);
3291 spin_lock(q->queue_lock);
3295 * Short-circuit if @q is dead
3297 if (unlikely(blk_queue_dying(q))) {
3298 __blk_end_request_all(rq, -ENODEV);
3303 * rq is already accounted, so use raw insert
3305 if (rq->cmd_flags & (REQ_PREFLUSH | REQ_FUA))
3306 __elv_add_request(q, rq, ELEVATOR_INSERT_FLUSH);
3308 __elv_add_request(q, rq, ELEVATOR_INSERT_SORT_MERGE);
3314 * This drops the queue lock
3317 queue_unplugged(q, depth, from_schedule);
3319 local_irq_restore(flags);
3322 void blk_finish_plug(struct blk_plug *plug)
3324 if (plug != current->plug)
3326 blk_flush_plug_list(plug, false);
3328 current->plug = NULL;
3330 EXPORT_SYMBOL(blk_finish_plug);
3332 bool blk_poll(struct request_queue *q, blk_qc_t cookie)
3334 struct blk_plug *plug;
3336 unsigned int queue_num;
3337 struct blk_mq_hw_ctx *hctx;
3339 if (!q->mq_ops || !q->mq_ops->poll || !blk_qc_t_valid(cookie) ||
3340 !test_bit(QUEUE_FLAG_POLL, &q->queue_flags))
3343 queue_num = blk_qc_t_to_queue_num(cookie);
3344 hctx = q->queue_hw_ctx[queue_num];
3345 hctx->poll_considered++;
3347 plug = current->plug;
3349 blk_flush_plug_list(plug, false);
3351 state = current->state;
3352 while (!need_resched()) {
3355 hctx->poll_invoked++;
3357 ret = q->mq_ops->poll(hctx, blk_qc_t_to_tag(cookie));
3359 hctx->poll_success++;
3360 set_current_state(TASK_RUNNING);
3364 if (signal_pending_state(state, current))
3365 set_current_state(TASK_RUNNING);
3367 if (current->state == TASK_RUNNING)
3376 EXPORT_SYMBOL_GPL(blk_poll);
3380 * blk_pm_runtime_init - Block layer runtime PM initialization routine
3381 * @q: the queue of the device
3382 * @dev: the device the queue belongs to
3385 * Initialize runtime-PM-related fields for @q and start auto suspend for
3386 * @dev. Drivers that want to take advantage of request-based runtime PM
3387 * should call this function after @dev has been initialized, and its
3388 * request queue @q has been allocated, and runtime PM for it can not happen
3389 * yet(either due to disabled/forbidden or its usage_count > 0). In most
3390 * cases, driver should call this function before any I/O has taken place.
3392 * This function takes care of setting up using auto suspend for the device,
3393 * the autosuspend delay is set to -1 to make runtime suspend impossible
3394 * until an updated value is either set by user or by driver. Drivers do
3395 * not need to touch other autosuspend settings.
3397 * The block layer runtime PM is request based, so only works for drivers
3398 * that use request as their IO unit instead of those directly use bio's.
3400 void blk_pm_runtime_init(struct request_queue *q, struct device *dev)
3403 q->rpm_status = RPM_ACTIVE;
3404 pm_runtime_set_autosuspend_delay(q->dev, -1);
3405 pm_runtime_use_autosuspend(q->dev);
3407 EXPORT_SYMBOL(blk_pm_runtime_init);
3410 * blk_pre_runtime_suspend - Pre runtime suspend check
3411 * @q: the queue of the device
3414 * This function will check if runtime suspend is allowed for the device
3415 * by examining if there are any requests pending in the queue. If there
3416 * are requests pending, the device can not be runtime suspended; otherwise,
3417 * the queue's status will be updated to SUSPENDING and the driver can
3418 * proceed to suspend the device.
3420 * For the not allowed case, we mark last busy for the device so that
3421 * runtime PM core will try to autosuspend it some time later.
3423 * This function should be called near the start of the device's
3424 * runtime_suspend callback.
3427 * 0 - OK to runtime suspend the device
3428 * -EBUSY - Device should not be runtime suspended
3430 int blk_pre_runtime_suspend(struct request_queue *q)
3437 spin_lock_irq(q->queue_lock);
3438 if (q->nr_pending) {
3440 pm_runtime_mark_last_busy(q->dev);
3442 q->rpm_status = RPM_SUSPENDING;
3444 spin_unlock_irq(q->queue_lock);
3447 EXPORT_SYMBOL(blk_pre_runtime_suspend);
3450 * blk_post_runtime_suspend - Post runtime suspend processing
3451 * @q: the queue of the device
3452 * @err: return value of the device's runtime_suspend function
3455 * Update the queue's runtime status according to the return value of the
3456 * device's runtime suspend function and mark last busy for the device so
3457 * that PM core will try to auto suspend the device at a later time.
3459 * This function should be called near the end of the device's
3460 * runtime_suspend callback.
3462 void blk_post_runtime_suspend(struct request_queue *q, int err)
3467 spin_lock_irq(q->queue_lock);
3469 q->rpm_status = RPM_SUSPENDED;
3471 q->rpm_status = RPM_ACTIVE;
3472 pm_runtime_mark_last_busy(q->dev);
3474 spin_unlock_irq(q->queue_lock);
3476 EXPORT_SYMBOL(blk_post_runtime_suspend);
3479 * blk_pre_runtime_resume - Pre runtime resume processing
3480 * @q: the queue of the device
3483 * Update the queue's runtime status to RESUMING in preparation for the
3484 * runtime resume of the device.
3486 * This function should be called near the start of the device's
3487 * runtime_resume callback.
3489 void blk_pre_runtime_resume(struct request_queue *q)
3494 spin_lock_irq(q->queue_lock);
3495 q->rpm_status = RPM_RESUMING;
3496 spin_unlock_irq(q->queue_lock);
3498 EXPORT_SYMBOL(blk_pre_runtime_resume);
3501 * blk_post_runtime_resume - Post runtime resume processing
3502 * @q: the queue of the device
3503 * @err: return value of the device's runtime_resume function
3506 * Update the queue's runtime status according to the return value of the
3507 * device's runtime_resume function. If it is successfully resumed, process
3508 * the requests that are queued into the device's queue when it is resuming
3509 * and then mark last busy and initiate autosuspend for it.
3511 * This function should be called near the end of the device's
3512 * runtime_resume callback.
3514 void blk_post_runtime_resume(struct request_queue *q, int err)
3519 spin_lock_irq(q->queue_lock);
3521 q->rpm_status = RPM_ACTIVE;
3523 pm_runtime_mark_last_busy(q->dev);
3524 pm_request_autosuspend(q->dev);
3526 q->rpm_status = RPM_SUSPENDED;
3528 spin_unlock_irq(q->queue_lock);
3530 EXPORT_SYMBOL(blk_post_runtime_resume);
3533 * blk_set_runtime_active - Force runtime status of the queue to be active
3534 * @q: the queue of the device
3536 * If the device is left runtime suspended during system suspend the resume
3537 * hook typically resumes the device and corrects runtime status
3538 * accordingly. However, that does not affect the queue runtime PM status
3539 * which is still "suspended". This prevents processing requests from the
3542 * This function can be used in driver's resume hook to correct queue
3543 * runtime PM status and re-enable peeking requests from the queue. It
3544 * should be called before first request is added to the queue.
3546 void blk_set_runtime_active(struct request_queue *q)
3548 spin_lock_irq(q->queue_lock);
3549 q->rpm_status = RPM_ACTIVE;
3550 pm_runtime_mark_last_busy(q->dev);
3551 pm_request_autosuspend(q->dev);
3552 spin_unlock_irq(q->queue_lock);
3554 EXPORT_SYMBOL(blk_set_runtime_active);
3557 int __init blk_dev_init(void)
3559 BUILD_BUG_ON(__REQ_NR_BITS > 8 *
3560 FIELD_SIZEOF(struct request, cmd_flags));
3562 /* used for unplugging and affects IO latency/throughput - HIGHPRI */
3563 kblockd_workqueue = alloc_workqueue("kblockd",
3564 WQ_MEM_RECLAIM | WQ_HIGHPRI, 0);
3565 if (!kblockd_workqueue)
3566 panic("Failed to create kblockd\n");
3568 request_cachep = kmem_cache_create("blkdev_requests",
3569 sizeof(struct request), 0, SLAB_PANIC, NULL);
3571 blk_requestq_cachep = kmem_cache_create("request_queue",
3572 sizeof(struct request_queue), 0, SLAB_PANIC, NULL);