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>
36 #include <linux/debugfs.h>
38 #define CREATE_TRACE_POINTS
39 #include <trace/events/block.h>
43 #include "blk-mq-sched.h"
46 #ifdef CONFIG_DEBUG_FS
47 struct dentry *blk_debugfs_root;
50 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_remap);
51 EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_remap);
52 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_complete);
53 EXPORT_TRACEPOINT_SYMBOL_GPL(block_split);
54 EXPORT_TRACEPOINT_SYMBOL_GPL(block_unplug);
56 DEFINE_IDA(blk_queue_ida);
59 * For the allocated request tables
61 struct kmem_cache *request_cachep;
64 * For queue allocation
66 struct kmem_cache *blk_requestq_cachep;
69 * Controlling structure to kblockd
71 static struct workqueue_struct *kblockd_workqueue;
73 static void blk_clear_congested(struct request_list *rl, int sync)
75 #ifdef CONFIG_CGROUP_WRITEBACK
76 clear_wb_congested(rl->blkg->wb_congested, sync);
79 * If !CGROUP_WRITEBACK, all blkg's map to bdi->wb and we shouldn't
80 * flip its congestion state for events on other blkcgs.
82 if (rl == &rl->q->root_rl)
83 clear_wb_congested(rl->q->backing_dev_info->wb.congested, sync);
87 static void blk_set_congested(struct request_list *rl, int sync)
89 #ifdef CONFIG_CGROUP_WRITEBACK
90 set_wb_congested(rl->blkg->wb_congested, sync);
92 /* see blk_clear_congested() */
93 if (rl == &rl->q->root_rl)
94 set_wb_congested(rl->q->backing_dev_info->wb.congested, sync);
98 void blk_queue_congestion_threshold(struct request_queue *q)
102 nr = q->nr_requests - (q->nr_requests / 8) + 1;
103 if (nr > q->nr_requests)
105 q->nr_congestion_on = nr;
107 nr = q->nr_requests - (q->nr_requests / 8) - (q->nr_requests / 16) - 1;
110 q->nr_congestion_off = nr;
113 void blk_rq_init(struct request_queue *q, struct request *rq)
115 memset(rq, 0, sizeof(*rq));
117 INIT_LIST_HEAD(&rq->queuelist);
118 INIT_LIST_HEAD(&rq->timeout_list);
121 rq->__sector = (sector_t) -1;
122 INIT_HLIST_NODE(&rq->hash);
123 RB_CLEAR_NODE(&rq->rb_node);
125 rq->internal_tag = -1;
126 rq->start_time = jiffies;
127 set_start_time_ns(rq);
130 EXPORT_SYMBOL(blk_rq_init);
132 static const struct {
136 [BLK_STS_OK] = { 0, "" },
137 [BLK_STS_NOTSUPP] = { -EOPNOTSUPP, "operation not supported" },
138 [BLK_STS_TIMEOUT] = { -ETIMEDOUT, "timeout" },
139 [BLK_STS_NOSPC] = { -ENOSPC, "critical space allocation" },
140 [BLK_STS_TRANSPORT] = { -ENOLINK, "recoverable transport" },
141 [BLK_STS_TARGET] = { -EREMOTEIO, "critical target" },
142 [BLK_STS_NEXUS] = { -EBADE, "critical nexus" },
143 [BLK_STS_MEDIUM] = { -ENODATA, "critical medium" },
144 [BLK_STS_PROTECTION] = { -EILSEQ, "protection" },
145 [BLK_STS_RESOURCE] = { -ENOMEM, "kernel resource" },
146 [BLK_STS_AGAIN] = { -EAGAIN, "nonblocking retry" },
148 /* device mapper special case, should not leak out: */
149 [BLK_STS_DM_REQUEUE] = { -EREMCHG, "dm internal retry" },
151 /* everything else not covered above: */
152 [BLK_STS_IOERR] = { -EIO, "I/O" },
155 blk_status_t errno_to_blk_status(int errno)
159 for (i = 0; i < ARRAY_SIZE(blk_errors); i++) {
160 if (blk_errors[i].errno == errno)
161 return (__force blk_status_t)i;
164 return BLK_STS_IOERR;
166 EXPORT_SYMBOL_GPL(errno_to_blk_status);
168 int blk_status_to_errno(blk_status_t status)
170 int idx = (__force int)status;
172 if (WARN_ON_ONCE(idx > ARRAY_SIZE(blk_errors)))
174 return blk_errors[idx].errno;
176 EXPORT_SYMBOL_GPL(blk_status_to_errno);
178 static void print_req_error(struct request *req, blk_status_t status)
180 int idx = (__force int)status;
182 if (WARN_ON_ONCE(idx > ARRAY_SIZE(blk_errors)))
185 printk_ratelimited(KERN_ERR "%s: %s error, dev %s, sector %llu\n",
186 __func__, blk_errors[idx].name, req->rq_disk ?
187 req->rq_disk->disk_name : "?",
188 (unsigned long long)blk_rq_pos(req));
191 static void req_bio_endio(struct request *rq, struct bio *bio,
192 unsigned int nbytes, blk_status_t error)
195 bio->bi_status = error;
197 if (unlikely(rq->rq_flags & RQF_QUIET))
198 bio_set_flag(bio, BIO_QUIET);
200 bio_advance(bio, nbytes);
202 /* don't actually finish bio if it's part of flush sequence */
203 if (bio->bi_iter.bi_size == 0 && !(rq->rq_flags & RQF_FLUSH_SEQ))
207 void blk_dump_rq_flags(struct request *rq, char *msg)
209 printk(KERN_INFO "%s: dev %s: flags=%llx\n", msg,
210 rq->rq_disk ? rq->rq_disk->disk_name : "?",
211 (unsigned long long) rq->cmd_flags);
213 printk(KERN_INFO " sector %llu, nr/cnr %u/%u\n",
214 (unsigned long long)blk_rq_pos(rq),
215 blk_rq_sectors(rq), blk_rq_cur_sectors(rq));
216 printk(KERN_INFO " bio %p, biotail %p, len %u\n",
217 rq->bio, rq->biotail, blk_rq_bytes(rq));
219 EXPORT_SYMBOL(blk_dump_rq_flags);
221 static void blk_delay_work(struct work_struct *work)
223 struct request_queue *q;
225 q = container_of(work, struct request_queue, delay_work.work);
226 spin_lock_irq(q->queue_lock);
228 spin_unlock_irq(q->queue_lock);
232 * blk_delay_queue - restart queueing after defined interval
233 * @q: The &struct request_queue in question
234 * @msecs: Delay in msecs
237 * Sometimes queueing needs to be postponed for a little while, to allow
238 * resources to come back. This function will make sure that queueing is
239 * restarted around the specified time.
241 void blk_delay_queue(struct request_queue *q, unsigned long msecs)
243 lockdep_assert_held(q->queue_lock);
245 if (likely(!blk_queue_dead(q)))
246 queue_delayed_work(kblockd_workqueue, &q->delay_work,
247 msecs_to_jiffies(msecs));
249 EXPORT_SYMBOL(blk_delay_queue);
252 * blk_start_queue_async - asynchronously restart a previously stopped queue
253 * @q: The &struct request_queue in question
256 * blk_start_queue_async() will clear the stop flag on the queue, and
257 * ensure that the request_fn for the queue is run from an async
260 void blk_start_queue_async(struct request_queue *q)
262 lockdep_assert_held(q->queue_lock);
264 queue_flag_clear(QUEUE_FLAG_STOPPED, q);
265 blk_run_queue_async(q);
267 EXPORT_SYMBOL(blk_start_queue_async);
270 * blk_start_queue - restart a previously stopped queue
271 * @q: The &struct request_queue in question
274 * blk_start_queue() will clear the stop flag on the queue, and call
275 * the request_fn for the queue if it was in a stopped state when
276 * entered. Also see blk_stop_queue().
278 void blk_start_queue(struct request_queue *q)
280 lockdep_assert_held(q->queue_lock);
281 WARN_ON(!irqs_disabled());
283 queue_flag_clear(QUEUE_FLAG_STOPPED, q);
286 EXPORT_SYMBOL(blk_start_queue);
289 * blk_stop_queue - stop a queue
290 * @q: The &struct request_queue in question
293 * The Linux block layer assumes that a block driver will consume all
294 * entries on the request queue when the request_fn strategy is called.
295 * Often this will not happen, because of hardware limitations (queue
296 * depth settings). If a device driver gets a 'queue full' response,
297 * or if it simply chooses not to queue more I/O at one point, it can
298 * call this function to prevent the request_fn from being called until
299 * the driver has signalled it's ready to go again. This happens by calling
300 * blk_start_queue() to restart queue operations.
302 void blk_stop_queue(struct request_queue *q)
304 lockdep_assert_held(q->queue_lock);
306 cancel_delayed_work(&q->delay_work);
307 queue_flag_set(QUEUE_FLAG_STOPPED, q);
309 EXPORT_SYMBOL(blk_stop_queue);
312 * blk_sync_queue - cancel any pending callbacks on a queue
316 * The block layer may perform asynchronous callback activity
317 * on a queue, such as calling the unplug function after a timeout.
318 * A block device may call blk_sync_queue to ensure that any
319 * such activity is cancelled, thus allowing it to release resources
320 * that the callbacks might use. The caller must already have made sure
321 * that its ->make_request_fn will not re-add plugging prior to calling
324 * This function does not cancel any asynchronous activity arising
325 * out of elevator or throttling code. That would require elevator_exit()
326 * and blkcg_exit_queue() to be called with queue lock initialized.
329 void blk_sync_queue(struct request_queue *q)
331 del_timer_sync(&q->timeout);
334 struct blk_mq_hw_ctx *hctx;
337 queue_for_each_hw_ctx(q, hctx, i)
338 cancel_delayed_work_sync(&hctx->run_work);
340 cancel_delayed_work_sync(&q->delay_work);
343 EXPORT_SYMBOL(blk_sync_queue);
346 * __blk_run_queue_uncond - run a queue whether or not it has been stopped
347 * @q: The queue to run
350 * Invoke request handling on a queue if there are any pending requests.
351 * May be used to restart request handling after a request has completed.
352 * This variant runs the queue whether or not the queue has been
353 * stopped. Must be called with the queue lock held and interrupts
354 * disabled. See also @blk_run_queue.
356 inline void __blk_run_queue_uncond(struct request_queue *q)
358 lockdep_assert_held(q->queue_lock);
360 if (unlikely(blk_queue_dead(q)))
364 * Some request_fn implementations, e.g. scsi_request_fn(), unlock
365 * the queue lock internally. As a result multiple threads may be
366 * running such a request function concurrently. Keep track of the
367 * number of active request_fn invocations such that blk_drain_queue()
368 * can wait until all these request_fn calls have finished.
370 q->request_fn_active++;
372 q->request_fn_active--;
374 EXPORT_SYMBOL_GPL(__blk_run_queue_uncond);
377 * __blk_run_queue - run a single device queue
378 * @q: The queue to run
381 * See @blk_run_queue.
383 void __blk_run_queue(struct request_queue *q)
385 lockdep_assert_held(q->queue_lock);
387 if (unlikely(blk_queue_stopped(q)))
390 __blk_run_queue_uncond(q);
392 EXPORT_SYMBOL(__blk_run_queue);
395 * blk_run_queue_async - run a single device queue in workqueue context
396 * @q: The queue to run
399 * Tells kblockd to perform the equivalent of @blk_run_queue on behalf
403 * Since it is not allowed to run q->delay_work after blk_cleanup_queue()
404 * has canceled q->delay_work, callers must hold the queue lock to avoid
405 * race conditions between blk_cleanup_queue() and blk_run_queue_async().
407 void blk_run_queue_async(struct request_queue *q)
409 lockdep_assert_held(q->queue_lock);
411 if (likely(!blk_queue_stopped(q) && !blk_queue_dead(q)))
412 mod_delayed_work(kblockd_workqueue, &q->delay_work, 0);
414 EXPORT_SYMBOL(blk_run_queue_async);
417 * blk_run_queue - run a single device queue
418 * @q: The queue to run
421 * Invoke request handling on this queue, if it has pending work to do.
422 * May be used to restart queueing when a request has completed.
424 void blk_run_queue(struct request_queue *q)
428 spin_lock_irqsave(q->queue_lock, flags);
430 spin_unlock_irqrestore(q->queue_lock, flags);
432 EXPORT_SYMBOL(blk_run_queue);
434 void blk_put_queue(struct request_queue *q)
436 kobject_put(&q->kobj);
438 EXPORT_SYMBOL(blk_put_queue);
441 * __blk_drain_queue - drain requests from request_queue
443 * @drain_all: whether to drain all requests or only the ones w/ ELVPRIV
445 * Drain requests from @q. If @drain_all is set, all requests are drained.
446 * If not, only ELVPRIV requests are drained. The caller is responsible
447 * for ensuring that no new requests which need to be drained are queued.
449 static void __blk_drain_queue(struct request_queue *q, bool drain_all)
450 __releases(q->queue_lock)
451 __acquires(q->queue_lock)
455 lockdep_assert_held(q->queue_lock);
461 * The caller might be trying to drain @q before its
462 * elevator is initialized.
465 elv_drain_elevator(q);
467 blkcg_drain_queue(q);
470 * This function might be called on a queue which failed
471 * driver init after queue creation or is not yet fully
472 * active yet. Some drivers (e.g. fd and loop) get unhappy
473 * in such cases. Kick queue iff dispatch queue has
474 * something on it and @q has request_fn set.
476 if (!list_empty(&q->queue_head) && q->request_fn)
479 drain |= q->nr_rqs_elvpriv;
480 drain |= q->request_fn_active;
483 * Unfortunately, requests are queued at and tracked from
484 * multiple places and there's no single counter which can
485 * be drained. Check all the queues and counters.
488 struct blk_flush_queue *fq = blk_get_flush_queue(q, NULL);
489 drain |= !list_empty(&q->queue_head);
490 for (i = 0; i < 2; i++) {
491 drain |= q->nr_rqs[i];
492 drain |= q->in_flight[i];
494 drain |= !list_empty(&fq->flush_queue[i]);
501 spin_unlock_irq(q->queue_lock);
505 spin_lock_irq(q->queue_lock);
509 * With queue marked dead, any woken up waiter will fail the
510 * allocation path, so the wakeup chaining is lost and we're
511 * left with hung waiters. We need to wake up those waiters.
514 struct request_list *rl;
516 blk_queue_for_each_rl(rl, q)
517 for (i = 0; i < ARRAY_SIZE(rl->wait); i++)
518 wake_up_all(&rl->wait[i]);
523 * blk_queue_bypass_start - enter queue bypass mode
524 * @q: queue of interest
526 * In bypass mode, only the dispatch FIFO queue of @q is used. This
527 * function makes @q enter bypass mode and drains all requests which were
528 * throttled or issued before. On return, it's guaranteed that no request
529 * is being throttled or has ELVPRIV set and blk_queue_bypass() %true
530 * inside queue or RCU read lock.
532 void blk_queue_bypass_start(struct request_queue *q)
534 spin_lock_irq(q->queue_lock);
536 queue_flag_set(QUEUE_FLAG_BYPASS, q);
537 spin_unlock_irq(q->queue_lock);
540 * Queues start drained. Skip actual draining till init is
541 * complete. This avoids lenghty delays during queue init which
542 * can happen many times during boot.
544 if (blk_queue_init_done(q)) {
545 spin_lock_irq(q->queue_lock);
546 __blk_drain_queue(q, false);
547 spin_unlock_irq(q->queue_lock);
549 /* ensure blk_queue_bypass() is %true inside RCU read lock */
553 EXPORT_SYMBOL_GPL(blk_queue_bypass_start);
556 * blk_queue_bypass_end - leave queue bypass mode
557 * @q: queue of interest
559 * Leave bypass mode and restore the normal queueing behavior.
561 void blk_queue_bypass_end(struct request_queue *q)
563 spin_lock_irq(q->queue_lock);
564 if (!--q->bypass_depth)
565 queue_flag_clear(QUEUE_FLAG_BYPASS, q);
566 WARN_ON_ONCE(q->bypass_depth < 0);
567 spin_unlock_irq(q->queue_lock);
569 EXPORT_SYMBOL_GPL(blk_queue_bypass_end);
571 void blk_set_queue_dying(struct request_queue *q)
573 spin_lock_irq(q->queue_lock);
574 queue_flag_set(QUEUE_FLAG_DYING, q);
575 spin_unlock_irq(q->queue_lock);
578 * When queue DYING flag is set, we need to block new req
579 * entering queue, so we call blk_freeze_queue_start() to
580 * prevent I/O from crossing blk_queue_enter().
582 blk_freeze_queue_start(q);
585 blk_mq_wake_waiters(q);
587 struct request_list *rl;
589 spin_lock_irq(q->queue_lock);
590 blk_queue_for_each_rl(rl, q) {
592 wake_up(&rl->wait[BLK_RW_SYNC]);
593 wake_up(&rl->wait[BLK_RW_ASYNC]);
596 spin_unlock_irq(q->queue_lock);
599 EXPORT_SYMBOL_GPL(blk_set_queue_dying);
602 * blk_cleanup_queue - shutdown a request queue
603 * @q: request queue to shutdown
605 * Mark @q DYING, drain all pending requests, mark @q DEAD, destroy and
606 * put it. All future requests will be failed immediately with -ENODEV.
608 void blk_cleanup_queue(struct request_queue *q)
610 spinlock_t *lock = q->queue_lock;
612 /* mark @q DYING, no new request or merges will be allowed afterwards */
613 mutex_lock(&q->sysfs_lock);
614 blk_set_queue_dying(q);
618 * A dying queue is permanently in bypass mode till released. Note
619 * that, unlike blk_queue_bypass_start(), we aren't performing
620 * synchronize_rcu() after entering bypass mode to avoid the delay
621 * as some drivers create and destroy a lot of queues while
622 * probing. This is still safe because blk_release_queue() will be
623 * called only after the queue refcnt drops to zero and nothing,
624 * RCU or not, would be traversing the queue by then.
627 queue_flag_set(QUEUE_FLAG_BYPASS, q);
629 queue_flag_set(QUEUE_FLAG_NOMERGES, q);
630 queue_flag_set(QUEUE_FLAG_NOXMERGES, q);
631 queue_flag_set(QUEUE_FLAG_DYING, q);
632 spin_unlock_irq(lock);
633 mutex_unlock(&q->sysfs_lock);
636 * Drain all requests queued before DYING marking. Set DEAD flag to
637 * prevent that q->request_fn() gets invoked after draining finished.
642 __blk_drain_queue(q, true);
643 queue_flag_set(QUEUE_FLAG_DEAD, q);
644 spin_unlock_irq(lock);
646 /* for synchronous bio-based driver finish in-flight integrity i/o */
647 blk_flush_integrity();
649 /* @q won't process any more request, flush async actions */
650 del_timer_sync(&q->backing_dev_info->laptop_mode_wb_timer);
654 blk_mq_free_queue(q);
655 percpu_ref_exit(&q->q_usage_counter);
658 if (q->queue_lock != &q->__queue_lock)
659 q->queue_lock = &q->__queue_lock;
660 spin_unlock_irq(lock);
662 /* @q is and will stay empty, shutdown and put */
665 EXPORT_SYMBOL(blk_cleanup_queue);
667 /* Allocate memory local to the request queue */
668 static void *alloc_request_simple(gfp_t gfp_mask, void *data)
670 struct request_queue *q = data;
672 return kmem_cache_alloc_node(request_cachep, gfp_mask, q->node);
675 static void free_request_simple(void *element, void *data)
677 kmem_cache_free(request_cachep, element);
680 static void *alloc_request_size(gfp_t gfp_mask, void *data)
682 struct request_queue *q = data;
685 rq = kmalloc_node(sizeof(struct request) + q->cmd_size, gfp_mask,
687 if (rq && q->init_rq_fn && q->init_rq_fn(q, rq, gfp_mask) < 0) {
694 static void free_request_size(void *element, void *data)
696 struct request_queue *q = data;
699 q->exit_rq_fn(q, element);
703 int blk_init_rl(struct request_list *rl, struct request_queue *q,
706 if (unlikely(rl->rq_pool))
710 rl->count[BLK_RW_SYNC] = rl->count[BLK_RW_ASYNC] = 0;
711 rl->starved[BLK_RW_SYNC] = rl->starved[BLK_RW_ASYNC] = 0;
712 init_waitqueue_head(&rl->wait[BLK_RW_SYNC]);
713 init_waitqueue_head(&rl->wait[BLK_RW_ASYNC]);
716 rl->rq_pool = mempool_create_node(BLKDEV_MIN_RQ,
717 alloc_request_size, free_request_size,
718 q, gfp_mask, q->node);
720 rl->rq_pool = mempool_create_node(BLKDEV_MIN_RQ,
721 alloc_request_simple, free_request_simple,
722 q, gfp_mask, q->node);
727 if (rl != &q->root_rl)
728 WARN_ON_ONCE(!blk_get_queue(q));
733 void blk_exit_rl(struct request_queue *q, struct request_list *rl)
736 mempool_destroy(rl->rq_pool);
737 if (rl != &q->root_rl)
742 struct request_queue *blk_alloc_queue(gfp_t gfp_mask)
744 return blk_alloc_queue_node(gfp_mask, NUMA_NO_NODE);
746 EXPORT_SYMBOL(blk_alloc_queue);
748 int blk_queue_enter(struct request_queue *q, bool nowait)
753 if (percpu_ref_tryget_live(&q->q_usage_counter))
760 * read pair of barrier in blk_freeze_queue_start(),
761 * we need to order reading __PERCPU_REF_DEAD flag of
762 * .q_usage_counter and reading .mq_freeze_depth or
763 * queue dying flag, otherwise the following wait may
764 * never return if the two reads are reordered.
768 ret = wait_event_interruptible(q->mq_freeze_wq,
769 !atomic_read(&q->mq_freeze_depth) ||
771 if (blk_queue_dying(q))
778 void blk_queue_exit(struct request_queue *q)
780 percpu_ref_put(&q->q_usage_counter);
783 static void blk_queue_usage_counter_release(struct percpu_ref *ref)
785 struct request_queue *q =
786 container_of(ref, struct request_queue, q_usage_counter);
788 wake_up_all(&q->mq_freeze_wq);
791 static void blk_rq_timed_out_timer(unsigned long data)
793 struct request_queue *q = (struct request_queue *)data;
795 kblockd_schedule_work(&q->timeout_work);
798 struct request_queue *blk_alloc_queue_node(gfp_t gfp_mask, int node_id)
800 struct request_queue *q;
802 q = kmem_cache_alloc_node(blk_requestq_cachep,
803 gfp_mask | __GFP_ZERO, node_id);
807 q->id = ida_simple_get(&blk_queue_ida, 0, 0, gfp_mask);
811 q->bio_split = bioset_create(BIO_POOL_SIZE, 0, BIOSET_NEED_BVECS);
815 q->backing_dev_info = bdi_alloc_node(gfp_mask, node_id);
816 if (!q->backing_dev_info)
819 q->stats = blk_alloc_queue_stats();
823 q->backing_dev_info->ra_pages =
824 (VM_MAX_READAHEAD * 1024) / PAGE_SIZE;
825 q->backing_dev_info->capabilities = BDI_CAP_CGROUP_WRITEBACK;
826 q->backing_dev_info->name = "block";
829 setup_timer(&q->backing_dev_info->laptop_mode_wb_timer,
830 laptop_mode_timer_fn, (unsigned long) q);
831 setup_timer(&q->timeout, blk_rq_timed_out_timer, (unsigned long) q);
832 INIT_LIST_HEAD(&q->queue_head);
833 INIT_LIST_HEAD(&q->timeout_list);
834 INIT_LIST_HEAD(&q->icq_list);
835 #ifdef CONFIG_BLK_CGROUP
836 INIT_LIST_HEAD(&q->blkg_list);
838 INIT_DELAYED_WORK(&q->delay_work, blk_delay_work);
840 kobject_init(&q->kobj, &blk_queue_ktype);
842 mutex_init(&q->sysfs_lock);
843 spin_lock_init(&q->__queue_lock);
846 * By default initialize queue_lock to internal lock and driver can
847 * override it later if need be.
849 q->queue_lock = &q->__queue_lock;
852 * A queue starts its life with bypass turned on to avoid
853 * unnecessary bypass on/off overhead and nasty surprises during
854 * init. The initial bypass will be finished when the queue is
855 * registered by blk_register_queue().
858 __set_bit(QUEUE_FLAG_BYPASS, &q->queue_flags);
860 init_waitqueue_head(&q->mq_freeze_wq);
863 * Init percpu_ref in atomic mode so that it's faster to shutdown.
864 * See blk_register_queue() for details.
866 if (percpu_ref_init(&q->q_usage_counter,
867 blk_queue_usage_counter_release,
868 PERCPU_REF_INIT_ATOMIC, GFP_KERNEL))
871 if (blkcg_init_queue(q))
877 percpu_ref_exit(&q->q_usage_counter);
879 blk_free_queue_stats(q->stats);
881 bdi_put(q->backing_dev_info);
883 bioset_free(q->bio_split);
885 ida_simple_remove(&blk_queue_ida, q->id);
887 kmem_cache_free(blk_requestq_cachep, q);
890 EXPORT_SYMBOL(blk_alloc_queue_node);
893 * blk_init_queue - prepare a request queue for use with a block device
894 * @rfn: The function to be called to process requests that have been
895 * placed on the queue.
896 * @lock: Request queue spin lock
899 * If a block device wishes to use the standard request handling procedures,
900 * which sorts requests and coalesces adjacent requests, then it must
901 * call blk_init_queue(). The function @rfn will be called when there
902 * are requests on the queue that need to be processed. If the device
903 * supports plugging, then @rfn may not be called immediately when requests
904 * are available on the queue, but may be called at some time later instead.
905 * Plugged queues are generally unplugged when a buffer belonging to one
906 * of the requests on the queue is needed, or due to memory pressure.
908 * @rfn is not required, or even expected, to remove all requests off the
909 * queue, but only as many as it can handle at a time. If it does leave
910 * requests on the queue, it is responsible for arranging that the requests
911 * get dealt with eventually.
913 * The queue spin lock must be held while manipulating the requests on the
914 * request queue; this lock will be taken also from interrupt context, so irq
915 * disabling is needed for it.
917 * Function returns a pointer to the initialized request queue, or %NULL if
921 * blk_init_queue() must be paired with a blk_cleanup_queue() call
922 * when the block device is deactivated (such as at module unload).
925 struct request_queue *blk_init_queue(request_fn_proc *rfn, spinlock_t *lock)
927 return blk_init_queue_node(rfn, lock, NUMA_NO_NODE);
929 EXPORT_SYMBOL(blk_init_queue);
931 struct request_queue *
932 blk_init_queue_node(request_fn_proc *rfn, spinlock_t *lock, int node_id)
934 struct request_queue *q;
936 q = blk_alloc_queue_node(GFP_KERNEL, node_id);
942 q->queue_lock = lock;
943 if (blk_init_allocated_queue(q) < 0) {
944 blk_cleanup_queue(q);
950 EXPORT_SYMBOL(blk_init_queue_node);
952 static blk_qc_t blk_queue_bio(struct request_queue *q, struct bio *bio);
955 int blk_init_allocated_queue(struct request_queue *q)
957 q->fq = blk_alloc_flush_queue(q, NUMA_NO_NODE, q->cmd_size);
961 if (q->init_rq_fn && q->init_rq_fn(q, q->fq->flush_rq, GFP_KERNEL))
962 goto out_free_flush_queue;
964 if (blk_init_rl(&q->root_rl, q, GFP_KERNEL))
965 goto out_exit_flush_rq;
967 INIT_WORK(&q->timeout_work, blk_timeout_work);
968 q->queue_flags |= QUEUE_FLAG_DEFAULT;
971 * This also sets hw/phys segments, boundary and size
973 blk_queue_make_request(q, blk_queue_bio);
975 q->sg_reserved_size = INT_MAX;
977 /* Protect q->elevator from elevator_change */
978 mutex_lock(&q->sysfs_lock);
981 if (elevator_init(q, NULL)) {
982 mutex_unlock(&q->sysfs_lock);
983 goto out_exit_flush_rq;
986 mutex_unlock(&q->sysfs_lock);
991 q->exit_rq_fn(q, q->fq->flush_rq);
992 out_free_flush_queue:
993 blk_free_flush_queue(q->fq);
996 EXPORT_SYMBOL(blk_init_allocated_queue);
998 bool blk_get_queue(struct request_queue *q)
1000 if (likely(!blk_queue_dying(q))) {
1007 EXPORT_SYMBOL(blk_get_queue);
1009 static inline void blk_free_request(struct request_list *rl, struct request *rq)
1011 if (rq->rq_flags & RQF_ELVPRIV) {
1012 elv_put_request(rl->q, rq);
1014 put_io_context(rq->elv.icq->ioc);
1017 mempool_free(rq, rl->rq_pool);
1021 * ioc_batching returns true if the ioc is a valid batching request and
1022 * should be given priority access to a request.
1024 static inline int ioc_batching(struct request_queue *q, struct io_context *ioc)
1030 * Make sure the process is able to allocate at least 1 request
1031 * even if the batch times out, otherwise we could theoretically
1034 return ioc->nr_batch_requests == q->nr_batching ||
1035 (ioc->nr_batch_requests > 0
1036 && time_before(jiffies, ioc->last_waited + BLK_BATCH_TIME));
1040 * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
1041 * will cause the process to be a "batcher" on all queues in the system. This
1042 * is the behaviour we want though - once it gets a wakeup it should be given
1045 static void ioc_set_batching(struct request_queue *q, struct io_context *ioc)
1047 if (!ioc || ioc_batching(q, ioc))
1050 ioc->nr_batch_requests = q->nr_batching;
1051 ioc->last_waited = jiffies;
1054 static void __freed_request(struct request_list *rl, int sync)
1056 struct request_queue *q = rl->q;
1058 if (rl->count[sync] < queue_congestion_off_threshold(q))
1059 blk_clear_congested(rl, sync);
1061 if (rl->count[sync] + 1 <= q->nr_requests) {
1062 if (waitqueue_active(&rl->wait[sync]))
1063 wake_up(&rl->wait[sync]);
1065 blk_clear_rl_full(rl, sync);
1070 * A request has just been released. Account for it, update the full and
1071 * congestion status, wake up any waiters. Called under q->queue_lock.
1073 static void freed_request(struct request_list *rl, bool sync,
1074 req_flags_t rq_flags)
1076 struct request_queue *q = rl->q;
1080 if (rq_flags & RQF_ELVPRIV)
1081 q->nr_rqs_elvpriv--;
1083 __freed_request(rl, sync);
1085 if (unlikely(rl->starved[sync ^ 1]))
1086 __freed_request(rl, sync ^ 1);
1089 int blk_update_nr_requests(struct request_queue *q, unsigned int nr)
1091 struct request_list *rl;
1092 int on_thresh, off_thresh;
1094 spin_lock_irq(q->queue_lock);
1095 q->nr_requests = nr;
1096 blk_queue_congestion_threshold(q);
1097 on_thresh = queue_congestion_on_threshold(q);
1098 off_thresh = queue_congestion_off_threshold(q);
1100 blk_queue_for_each_rl(rl, q) {
1101 if (rl->count[BLK_RW_SYNC] >= on_thresh)
1102 blk_set_congested(rl, BLK_RW_SYNC);
1103 else if (rl->count[BLK_RW_SYNC] < off_thresh)
1104 blk_clear_congested(rl, BLK_RW_SYNC);
1106 if (rl->count[BLK_RW_ASYNC] >= on_thresh)
1107 blk_set_congested(rl, BLK_RW_ASYNC);
1108 else if (rl->count[BLK_RW_ASYNC] < off_thresh)
1109 blk_clear_congested(rl, BLK_RW_ASYNC);
1111 if (rl->count[BLK_RW_SYNC] >= q->nr_requests) {
1112 blk_set_rl_full(rl, BLK_RW_SYNC);
1114 blk_clear_rl_full(rl, BLK_RW_SYNC);
1115 wake_up(&rl->wait[BLK_RW_SYNC]);
1118 if (rl->count[BLK_RW_ASYNC] >= q->nr_requests) {
1119 blk_set_rl_full(rl, BLK_RW_ASYNC);
1121 blk_clear_rl_full(rl, BLK_RW_ASYNC);
1122 wake_up(&rl->wait[BLK_RW_ASYNC]);
1126 spin_unlock_irq(q->queue_lock);
1131 * __get_request - get a free request
1132 * @rl: request list to allocate from
1133 * @op: operation and flags
1134 * @bio: bio to allocate request for (can be %NULL)
1135 * @gfp_mask: allocation mask
1137 * Get a free request from @q. This function may fail under memory
1138 * pressure or if @q is dead.
1140 * Must be called with @q->queue_lock held and,
1141 * Returns ERR_PTR on failure, with @q->queue_lock held.
1142 * Returns request pointer on success, with @q->queue_lock *not held*.
1144 static struct request *__get_request(struct request_list *rl, unsigned int op,
1145 struct bio *bio, gfp_t gfp_mask)
1147 struct request_queue *q = rl->q;
1149 struct elevator_type *et = q->elevator->type;
1150 struct io_context *ioc = rq_ioc(bio);
1151 struct io_cq *icq = NULL;
1152 const bool is_sync = op_is_sync(op);
1154 req_flags_t rq_flags = RQF_ALLOCED;
1156 lockdep_assert_held(q->queue_lock);
1158 if (unlikely(blk_queue_dying(q)))
1159 return ERR_PTR(-ENODEV);
1161 may_queue = elv_may_queue(q, op);
1162 if (may_queue == ELV_MQUEUE_NO)
1165 if (rl->count[is_sync]+1 >= queue_congestion_on_threshold(q)) {
1166 if (rl->count[is_sync]+1 >= q->nr_requests) {
1168 * The queue will fill after this allocation, so set
1169 * it as full, and mark this process as "batching".
1170 * This process will be allowed to complete a batch of
1171 * requests, others will be blocked.
1173 if (!blk_rl_full(rl, is_sync)) {
1174 ioc_set_batching(q, ioc);
1175 blk_set_rl_full(rl, is_sync);
1177 if (may_queue != ELV_MQUEUE_MUST
1178 && !ioc_batching(q, ioc)) {
1180 * The queue is full and the allocating
1181 * process is not a "batcher", and not
1182 * exempted by the IO scheduler
1184 return ERR_PTR(-ENOMEM);
1188 blk_set_congested(rl, is_sync);
1192 * Only allow batching queuers to allocate up to 50% over the defined
1193 * limit of requests, otherwise we could have thousands of requests
1194 * allocated with any setting of ->nr_requests
1196 if (rl->count[is_sync] >= (3 * q->nr_requests / 2))
1197 return ERR_PTR(-ENOMEM);
1199 q->nr_rqs[is_sync]++;
1200 rl->count[is_sync]++;
1201 rl->starved[is_sync] = 0;
1204 * Decide whether the new request will be managed by elevator. If
1205 * so, mark @rq_flags and increment elvpriv. Non-zero elvpriv will
1206 * prevent the current elevator from being destroyed until the new
1207 * request is freed. This guarantees icq's won't be destroyed and
1208 * makes creating new ones safe.
1210 * Flush requests do not use the elevator so skip initialization.
1211 * This allows a request to share the flush and elevator data.
1213 * Also, lookup icq while holding queue_lock. If it doesn't exist,
1214 * it will be created after releasing queue_lock.
1216 if (!op_is_flush(op) && !blk_queue_bypass(q)) {
1217 rq_flags |= RQF_ELVPRIV;
1218 q->nr_rqs_elvpriv++;
1219 if (et->icq_cache && ioc)
1220 icq = ioc_lookup_icq(ioc, q);
1223 if (blk_queue_io_stat(q))
1224 rq_flags |= RQF_IO_STAT;
1225 spin_unlock_irq(q->queue_lock);
1227 /* allocate and init request */
1228 rq = mempool_alloc(rl->rq_pool, gfp_mask);
1233 blk_rq_set_rl(rq, rl);
1235 rq->rq_flags = rq_flags;
1238 if (rq_flags & RQF_ELVPRIV) {
1239 if (unlikely(et->icq_cache && !icq)) {
1241 icq = ioc_create_icq(ioc, q, gfp_mask);
1247 if (unlikely(elv_set_request(q, rq, bio, gfp_mask)))
1250 /* @rq->elv.icq holds io_context until @rq is freed */
1252 get_io_context(icq->ioc);
1256 * ioc may be NULL here, and ioc_batching will be false. That's
1257 * OK, if the queue is under the request limit then requests need
1258 * not count toward the nr_batch_requests limit. There will always
1259 * be some limit enforced by BLK_BATCH_TIME.
1261 if (ioc_batching(q, ioc))
1262 ioc->nr_batch_requests--;
1264 trace_block_getrq(q, bio, op);
1269 * elvpriv init failed. ioc, icq and elvpriv aren't mempool backed
1270 * and may fail indefinitely under memory pressure and thus
1271 * shouldn't stall IO. Treat this request as !elvpriv. This will
1272 * disturb iosched and blkcg but weird is bettern than dead.
1274 printk_ratelimited(KERN_WARNING "%s: dev %s: request aux data allocation failed, iosched may be disturbed\n",
1275 __func__, dev_name(q->backing_dev_info->dev));
1277 rq->rq_flags &= ~RQF_ELVPRIV;
1280 spin_lock_irq(q->queue_lock);
1281 q->nr_rqs_elvpriv--;
1282 spin_unlock_irq(q->queue_lock);
1287 * Allocation failed presumably due to memory. Undo anything we
1288 * might have messed up.
1290 * Allocating task should really be put onto the front of the wait
1291 * queue, but this is pretty rare.
1293 spin_lock_irq(q->queue_lock);
1294 freed_request(rl, is_sync, rq_flags);
1297 * in the very unlikely event that allocation failed and no
1298 * requests for this direction was pending, mark us starved so that
1299 * freeing of a request in the other direction will notice
1300 * us. another possible fix would be to split the rq mempool into
1304 if (unlikely(rl->count[is_sync] == 0))
1305 rl->starved[is_sync] = 1;
1306 return ERR_PTR(-ENOMEM);
1310 * get_request - get a free request
1311 * @q: request_queue to allocate request from
1312 * @op: operation and flags
1313 * @bio: bio to allocate request for (can be %NULL)
1314 * @gfp_mask: allocation mask
1316 * Get a free request from @q. If %__GFP_DIRECT_RECLAIM is set in @gfp_mask,
1317 * this function keeps retrying under memory pressure and fails iff @q is dead.
1319 * Must be called with @q->queue_lock held and,
1320 * Returns ERR_PTR on failure, with @q->queue_lock held.
1321 * Returns request pointer on success, with @q->queue_lock *not held*.
1323 static struct request *get_request(struct request_queue *q, unsigned int op,
1324 struct bio *bio, gfp_t gfp_mask)
1326 const bool is_sync = op_is_sync(op);
1328 struct request_list *rl;
1331 lockdep_assert_held(q->queue_lock);
1333 rl = blk_get_rl(q, bio); /* transferred to @rq on success */
1335 rq = __get_request(rl, op, bio, gfp_mask);
1339 if (op & REQ_NOWAIT) {
1341 return ERR_PTR(-EAGAIN);
1344 if (!gfpflags_allow_blocking(gfp_mask) || unlikely(blk_queue_dying(q))) {
1349 /* wait on @rl and retry */
1350 prepare_to_wait_exclusive(&rl->wait[is_sync], &wait,
1351 TASK_UNINTERRUPTIBLE);
1353 trace_block_sleeprq(q, bio, op);
1355 spin_unlock_irq(q->queue_lock);
1359 * After sleeping, we become a "batching" process and will be able
1360 * to allocate at least one request, and up to a big batch of them
1361 * for a small period time. See ioc_batching, ioc_set_batching
1363 ioc_set_batching(q, current->io_context);
1365 spin_lock_irq(q->queue_lock);
1366 finish_wait(&rl->wait[is_sync], &wait);
1371 static struct request *blk_old_get_request(struct request_queue *q,
1372 unsigned int op, gfp_t gfp_mask)
1376 /* create ioc upfront */
1377 create_io_context(gfp_mask, q->node);
1379 spin_lock_irq(q->queue_lock);
1380 rq = get_request(q, op, NULL, gfp_mask);
1382 spin_unlock_irq(q->queue_lock);
1386 /* q->queue_lock is unlocked at this point */
1388 rq->__sector = (sector_t) -1;
1389 rq->bio = rq->biotail = NULL;
1393 struct request *blk_get_request(struct request_queue *q, unsigned int op,
1396 struct request *req;
1399 req = blk_mq_alloc_request(q, op,
1400 (gfp_mask & __GFP_DIRECT_RECLAIM) ?
1401 0 : BLK_MQ_REQ_NOWAIT);
1402 if (!IS_ERR(req) && q->mq_ops->initialize_rq_fn)
1403 q->mq_ops->initialize_rq_fn(req);
1405 req = blk_old_get_request(q, op, gfp_mask);
1406 if (!IS_ERR(req) && q->initialize_rq_fn)
1407 q->initialize_rq_fn(req);
1412 EXPORT_SYMBOL(blk_get_request);
1415 * blk_requeue_request - put a request back on queue
1416 * @q: request queue where request should be inserted
1417 * @rq: request to be inserted
1420 * Drivers often keep queueing requests until the hardware cannot accept
1421 * more, when that condition happens we need to put the request back
1422 * on the queue. Must be called with queue lock held.
1424 void blk_requeue_request(struct request_queue *q, struct request *rq)
1426 lockdep_assert_held(q->queue_lock);
1428 blk_delete_timer(rq);
1429 blk_clear_rq_complete(rq);
1430 trace_block_rq_requeue(q, rq);
1431 wbt_requeue(q->rq_wb, &rq->issue_stat);
1433 if (rq->rq_flags & RQF_QUEUED)
1434 blk_queue_end_tag(q, rq);
1436 BUG_ON(blk_queued_rq(rq));
1438 elv_requeue_request(q, rq);
1440 EXPORT_SYMBOL(blk_requeue_request);
1442 static void add_acct_request(struct request_queue *q, struct request *rq,
1445 blk_account_io_start(rq, true);
1446 __elv_add_request(q, rq, where);
1449 static void part_round_stats_single(int cpu, struct hd_struct *part,
1454 if (now == part->stamp)
1457 inflight = part_in_flight(part);
1459 __part_stat_add(cpu, part, time_in_queue,
1460 inflight * (now - part->stamp));
1461 __part_stat_add(cpu, part, io_ticks, (now - part->stamp));
1467 * part_round_stats() - Round off the performance stats on a struct disk_stats.
1468 * @cpu: cpu number for stats access
1469 * @part: target partition
1471 * The average IO queue length and utilisation statistics are maintained
1472 * by observing the current state of the queue length and the amount of
1473 * time it has been in this state for.
1475 * Normally, that accounting is done on IO completion, but that can result
1476 * in more than a second's worth of IO being accounted for within any one
1477 * second, leading to >100% utilisation. To deal with that, we call this
1478 * function to do a round-off before returning the results when reading
1479 * /proc/diskstats. This accounts immediately for all queue usage up to
1480 * the current jiffies and restarts the counters again.
1482 void part_round_stats(int cpu, struct hd_struct *part)
1484 unsigned long now = jiffies;
1487 part_round_stats_single(cpu, &part_to_disk(part)->part0, now);
1488 part_round_stats_single(cpu, part, now);
1490 EXPORT_SYMBOL_GPL(part_round_stats);
1493 static void blk_pm_put_request(struct request *rq)
1495 if (rq->q->dev && !(rq->rq_flags & RQF_PM) && !--rq->q->nr_pending)
1496 pm_runtime_mark_last_busy(rq->q->dev);
1499 static inline void blk_pm_put_request(struct request *rq) {}
1502 void __blk_put_request(struct request_queue *q, struct request *req)
1504 req_flags_t rq_flags = req->rq_flags;
1510 blk_mq_free_request(req);
1514 lockdep_assert_held(q->queue_lock);
1516 blk_pm_put_request(req);
1518 elv_completed_request(q, req);
1520 /* this is a bio leak */
1521 WARN_ON(req->bio != NULL);
1523 wbt_done(q->rq_wb, &req->issue_stat);
1526 * Request may not have originated from ll_rw_blk. if not,
1527 * it didn't come out of our reserved rq pools
1529 if (rq_flags & RQF_ALLOCED) {
1530 struct request_list *rl = blk_rq_rl(req);
1531 bool sync = op_is_sync(req->cmd_flags);
1533 BUG_ON(!list_empty(&req->queuelist));
1534 BUG_ON(ELV_ON_HASH(req));
1536 blk_free_request(rl, req);
1537 freed_request(rl, sync, rq_flags);
1541 EXPORT_SYMBOL_GPL(__blk_put_request);
1543 void blk_put_request(struct request *req)
1545 struct request_queue *q = req->q;
1548 blk_mq_free_request(req);
1550 unsigned long flags;
1552 spin_lock_irqsave(q->queue_lock, flags);
1553 __blk_put_request(q, req);
1554 spin_unlock_irqrestore(q->queue_lock, flags);
1557 EXPORT_SYMBOL(blk_put_request);
1559 bool bio_attempt_back_merge(struct request_queue *q, struct request *req,
1562 const int ff = bio->bi_opf & REQ_FAILFAST_MASK;
1564 if (!ll_back_merge_fn(q, req, bio))
1567 trace_block_bio_backmerge(q, req, bio);
1569 if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
1570 blk_rq_set_mixed_merge(req);
1572 req->biotail->bi_next = bio;
1574 req->__data_len += bio->bi_iter.bi_size;
1575 req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
1577 blk_account_io_start(req, false);
1581 bool bio_attempt_front_merge(struct request_queue *q, struct request *req,
1584 const int ff = bio->bi_opf & REQ_FAILFAST_MASK;
1586 if (!ll_front_merge_fn(q, req, bio))
1589 trace_block_bio_frontmerge(q, req, bio);
1591 if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
1592 blk_rq_set_mixed_merge(req);
1594 bio->bi_next = req->bio;
1597 req->__sector = bio->bi_iter.bi_sector;
1598 req->__data_len += bio->bi_iter.bi_size;
1599 req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
1601 blk_account_io_start(req, false);
1605 bool bio_attempt_discard_merge(struct request_queue *q, struct request *req,
1608 unsigned short segments = blk_rq_nr_discard_segments(req);
1610 if (segments >= queue_max_discard_segments(q))
1612 if (blk_rq_sectors(req) + bio_sectors(bio) >
1613 blk_rq_get_max_sectors(req, blk_rq_pos(req)))
1616 req->biotail->bi_next = bio;
1618 req->__data_len += bio->bi_iter.bi_size;
1619 req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
1620 req->nr_phys_segments = segments + 1;
1622 blk_account_io_start(req, false);
1625 req_set_nomerge(q, req);
1630 * blk_attempt_plug_merge - try to merge with %current's plugged list
1631 * @q: request_queue new bio is being queued at
1632 * @bio: new bio being queued
1633 * @request_count: out parameter for number of traversed plugged requests
1634 * @same_queue_rq: pointer to &struct request that gets filled in when
1635 * another request associated with @q is found on the plug list
1636 * (optional, may be %NULL)
1638 * Determine whether @bio being queued on @q can be merged with a request
1639 * on %current's plugged list. Returns %true if merge was successful,
1642 * Plugging coalesces IOs from the same issuer for the same purpose without
1643 * going through @q->queue_lock. As such it's more of an issuing mechanism
1644 * than scheduling, and the request, while may have elvpriv data, is not
1645 * added on the elevator at this point. In addition, we don't have
1646 * reliable access to the elevator outside queue lock. Only check basic
1647 * merging parameters without querying the elevator.
1649 * Caller must ensure !blk_queue_nomerges(q) beforehand.
1651 bool blk_attempt_plug_merge(struct request_queue *q, struct bio *bio,
1652 unsigned int *request_count,
1653 struct request **same_queue_rq)
1655 struct blk_plug *plug;
1657 struct list_head *plug_list;
1659 plug = current->plug;
1665 plug_list = &plug->mq_list;
1667 plug_list = &plug->list;
1669 list_for_each_entry_reverse(rq, plug_list, queuelist) {
1670 bool merged = false;
1675 * Only blk-mq multiple hardware queues case checks the
1676 * rq in the same queue, there should be only one such
1680 *same_queue_rq = rq;
1683 if (rq->q != q || !blk_rq_merge_ok(rq, bio))
1686 switch (blk_try_merge(rq, bio)) {
1687 case ELEVATOR_BACK_MERGE:
1688 merged = bio_attempt_back_merge(q, rq, bio);
1690 case ELEVATOR_FRONT_MERGE:
1691 merged = bio_attempt_front_merge(q, rq, bio);
1693 case ELEVATOR_DISCARD_MERGE:
1694 merged = bio_attempt_discard_merge(q, rq, bio);
1707 unsigned int blk_plug_queued_count(struct request_queue *q)
1709 struct blk_plug *plug;
1711 struct list_head *plug_list;
1712 unsigned int ret = 0;
1714 plug = current->plug;
1719 plug_list = &plug->mq_list;
1721 plug_list = &plug->list;
1723 list_for_each_entry(rq, plug_list, queuelist) {
1731 void blk_init_request_from_bio(struct request *req, struct bio *bio)
1733 struct io_context *ioc = rq_ioc(bio);
1735 if (bio->bi_opf & REQ_RAHEAD)
1736 req->cmd_flags |= REQ_FAILFAST_MASK;
1738 req->__sector = bio->bi_iter.bi_sector;
1739 if (ioprio_valid(bio_prio(bio)))
1740 req->ioprio = bio_prio(bio);
1742 req->ioprio = ioc->ioprio;
1744 req->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE, 0);
1745 blk_rq_bio_prep(req->q, req, bio);
1747 EXPORT_SYMBOL_GPL(blk_init_request_from_bio);
1749 static blk_qc_t blk_queue_bio(struct request_queue *q, struct bio *bio)
1751 struct blk_plug *plug;
1752 int where = ELEVATOR_INSERT_SORT;
1753 struct request *req, *free;
1754 unsigned int request_count = 0;
1755 unsigned int wb_acct;
1758 * low level driver can indicate that it wants pages above a
1759 * certain limit bounced to low memory (ie for highmem, or even
1760 * ISA dma in theory)
1762 blk_queue_bounce(q, &bio);
1764 blk_queue_split(q, &bio);
1766 if (bio_integrity_enabled(bio) && bio_integrity_prep(bio)) {
1767 bio->bi_status = BLK_STS_IOERR;
1769 return BLK_QC_T_NONE;
1772 if (op_is_flush(bio->bi_opf)) {
1773 spin_lock_irq(q->queue_lock);
1774 where = ELEVATOR_INSERT_FLUSH;
1779 * Check if we can merge with the plugged list before grabbing
1782 if (!blk_queue_nomerges(q)) {
1783 if (blk_attempt_plug_merge(q, bio, &request_count, NULL))
1784 return BLK_QC_T_NONE;
1786 request_count = blk_plug_queued_count(q);
1788 spin_lock_irq(q->queue_lock);
1790 switch (elv_merge(q, &req, bio)) {
1791 case ELEVATOR_BACK_MERGE:
1792 if (!bio_attempt_back_merge(q, req, bio))
1794 elv_bio_merged(q, req, bio);
1795 free = attempt_back_merge(q, req);
1797 __blk_put_request(q, free);
1799 elv_merged_request(q, req, ELEVATOR_BACK_MERGE);
1801 case ELEVATOR_FRONT_MERGE:
1802 if (!bio_attempt_front_merge(q, req, bio))
1804 elv_bio_merged(q, req, bio);
1805 free = attempt_front_merge(q, req);
1807 __blk_put_request(q, free);
1809 elv_merged_request(q, req, ELEVATOR_FRONT_MERGE);
1816 wb_acct = wbt_wait(q->rq_wb, bio, q->queue_lock);
1819 * Grab a free request. This is might sleep but can not fail.
1820 * Returns with the queue unlocked.
1822 req = get_request(q, bio->bi_opf, bio, GFP_NOIO);
1824 __wbt_done(q->rq_wb, wb_acct);
1825 if (PTR_ERR(req) == -ENOMEM)
1826 bio->bi_status = BLK_STS_RESOURCE;
1828 bio->bi_status = BLK_STS_IOERR;
1833 wbt_track(&req->issue_stat, wb_acct);
1836 * After dropping the lock and possibly sleeping here, our request
1837 * may now be mergeable after it had proven unmergeable (above).
1838 * We don't worry about that case for efficiency. It won't happen
1839 * often, and the elevators are able to handle it.
1841 blk_init_request_from_bio(req, bio);
1843 if (test_bit(QUEUE_FLAG_SAME_COMP, &q->queue_flags))
1844 req->cpu = raw_smp_processor_id();
1846 plug = current->plug;
1849 * If this is the first request added after a plug, fire
1852 * @request_count may become stale because of schedule
1853 * out, so check plug list again.
1855 if (!request_count || list_empty(&plug->list))
1856 trace_block_plug(q);
1858 struct request *last = list_entry_rq(plug->list.prev);
1859 if (request_count >= BLK_MAX_REQUEST_COUNT ||
1860 blk_rq_bytes(last) >= BLK_PLUG_FLUSH_SIZE) {
1861 blk_flush_plug_list(plug, false);
1862 trace_block_plug(q);
1865 list_add_tail(&req->queuelist, &plug->list);
1866 blk_account_io_start(req, true);
1868 spin_lock_irq(q->queue_lock);
1869 add_acct_request(q, req, where);
1872 spin_unlock_irq(q->queue_lock);
1875 return BLK_QC_T_NONE;
1879 * If bio->bi_dev is a partition, remap the location
1881 static inline void blk_partition_remap(struct bio *bio)
1883 struct block_device *bdev = bio->bi_bdev;
1886 * Zone reset does not include bi_size so bio_sectors() is always 0.
1887 * Include a test for the reset op code and perform the remap if needed.
1889 if (bdev != bdev->bd_contains &&
1890 (bio_sectors(bio) || bio_op(bio) == REQ_OP_ZONE_RESET)) {
1891 struct hd_struct *p = bdev->bd_part;
1893 bio->bi_iter.bi_sector += p->start_sect;
1894 bio->bi_bdev = bdev->bd_contains;
1896 trace_block_bio_remap(bdev_get_queue(bio->bi_bdev), bio,
1898 bio->bi_iter.bi_sector - p->start_sect);
1902 static void handle_bad_sector(struct bio *bio)
1904 char b[BDEVNAME_SIZE];
1906 printk(KERN_INFO "attempt to access beyond end of device\n");
1907 printk(KERN_INFO "%s: rw=%d, want=%Lu, limit=%Lu\n",
1908 bdevname(bio->bi_bdev, b),
1910 (unsigned long long)bio_end_sector(bio),
1911 (long long)(i_size_read(bio->bi_bdev->bd_inode) >> 9));
1914 #ifdef CONFIG_FAIL_MAKE_REQUEST
1916 static DECLARE_FAULT_ATTR(fail_make_request);
1918 static int __init setup_fail_make_request(char *str)
1920 return setup_fault_attr(&fail_make_request, str);
1922 __setup("fail_make_request=", setup_fail_make_request);
1924 static bool should_fail_request(struct hd_struct *part, unsigned int bytes)
1926 return part->make_it_fail && should_fail(&fail_make_request, bytes);
1929 static int __init fail_make_request_debugfs(void)
1931 struct dentry *dir = fault_create_debugfs_attr("fail_make_request",
1932 NULL, &fail_make_request);
1934 return PTR_ERR_OR_ZERO(dir);
1937 late_initcall(fail_make_request_debugfs);
1939 #else /* CONFIG_FAIL_MAKE_REQUEST */
1941 static inline bool should_fail_request(struct hd_struct *part,
1947 #endif /* CONFIG_FAIL_MAKE_REQUEST */
1950 * Check whether this bio extends beyond the end of the device.
1952 static inline int bio_check_eod(struct bio *bio, unsigned int nr_sectors)
1959 /* Test device or partition size, when known. */
1960 maxsector = i_size_read(bio->bi_bdev->bd_inode) >> 9;
1962 sector_t sector = bio->bi_iter.bi_sector;
1964 if (maxsector < nr_sectors || maxsector - nr_sectors < sector) {
1966 * This may well happen - the kernel calls bread()
1967 * without checking the size of the device, e.g., when
1968 * mounting a device.
1970 handle_bad_sector(bio);
1978 static noinline_for_stack bool
1979 generic_make_request_checks(struct bio *bio)
1981 struct request_queue *q;
1982 int nr_sectors = bio_sectors(bio);
1983 blk_status_t status = BLK_STS_IOERR;
1984 char b[BDEVNAME_SIZE];
1985 struct hd_struct *part;
1989 if (bio_check_eod(bio, nr_sectors))
1992 q = bdev_get_queue(bio->bi_bdev);
1995 "generic_make_request: Trying to access "
1996 "nonexistent block-device %s (%Lu)\n",
1997 bdevname(bio->bi_bdev, b),
1998 (long long) bio->bi_iter.bi_sector);
2003 * For a REQ_NOWAIT based request, return -EOPNOTSUPP
2004 * if queue is not a request based queue.
2007 if ((bio->bi_opf & REQ_NOWAIT) && !queue_is_rq_based(q))
2010 part = bio->bi_bdev->bd_part;
2011 if (should_fail_request(part, bio->bi_iter.bi_size) ||
2012 should_fail_request(&part_to_disk(part)->part0,
2013 bio->bi_iter.bi_size))
2017 * If this device has partitions, remap block n
2018 * of partition p to block n+start(p) of the disk.
2020 blk_partition_remap(bio);
2022 if (bio_check_eod(bio, nr_sectors))
2026 * Filter flush bio's early so that make_request based
2027 * drivers without flush support don't have to worry
2030 if (op_is_flush(bio->bi_opf) &&
2031 !test_bit(QUEUE_FLAG_WC, &q->queue_flags)) {
2032 bio->bi_opf &= ~(REQ_PREFLUSH | REQ_FUA);
2034 status = BLK_STS_OK;
2039 switch (bio_op(bio)) {
2040 case REQ_OP_DISCARD:
2041 if (!blk_queue_discard(q))
2044 case REQ_OP_SECURE_ERASE:
2045 if (!blk_queue_secure_erase(q))
2048 case REQ_OP_WRITE_SAME:
2049 if (!bdev_write_same(bio->bi_bdev))
2052 case REQ_OP_ZONE_REPORT:
2053 case REQ_OP_ZONE_RESET:
2054 if (!bdev_is_zoned(bio->bi_bdev))
2057 case REQ_OP_WRITE_ZEROES:
2058 if (!bdev_write_zeroes_sectors(bio->bi_bdev))
2066 * Various block parts want %current->io_context and lazy ioc
2067 * allocation ends up trading a lot of pain for a small amount of
2068 * memory. Just allocate it upfront. This may fail and block
2069 * layer knows how to live with it.
2071 create_io_context(GFP_ATOMIC, q->node);
2073 if (!blkcg_bio_issue_check(q, bio))
2076 if (!bio_flagged(bio, BIO_TRACE_COMPLETION)) {
2077 trace_block_bio_queue(q, bio);
2078 /* Now that enqueuing has been traced, we need to trace
2079 * completion as well.
2081 bio_set_flag(bio, BIO_TRACE_COMPLETION);
2086 status = BLK_STS_NOTSUPP;
2088 bio->bi_status = status;
2094 * generic_make_request - hand a buffer to its device driver for I/O
2095 * @bio: The bio describing the location in memory and on the device.
2097 * generic_make_request() is used to make I/O requests of block
2098 * devices. It is passed a &struct bio, which describes the I/O that needs
2101 * generic_make_request() does not return any status. The
2102 * success/failure status of the request, along with notification of
2103 * completion, is delivered asynchronously through the bio->bi_end_io
2104 * function described (one day) else where.
2106 * The caller of generic_make_request must make sure that bi_io_vec
2107 * are set to describe the memory buffer, and that bi_dev and bi_sector are
2108 * set to describe the device address, and the
2109 * bi_end_io and optionally bi_private are set to describe how
2110 * completion notification should be signaled.
2112 * generic_make_request and the drivers it calls may use bi_next if this
2113 * bio happens to be merged with someone else, and may resubmit the bio to
2114 * a lower device by calling into generic_make_request recursively, which
2115 * means the bio should NOT be touched after the call to ->make_request_fn.
2117 blk_qc_t generic_make_request(struct bio *bio)
2120 * bio_list_on_stack[0] contains bios submitted by the current
2122 * bio_list_on_stack[1] contains bios that were submitted before
2123 * the current make_request_fn, but that haven't been processed
2126 struct bio_list bio_list_on_stack[2];
2127 blk_qc_t ret = BLK_QC_T_NONE;
2129 if (!generic_make_request_checks(bio))
2133 * We only want one ->make_request_fn to be active at a time, else
2134 * stack usage with stacked devices could be a problem. So use
2135 * current->bio_list to keep a list of requests submited by a
2136 * make_request_fn function. current->bio_list is also used as a
2137 * flag to say if generic_make_request is currently active in this
2138 * task or not. If it is NULL, then no make_request is active. If
2139 * it is non-NULL, then a make_request is active, and new requests
2140 * should be added at the tail
2142 if (current->bio_list) {
2143 bio_list_add(¤t->bio_list[0], bio);
2147 /* following loop may be a bit non-obvious, and so deserves some
2149 * Before entering the loop, bio->bi_next is NULL (as all callers
2150 * ensure that) so we have a list with a single bio.
2151 * We pretend that we have just taken it off a longer list, so
2152 * we assign bio_list to a pointer to the bio_list_on_stack,
2153 * thus initialising the bio_list of new bios to be
2154 * added. ->make_request() may indeed add some more bios
2155 * through a recursive call to generic_make_request. If it
2156 * did, we find a non-NULL value in bio_list and re-enter the loop
2157 * from the top. In this case we really did just take the bio
2158 * of the top of the list (no pretending) and so remove it from
2159 * bio_list, and call into ->make_request() again.
2161 BUG_ON(bio->bi_next);
2162 bio_list_init(&bio_list_on_stack[0]);
2163 current->bio_list = bio_list_on_stack;
2165 struct request_queue *q = bdev_get_queue(bio->bi_bdev);
2167 if (likely(blk_queue_enter(q, bio->bi_opf & REQ_NOWAIT) == 0)) {
2168 struct bio_list lower, same;
2170 /* Create a fresh bio_list for all subordinate requests */
2171 bio_list_on_stack[1] = bio_list_on_stack[0];
2172 bio_list_init(&bio_list_on_stack[0]);
2173 ret = q->make_request_fn(q, bio);
2177 /* sort new bios into those for a lower level
2178 * and those for the same level
2180 bio_list_init(&lower);
2181 bio_list_init(&same);
2182 while ((bio = bio_list_pop(&bio_list_on_stack[0])) != NULL)
2183 if (q == bdev_get_queue(bio->bi_bdev))
2184 bio_list_add(&same, bio);
2186 bio_list_add(&lower, bio);
2187 /* now assemble so we handle the lowest level first */
2188 bio_list_merge(&bio_list_on_stack[0], &lower);
2189 bio_list_merge(&bio_list_on_stack[0], &same);
2190 bio_list_merge(&bio_list_on_stack[0], &bio_list_on_stack[1]);
2192 if (unlikely(!blk_queue_dying(q) &&
2193 (bio->bi_opf & REQ_NOWAIT)))
2194 bio_wouldblock_error(bio);
2198 bio = bio_list_pop(&bio_list_on_stack[0]);
2200 current->bio_list = NULL; /* deactivate */
2205 EXPORT_SYMBOL(generic_make_request);
2208 * submit_bio - submit a bio to the block device layer for I/O
2209 * @bio: The &struct bio which describes the I/O
2211 * submit_bio() is very similar in purpose to generic_make_request(), and
2212 * uses that function to do most of the work. Both are fairly rough
2213 * interfaces; @bio must be presetup and ready for I/O.
2216 blk_qc_t submit_bio(struct bio *bio)
2219 * If it's a regular read/write or a barrier with data attached,
2220 * go through the normal accounting stuff before submission.
2222 if (bio_has_data(bio)) {
2225 if (unlikely(bio_op(bio) == REQ_OP_WRITE_SAME))
2226 count = bdev_logical_block_size(bio->bi_bdev) >> 9;
2228 count = bio_sectors(bio);
2230 if (op_is_write(bio_op(bio))) {
2231 count_vm_events(PGPGOUT, count);
2233 task_io_account_read(bio->bi_iter.bi_size);
2234 count_vm_events(PGPGIN, count);
2237 if (unlikely(block_dump)) {
2238 char b[BDEVNAME_SIZE];
2239 printk(KERN_DEBUG "%s(%d): %s block %Lu on %s (%u sectors)\n",
2240 current->comm, task_pid_nr(current),
2241 op_is_write(bio_op(bio)) ? "WRITE" : "READ",
2242 (unsigned long long)bio->bi_iter.bi_sector,
2243 bdevname(bio->bi_bdev, b),
2248 return generic_make_request(bio);
2250 EXPORT_SYMBOL(submit_bio);
2253 * blk_cloned_rq_check_limits - Helper function to check a cloned request
2254 * for new the queue limits
2256 * @rq: the request being checked
2259 * @rq may have been made based on weaker limitations of upper-level queues
2260 * in request stacking drivers, and it may violate the limitation of @q.
2261 * Since the block layer and the underlying device driver trust @rq
2262 * after it is inserted to @q, it should be checked against @q before
2263 * the insertion using this generic function.
2265 * Request stacking drivers like request-based dm may change the queue
2266 * limits when retrying requests on other queues. Those requests need
2267 * to be checked against the new queue limits again during dispatch.
2269 static int blk_cloned_rq_check_limits(struct request_queue *q,
2272 if (blk_rq_sectors(rq) > blk_queue_get_max_sectors(q, req_op(rq))) {
2273 printk(KERN_ERR "%s: over max size limit.\n", __func__);
2278 * queue's settings related to segment counting like q->bounce_pfn
2279 * may differ from that of other stacking queues.
2280 * Recalculate it to check the request correctly on this queue's
2283 blk_recalc_rq_segments(rq);
2284 if (rq->nr_phys_segments > queue_max_segments(q)) {
2285 printk(KERN_ERR "%s: over max segments limit.\n", __func__);
2293 * blk_insert_cloned_request - Helper for stacking drivers to submit a request
2294 * @q: the queue to submit the request
2295 * @rq: the request being queued
2297 blk_status_t blk_insert_cloned_request(struct request_queue *q, struct request *rq)
2299 unsigned long flags;
2300 int where = ELEVATOR_INSERT_BACK;
2302 if (blk_cloned_rq_check_limits(q, rq))
2303 return BLK_STS_IOERR;
2306 should_fail_request(&rq->rq_disk->part0, blk_rq_bytes(rq)))
2307 return BLK_STS_IOERR;
2310 if (blk_queue_io_stat(q))
2311 blk_account_io_start(rq, true);
2312 blk_mq_sched_insert_request(rq, false, true, false, false);
2316 spin_lock_irqsave(q->queue_lock, flags);
2317 if (unlikely(blk_queue_dying(q))) {
2318 spin_unlock_irqrestore(q->queue_lock, flags);
2319 return BLK_STS_IOERR;
2323 * Submitting request must be dequeued before calling this function
2324 * because it will be linked to another request_queue
2326 BUG_ON(blk_queued_rq(rq));
2328 if (op_is_flush(rq->cmd_flags))
2329 where = ELEVATOR_INSERT_FLUSH;
2331 add_acct_request(q, rq, where);
2332 if (where == ELEVATOR_INSERT_FLUSH)
2334 spin_unlock_irqrestore(q->queue_lock, flags);
2338 EXPORT_SYMBOL_GPL(blk_insert_cloned_request);
2341 * blk_rq_err_bytes - determine number of bytes till the next failure boundary
2342 * @rq: request to examine
2345 * A request could be merge of IOs which require different failure
2346 * handling. This function determines the number of bytes which
2347 * can be failed from the beginning of the request without
2348 * crossing into area which need to be retried further.
2351 * The number of bytes to fail.
2353 unsigned int blk_rq_err_bytes(const struct request *rq)
2355 unsigned int ff = rq->cmd_flags & REQ_FAILFAST_MASK;
2356 unsigned int bytes = 0;
2359 if (!(rq->rq_flags & RQF_MIXED_MERGE))
2360 return blk_rq_bytes(rq);
2363 * Currently the only 'mixing' which can happen is between
2364 * different fastfail types. We can safely fail portions
2365 * which have all the failfast bits that the first one has -
2366 * the ones which are at least as eager to fail as the first
2369 for (bio = rq->bio; bio; bio = bio->bi_next) {
2370 if ((bio->bi_opf & ff) != ff)
2372 bytes += bio->bi_iter.bi_size;
2375 /* this could lead to infinite loop */
2376 BUG_ON(blk_rq_bytes(rq) && !bytes);
2379 EXPORT_SYMBOL_GPL(blk_rq_err_bytes);
2381 void blk_account_io_completion(struct request *req, unsigned int bytes)
2383 if (blk_do_io_stat(req)) {
2384 const int rw = rq_data_dir(req);
2385 struct hd_struct *part;
2388 cpu = part_stat_lock();
2390 part_stat_add(cpu, part, sectors[rw], bytes >> 9);
2395 void blk_account_io_done(struct request *req)
2398 * Account IO completion. flush_rq isn't accounted as a
2399 * normal IO on queueing nor completion. Accounting the
2400 * containing request is enough.
2402 if (blk_do_io_stat(req) && !(req->rq_flags & RQF_FLUSH_SEQ)) {
2403 unsigned long duration = jiffies - req->start_time;
2404 const int rw = rq_data_dir(req);
2405 struct hd_struct *part;
2408 cpu = part_stat_lock();
2411 part_stat_inc(cpu, part, ios[rw]);
2412 part_stat_add(cpu, part, ticks[rw], duration);
2413 part_round_stats(cpu, part);
2414 part_dec_in_flight(part, rw);
2416 hd_struct_put(part);
2423 * Don't process normal requests when queue is suspended
2424 * or in the process of suspending/resuming
2426 static struct request *blk_pm_peek_request(struct request_queue *q,
2429 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
2430 (q->rpm_status != RPM_ACTIVE && !(rq->rq_flags & RQF_PM))))
2436 static inline struct request *blk_pm_peek_request(struct request_queue *q,
2443 void blk_account_io_start(struct request *rq, bool new_io)
2445 struct hd_struct *part;
2446 int rw = rq_data_dir(rq);
2449 if (!blk_do_io_stat(rq))
2452 cpu = part_stat_lock();
2456 part_stat_inc(cpu, part, merges[rw]);
2458 part = disk_map_sector_rcu(rq->rq_disk, blk_rq_pos(rq));
2459 if (!hd_struct_try_get(part)) {
2461 * The partition is already being removed,
2462 * the request will be accounted on the disk only
2464 * We take a reference on disk->part0 although that
2465 * partition will never be deleted, so we can treat
2466 * it as any other partition.
2468 part = &rq->rq_disk->part0;
2469 hd_struct_get(part);
2471 part_round_stats(cpu, part);
2472 part_inc_in_flight(part, rw);
2480 * blk_peek_request - peek at the top of a request queue
2481 * @q: request queue to peek at
2484 * Return the request at the top of @q. The returned request
2485 * should be started using blk_start_request() before LLD starts
2489 * Pointer to the request at the top of @q if available. Null
2492 struct request *blk_peek_request(struct request_queue *q)
2497 lockdep_assert_held(q->queue_lock);
2499 while ((rq = __elv_next_request(q)) != NULL) {
2501 rq = blk_pm_peek_request(q, rq);
2505 if (!(rq->rq_flags & RQF_STARTED)) {
2507 * This is the first time the device driver
2508 * sees this request (possibly after
2509 * requeueing). Notify IO scheduler.
2511 if (rq->rq_flags & RQF_SORTED)
2512 elv_activate_rq(q, rq);
2515 * just mark as started even if we don't start
2516 * it, a request that has been delayed should
2517 * not be passed by new incoming requests
2519 rq->rq_flags |= RQF_STARTED;
2520 trace_block_rq_issue(q, rq);
2523 if (!q->boundary_rq || q->boundary_rq == rq) {
2524 q->end_sector = rq_end_sector(rq);
2525 q->boundary_rq = NULL;
2528 if (rq->rq_flags & RQF_DONTPREP)
2531 if (q->dma_drain_size && blk_rq_bytes(rq)) {
2533 * make sure space for the drain appears we
2534 * know we can do this because max_hw_segments
2535 * has been adjusted to be one fewer than the
2538 rq->nr_phys_segments++;
2544 ret = q->prep_rq_fn(q, rq);
2545 if (ret == BLKPREP_OK) {
2547 } else if (ret == BLKPREP_DEFER) {
2549 * the request may have been (partially) prepped.
2550 * we need to keep this request in the front to
2551 * avoid resource deadlock. RQF_STARTED will
2552 * prevent other fs requests from passing this one.
2554 if (q->dma_drain_size && blk_rq_bytes(rq) &&
2555 !(rq->rq_flags & RQF_DONTPREP)) {
2557 * remove the space for the drain we added
2558 * so that we don't add it again
2560 --rq->nr_phys_segments;
2565 } else if (ret == BLKPREP_KILL || ret == BLKPREP_INVALID) {
2566 rq->rq_flags |= RQF_QUIET;
2568 * Mark this request as started so we don't trigger
2569 * any debug logic in the end I/O path.
2571 blk_start_request(rq);
2572 __blk_end_request_all(rq, ret == BLKPREP_INVALID ?
2573 BLK_STS_TARGET : BLK_STS_IOERR);
2575 printk(KERN_ERR "%s: bad return=%d\n", __func__, ret);
2582 EXPORT_SYMBOL(blk_peek_request);
2584 void blk_dequeue_request(struct request *rq)
2586 struct request_queue *q = rq->q;
2588 BUG_ON(list_empty(&rq->queuelist));
2589 BUG_ON(ELV_ON_HASH(rq));
2591 list_del_init(&rq->queuelist);
2594 * the time frame between a request being removed from the lists
2595 * and to it is freed is accounted as io that is in progress at
2598 if (blk_account_rq(rq)) {
2599 q->in_flight[rq_is_sync(rq)]++;
2600 set_io_start_time_ns(rq);
2605 * blk_start_request - start request processing on the driver
2606 * @req: request to dequeue
2609 * Dequeue @req and start timeout timer on it. This hands off the
2610 * request to the driver.
2612 * Block internal functions which don't want to start timer should
2613 * call blk_dequeue_request().
2615 void blk_start_request(struct request *req)
2617 lockdep_assert_held(req->q->queue_lock);
2619 blk_dequeue_request(req);
2621 if (test_bit(QUEUE_FLAG_STATS, &req->q->queue_flags)) {
2622 blk_stat_set_issue(&req->issue_stat, blk_rq_sectors(req));
2623 req->rq_flags |= RQF_STATS;
2624 wbt_issue(req->q->rq_wb, &req->issue_stat);
2627 BUG_ON(test_bit(REQ_ATOM_COMPLETE, &req->atomic_flags));
2630 EXPORT_SYMBOL(blk_start_request);
2633 * blk_fetch_request - fetch a request from a request queue
2634 * @q: request queue to fetch a request from
2637 * Return the request at the top of @q. The request is started on
2638 * return and LLD can start processing it immediately.
2641 * Pointer to the request at the top of @q if available. Null
2644 struct request *blk_fetch_request(struct request_queue *q)
2648 lockdep_assert_held(q->queue_lock);
2650 rq = blk_peek_request(q);
2652 blk_start_request(rq);
2655 EXPORT_SYMBOL(blk_fetch_request);
2658 * blk_update_request - Special helper function for request stacking drivers
2659 * @req: the request being processed
2660 * @error: block status code
2661 * @nr_bytes: number of bytes to complete @req
2664 * Ends I/O on a number of bytes attached to @req, but doesn't complete
2665 * the request structure even if @req doesn't have leftover.
2666 * If @req has leftover, sets it up for the next range of segments.
2668 * This special helper function is only for request stacking drivers
2669 * (e.g. request-based dm) so that they can handle partial completion.
2670 * Actual device drivers should use blk_end_request instead.
2672 * Passing the result of blk_rq_bytes() as @nr_bytes guarantees
2673 * %false return from this function.
2676 * %false - this request doesn't have any more data
2677 * %true - this request has more data
2679 bool blk_update_request(struct request *req, blk_status_t error,
2680 unsigned int nr_bytes)
2684 trace_block_rq_complete(req, blk_status_to_errno(error), nr_bytes);
2689 if (unlikely(error && !blk_rq_is_passthrough(req) &&
2690 !(req->rq_flags & RQF_QUIET)))
2691 print_req_error(req, error);
2693 blk_account_io_completion(req, nr_bytes);
2697 struct bio *bio = req->bio;
2698 unsigned bio_bytes = min(bio->bi_iter.bi_size, nr_bytes);
2700 if (bio_bytes == bio->bi_iter.bi_size)
2701 req->bio = bio->bi_next;
2703 /* Completion has already been traced */
2704 bio_clear_flag(bio, BIO_TRACE_COMPLETION);
2705 req_bio_endio(req, bio, bio_bytes, error);
2707 total_bytes += bio_bytes;
2708 nr_bytes -= bio_bytes;
2719 * Reset counters so that the request stacking driver
2720 * can find how many bytes remain in the request
2723 req->__data_len = 0;
2727 req->__data_len -= total_bytes;
2729 /* update sector only for requests with clear definition of sector */
2730 if (!blk_rq_is_passthrough(req))
2731 req->__sector += total_bytes >> 9;
2733 /* mixed attributes always follow the first bio */
2734 if (req->rq_flags & RQF_MIXED_MERGE) {
2735 req->cmd_flags &= ~REQ_FAILFAST_MASK;
2736 req->cmd_flags |= req->bio->bi_opf & REQ_FAILFAST_MASK;
2739 if (!(req->rq_flags & RQF_SPECIAL_PAYLOAD)) {
2741 * If total number of sectors is less than the first segment
2742 * size, something has gone terribly wrong.
2744 if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {
2745 blk_dump_rq_flags(req, "request botched");
2746 req->__data_len = blk_rq_cur_bytes(req);
2749 /* recalculate the number of segments */
2750 blk_recalc_rq_segments(req);
2755 EXPORT_SYMBOL_GPL(blk_update_request);
2757 static bool blk_update_bidi_request(struct request *rq, blk_status_t error,
2758 unsigned int nr_bytes,
2759 unsigned int bidi_bytes)
2761 if (blk_update_request(rq, error, nr_bytes))
2764 /* Bidi request must be completed as a whole */
2765 if (unlikely(blk_bidi_rq(rq)) &&
2766 blk_update_request(rq->next_rq, error, bidi_bytes))
2769 if (blk_queue_add_random(rq->q))
2770 add_disk_randomness(rq->rq_disk);
2776 * blk_unprep_request - unprepare a request
2779 * This function makes a request ready for complete resubmission (or
2780 * completion). It happens only after all error handling is complete,
2781 * so represents the appropriate moment to deallocate any resources
2782 * that were allocated to the request in the prep_rq_fn. The queue
2783 * lock is held when calling this.
2785 void blk_unprep_request(struct request *req)
2787 struct request_queue *q = req->q;
2789 req->rq_flags &= ~RQF_DONTPREP;
2790 if (q->unprep_rq_fn)
2791 q->unprep_rq_fn(q, req);
2793 EXPORT_SYMBOL_GPL(blk_unprep_request);
2795 void blk_finish_request(struct request *req, blk_status_t error)
2797 struct request_queue *q = req->q;
2799 lockdep_assert_held(req->q->queue_lock);
2801 if (req->rq_flags & RQF_STATS)
2804 if (req->rq_flags & RQF_QUEUED)
2805 blk_queue_end_tag(q, req);
2807 BUG_ON(blk_queued_rq(req));
2809 if (unlikely(laptop_mode) && !blk_rq_is_passthrough(req))
2810 laptop_io_completion(req->q->backing_dev_info);
2812 blk_delete_timer(req);
2814 if (req->rq_flags & RQF_DONTPREP)
2815 blk_unprep_request(req);
2817 blk_account_io_done(req);
2820 wbt_done(req->q->rq_wb, &req->issue_stat);
2821 req->end_io(req, error);
2823 if (blk_bidi_rq(req))
2824 __blk_put_request(req->next_rq->q, req->next_rq);
2826 __blk_put_request(q, req);
2829 EXPORT_SYMBOL(blk_finish_request);
2832 * blk_end_bidi_request - Complete a bidi request
2833 * @rq: the request to complete
2834 * @error: block status code
2835 * @nr_bytes: number of bytes to complete @rq
2836 * @bidi_bytes: number of bytes to complete @rq->next_rq
2839 * Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
2840 * Drivers that supports bidi can safely call this member for any
2841 * type of request, bidi or uni. In the later case @bidi_bytes is
2845 * %false - we are done with this request
2846 * %true - still buffers pending for this request
2848 static bool blk_end_bidi_request(struct request *rq, blk_status_t error,
2849 unsigned int nr_bytes, unsigned int bidi_bytes)
2851 struct request_queue *q = rq->q;
2852 unsigned long flags;
2854 if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2857 spin_lock_irqsave(q->queue_lock, flags);
2858 blk_finish_request(rq, error);
2859 spin_unlock_irqrestore(q->queue_lock, flags);
2865 * __blk_end_bidi_request - Complete a bidi request with queue lock held
2866 * @rq: the request to complete
2867 * @error: block status code
2868 * @nr_bytes: number of bytes to complete @rq
2869 * @bidi_bytes: number of bytes to complete @rq->next_rq
2872 * Identical to blk_end_bidi_request() except that queue lock is
2873 * assumed to be locked on entry and remains so on return.
2876 * %false - we are done with this request
2877 * %true - still buffers pending for this request
2879 static bool __blk_end_bidi_request(struct request *rq, blk_status_t error,
2880 unsigned int nr_bytes, unsigned int bidi_bytes)
2882 lockdep_assert_held(rq->q->queue_lock);
2884 if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2887 blk_finish_request(rq, error);
2893 * blk_end_request - Helper function for drivers to complete the request.
2894 * @rq: the request being processed
2895 * @error: block status code
2896 * @nr_bytes: number of bytes to complete
2899 * Ends I/O on a number of bytes attached to @rq.
2900 * If @rq has leftover, sets it up for the next range of segments.
2903 * %false - we are done with this request
2904 * %true - still buffers pending for this request
2906 bool blk_end_request(struct request *rq, blk_status_t error,
2907 unsigned int nr_bytes)
2909 return blk_end_bidi_request(rq, error, nr_bytes, 0);
2911 EXPORT_SYMBOL(blk_end_request);
2914 * blk_end_request_all - Helper function for drives to finish the request.
2915 * @rq: the request to finish
2916 * @error: block status code
2919 * Completely finish @rq.
2921 void blk_end_request_all(struct request *rq, blk_status_t error)
2924 unsigned int bidi_bytes = 0;
2926 if (unlikely(blk_bidi_rq(rq)))
2927 bidi_bytes = blk_rq_bytes(rq->next_rq);
2929 pending = blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2932 EXPORT_SYMBOL(blk_end_request_all);
2935 * __blk_end_request - Helper function for drivers to complete the request.
2936 * @rq: the request being processed
2937 * @error: block status code
2938 * @nr_bytes: number of bytes to complete
2941 * Must be called with queue lock held unlike blk_end_request().
2944 * %false - we are done with this request
2945 * %true - still buffers pending for this request
2947 bool __blk_end_request(struct request *rq, blk_status_t error,
2948 unsigned int nr_bytes)
2950 lockdep_assert_held(rq->q->queue_lock);
2952 return __blk_end_bidi_request(rq, error, nr_bytes, 0);
2954 EXPORT_SYMBOL(__blk_end_request);
2957 * __blk_end_request_all - Helper function for drives to finish the request.
2958 * @rq: the request to finish
2959 * @error: block status code
2962 * Completely finish @rq. Must be called with queue lock held.
2964 void __blk_end_request_all(struct request *rq, blk_status_t error)
2967 unsigned int bidi_bytes = 0;
2969 lockdep_assert_held(rq->q->queue_lock);
2971 if (unlikely(blk_bidi_rq(rq)))
2972 bidi_bytes = blk_rq_bytes(rq->next_rq);
2974 pending = __blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2977 EXPORT_SYMBOL(__blk_end_request_all);
2980 * __blk_end_request_cur - Helper function to finish the current request chunk.
2981 * @rq: the request to finish the current chunk for
2982 * @error: block status code
2985 * Complete the current consecutively mapped chunk from @rq. Must
2986 * be called with queue lock held.
2989 * %false - we are done with this request
2990 * %true - still buffers pending for this request
2992 bool __blk_end_request_cur(struct request *rq, blk_status_t error)
2994 return __blk_end_request(rq, error, blk_rq_cur_bytes(rq));
2996 EXPORT_SYMBOL(__blk_end_request_cur);
2998 void blk_rq_bio_prep(struct request_queue *q, struct request *rq,
3001 if (bio_has_data(bio))
3002 rq->nr_phys_segments = bio_phys_segments(q, bio);
3004 rq->__data_len = bio->bi_iter.bi_size;
3005 rq->bio = rq->biotail = bio;
3008 rq->rq_disk = bio->bi_bdev->bd_disk;
3011 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE
3013 * rq_flush_dcache_pages - Helper function to flush all pages in a request
3014 * @rq: the request to be flushed
3017 * Flush all pages in @rq.
3019 void rq_flush_dcache_pages(struct request *rq)
3021 struct req_iterator iter;
3022 struct bio_vec bvec;
3024 rq_for_each_segment(bvec, rq, iter)
3025 flush_dcache_page(bvec.bv_page);
3027 EXPORT_SYMBOL_GPL(rq_flush_dcache_pages);
3031 * blk_lld_busy - Check if underlying low-level drivers of a device are busy
3032 * @q : the queue of the device being checked
3035 * Check if underlying low-level drivers of a device are busy.
3036 * If the drivers want to export their busy state, they must set own
3037 * exporting function using blk_queue_lld_busy() first.
3039 * Basically, this function is used only by request stacking drivers
3040 * to stop dispatching requests to underlying devices when underlying
3041 * devices are busy. This behavior helps more I/O merging on the queue
3042 * of the request stacking driver and prevents I/O throughput regression
3043 * on burst I/O load.
3046 * 0 - Not busy (The request stacking driver should dispatch request)
3047 * 1 - Busy (The request stacking driver should stop dispatching request)
3049 int blk_lld_busy(struct request_queue *q)
3052 return q->lld_busy_fn(q);
3056 EXPORT_SYMBOL_GPL(blk_lld_busy);
3059 * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
3060 * @rq: the clone request to be cleaned up
3063 * Free all bios in @rq for a cloned request.
3065 void blk_rq_unprep_clone(struct request *rq)
3069 while ((bio = rq->bio) != NULL) {
3070 rq->bio = bio->bi_next;
3075 EXPORT_SYMBOL_GPL(blk_rq_unprep_clone);
3078 * Copy attributes of the original request to the clone request.
3079 * The actual data parts (e.g. ->cmd, ->sense) are not copied.
3081 static void __blk_rq_prep_clone(struct request *dst, struct request *src)
3083 dst->cpu = src->cpu;
3084 dst->__sector = blk_rq_pos(src);
3085 dst->__data_len = blk_rq_bytes(src);
3086 dst->nr_phys_segments = src->nr_phys_segments;
3087 dst->ioprio = src->ioprio;
3088 dst->extra_len = src->extra_len;
3092 * blk_rq_prep_clone - Helper function to setup clone request
3093 * @rq: the request to be setup
3094 * @rq_src: original request to be cloned
3095 * @bs: bio_set that bios for clone are allocated from
3096 * @gfp_mask: memory allocation mask for bio
3097 * @bio_ctr: setup function to be called for each clone bio.
3098 * Returns %0 for success, non %0 for failure.
3099 * @data: private data to be passed to @bio_ctr
3102 * Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
3103 * The actual data parts of @rq_src (e.g. ->cmd, ->sense)
3104 * are not copied, and copying such parts is the caller's responsibility.
3105 * Also, pages which the original bios are pointing to are not copied
3106 * and the cloned bios just point same pages.
3107 * So cloned bios must be completed before original bios, which means
3108 * the caller must complete @rq before @rq_src.
3110 int blk_rq_prep_clone(struct request *rq, struct request *rq_src,
3111 struct bio_set *bs, gfp_t gfp_mask,
3112 int (*bio_ctr)(struct bio *, struct bio *, void *),
3115 struct bio *bio, *bio_src;
3120 __rq_for_each_bio(bio_src, rq_src) {
3121 bio = bio_clone_fast(bio_src, gfp_mask, bs);
3125 if (bio_ctr && bio_ctr(bio, bio_src, data))
3129 rq->biotail->bi_next = bio;
3132 rq->bio = rq->biotail = bio;
3135 __blk_rq_prep_clone(rq, rq_src);
3142 blk_rq_unprep_clone(rq);
3146 EXPORT_SYMBOL_GPL(blk_rq_prep_clone);
3148 int kblockd_schedule_work(struct work_struct *work)
3150 return queue_work(kblockd_workqueue, work);
3152 EXPORT_SYMBOL(kblockd_schedule_work);
3154 int kblockd_schedule_work_on(int cpu, struct work_struct *work)
3156 return queue_work_on(cpu, kblockd_workqueue, work);
3158 EXPORT_SYMBOL(kblockd_schedule_work_on);
3160 int kblockd_mod_delayed_work_on(int cpu, struct delayed_work *dwork,
3161 unsigned long delay)
3163 return mod_delayed_work_on(cpu, kblockd_workqueue, dwork, delay);
3165 EXPORT_SYMBOL(kblockd_mod_delayed_work_on);
3167 int kblockd_schedule_delayed_work(struct delayed_work *dwork,
3168 unsigned long delay)
3170 return queue_delayed_work(kblockd_workqueue, dwork, delay);
3172 EXPORT_SYMBOL(kblockd_schedule_delayed_work);
3174 int kblockd_schedule_delayed_work_on(int cpu, struct delayed_work *dwork,
3175 unsigned long delay)
3177 return queue_delayed_work_on(cpu, kblockd_workqueue, dwork, delay);
3179 EXPORT_SYMBOL(kblockd_schedule_delayed_work_on);
3182 * blk_start_plug - initialize blk_plug and track it inside the task_struct
3183 * @plug: The &struct blk_plug that needs to be initialized
3186 * Tracking blk_plug inside the task_struct will help with auto-flushing the
3187 * pending I/O should the task end up blocking between blk_start_plug() and
3188 * blk_finish_plug(). This is important from a performance perspective, but
3189 * also ensures that we don't deadlock. For instance, if the task is blocking
3190 * for a memory allocation, memory reclaim could end up wanting to free a
3191 * page belonging to that request that is currently residing in our private
3192 * plug. By flushing the pending I/O when the process goes to sleep, we avoid
3193 * this kind of deadlock.
3195 void blk_start_plug(struct blk_plug *plug)
3197 struct task_struct *tsk = current;
3200 * If this is a nested plug, don't actually assign it.
3205 INIT_LIST_HEAD(&plug->list);
3206 INIT_LIST_HEAD(&plug->mq_list);
3207 INIT_LIST_HEAD(&plug->cb_list);
3209 * Store ordering should not be needed here, since a potential
3210 * preempt will imply a full memory barrier
3214 EXPORT_SYMBOL(blk_start_plug);
3216 static int plug_rq_cmp(void *priv, struct list_head *a, struct list_head *b)
3218 struct request *rqa = container_of(a, struct request, queuelist);
3219 struct request *rqb = container_of(b, struct request, queuelist);
3221 return !(rqa->q < rqb->q ||
3222 (rqa->q == rqb->q && blk_rq_pos(rqa) < blk_rq_pos(rqb)));
3226 * If 'from_schedule' is true, then postpone the dispatch of requests
3227 * until a safe kblockd context. We due this to avoid accidental big
3228 * additional stack usage in driver dispatch, in places where the originally
3229 * plugger did not intend it.
3231 static void queue_unplugged(struct request_queue *q, unsigned int depth,
3233 __releases(q->queue_lock)
3235 lockdep_assert_held(q->queue_lock);
3237 trace_block_unplug(q, depth, !from_schedule);
3240 blk_run_queue_async(q);
3243 spin_unlock(q->queue_lock);
3246 static void flush_plug_callbacks(struct blk_plug *plug, bool from_schedule)
3248 LIST_HEAD(callbacks);
3250 while (!list_empty(&plug->cb_list)) {
3251 list_splice_init(&plug->cb_list, &callbacks);
3253 while (!list_empty(&callbacks)) {
3254 struct blk_plug_cb *cb = list_first_entry(&callbacks,
3257 list_del(&cb->list);
3258 cb->callback(cb, from_schedule);
3263 struct blk_plug_cb *blk_check_plugged(blk_plug_cb_fn unplug, void *data,
3266 struct blk_plug *plug = current->plug;
3267 struct blk_plug_cb *cb;
3272 list_for_each_entry(cb, &plug->cb_list, list)
3273 if (cb->callback == unplug && cb->data == data)
3276 /* Not currently on the callback list */
3277 BUG_ON(size < sizeof(*cb));
3278 cb = kzalloc(size, GFP_ATOMIC);
3281 cb->callback = unplug;
3282 list_add(&cb->list, &plug->cb_list);
3286 EXPORT_SYMBOL(blk_check_plugged);
3288 void blk_flush_plug_list(struct blk_plug *plug, bool from_schedule)
3290 struct request_queue *q;
3291 unsigned long flags;
3296 flush_plug_callbacks(plug, from_schedule);
3298 if (!list_empty(&plug->mq_list))
3299 blk_mq_flush_plug_list(plug, from_schedule);
3301 if (list_empty(&plug->list))
3304 list_splice_init(&plug->list, &list);
3306 list_sort(NULL, &list, plug_rq_cmp);
3312 * Save and disable interrupts here, to avoid doing it for every
3313 * queue lock we have to take.
3315 local_irq_save(flags);
3316 while (!list_empty(&list)) {
3317 rq = list_entry_rq(list.next);
3318 list_del_init(&rq->queuelist);
3322 * This drops the queue lock
3325 queue_unplugged(q, depth, from_schedule);
3328 spin_lock(q->queue_lock);
3332 * Short-circuit if @q is dead
3334 if (unlikely(blk_queue_dying(q))) {
3335 __blk_end_request_all(rq, BLK_STS_IOERR);
3340 * rq is already accounted, so use raw insert
3342 if (op_is_flush(rq->cmd_flags))
3343 __elv_add_request(q, rq, ELEVATOR_INSERT_FLUSH);
3345 __elv_add_request(q, rq, ELEVATOR_INSERT_SORT_MERGE);
3351 * This drops the queue lock
3354 queue_unplugged(q, depth, from_schedule);
3356 local_irq_restore(flags);
3359 void blk_finish_plug(struct blk_plug *plug)
3361 if (plug != current->plug)
3363 blk_flush_plug_list(plug, false);
3365 current->plug = NULL;
3367 EXPORT_SYMBOL(blk_finish_plug);
3371 * blk_pm_runtime_init - Block layer runtime PM initialization routine
3372 * @q: the queue of the device
3373 * @dev: the device the queue belongs to
3376 * Initialize runtime-PM-related fields for @q and start auto suspend for
3377 * @dev. Drivers that want to take advantage of request-based runtime PM
3378 * should call this function after @dev has been initialized, and its
3379 * request queue @q has been allocated, and runtime PM for it can not happen
3380 * yet(either due to disabled/forbidden or its usage_count > 0). In most
3381 * cases, driver should call this function before any I/O has taken place.
3383 * This function takes care of setting up using auto suspend for the device,
3384 * the autosuspend delay is set to -1 to make runtime suspend impossible
3385 * until an updated value is either set by user or by driver. Drivers do
3386 * not need to touch other autosuspend settings.
3388 * The block layer runtime PM is request based, so only works for drivers
3389 * that use request as their IO unit instead of those directly use bio's.
3391 void blk_pm_runtime_init(struct request_queue *q, struct device *dev)
3394 q->rpm_status = RPM_ACTIVE;
3395 pm_runtime_set_autosuspend_delay(q->dev, -1);
3396 pm_runtime_use_autosuspend(q->dev);
3398 EXPORT_SYMBOL(blk_pm_runtime_init);
3401 * blk_pre_runtime_suspend - Pre runtime suspend check
3402 * @q: the queue of the device
3405 * This function will check if runtime suspend is allowed for the device
3406 * by examining if there are any requests pending in the queue. If there
3407 * are requests pending, the device can not be runtime suspended; otherwise,
3408 * the queue's status will be updated to SUSPENDING and the driver can
3409 * proceed to suspend the device.
3411 * For the not allowed case, we mark last busy for the device so that
3412 * runtime PM core will try to autosuspend it some time later.
3414 * This function should be called near the start of the device's
3415 * runtime_suspend callback.
3418 * 0 - OK to runtime suspend the device
3419 * -EBUSY - Device should not be runtime suspended
3421 int blk_pre_runtime_suspend(struct request_queue *q)
3428 spin_lock_irq(q->queue_lock);
3429 if (q->nr_pending) {
3431 pm_runtime_mark_last_busy(q->dev);
3433 q->rpm_status = RPM_SUSPENDING;
3435 spin_unlock_irq(q->queue_lock);
3438 EXPORT_SYMBOL(blk_pre_runtime_suspend);
3441 * blk_post_runtime_suspend - Post runtime suspend processing
3442 * @q: the queue of the device
3443 * @err: return value of the device's runtime_suspend function
3446 * Update the queue's runtime status according to the return value of the
3447 * device's runtime suspend function and mark last busy for the device so
3448 * that PM core will try to auto suspend the device at a later time.
3450 * This function should be called near the end of the device's
3451 * runtime_suspend callback.
3453 void blk_post_runtime_suspend(struct request_queue *q, int err)
3458 spin_lock_irq(q->queue_lock);
3460 q->rpm_status = RPM_SUSPENDED;
3462 q->rpm_status = RPM_ACTIVE;
3463 pm_runtime_mark_last_busy(q->dev);
3465 spin_unlock_irq(q->queue_lock);
3467 EXPORT_SYMBOL(blk_post_runtime_suspend);
3470 * blk_pre_runtime_resume - Pre runtime resume processing
3471 * @q: the queue of the device
3474 * Update the queue's runtime status to RESUMING in preparation for the
3475 * runtime resume of the device.
3477 * This function should be called near the start of the device's
3478 * runtime_resume callback.
3480 void blk_pre_runtime_resume(struct request_queue *q)
3485 spin_lock_irq(q->queue_lock);
3486 q->rpm_status = RPM_RESUMING;
3487 spin_unlock_irq(q->queue_lock);
3489 EXPORT_SYMBOL(blk_pre_runtime_resume);
3492 * blk_post_runtime_resume - Post runtime resume processing
3493 * @q: the queue of the device
3494 * @err: return value of the device's runtime_resume function
3497 * Update the queue's runtime status according to the return value of the
3498 * device's runtime_resume function. If it is successfully resumed, process
3499 * the requests that are queued into the device's queue when it is resuming
3500 * and then mark last busy and initiate autosuspend for it.
3502 * This function should be called near the end of the device's
3503 * runtime_resume callback.
3505 void blk_post_runtime_resume(struct request_queue *q, int err)
3510 spin_lock_irq(q->queue_lock);
3512 q->rpm_status = RPM_ACTIVE;
3514 pm_runtime_mark_last_busy(q->dev);
3515 pm_request_autosuspend(q->dev);
3517 q->rpm_status = RPM_SUSPENDED;
3519 spin_unlock_irq(q->queue_lock);
3521 EXPORT_SYMBOL(blk_post_runtime_resume);
3524 * blk_set_runtime_active - Force runtime status of the queue to be active
3525 * @q: the queue of the device
3527 * If the device is left runtime suspended during system suspend the resume
3528 * hook typically resumes the device and corrects runtime status
3529 * accordingly. However, that does not affect the queue runtime PM status
3530 * which is still "suspended". This prevents processing requests from the
3533 * This function can be used in driver's resume hook to correct queue
3534 * runtime PM status and re-enable peeking requests from the queue. It
3535 * should be called before first request is added to the queue.
3537 void blk_set_runtime_active(struct request_queue *q)
3539 spin_lock_irq(q->queue_lock);
3540 q->rpm_status = RPM_ACTIVE;
3541 pm_runtime_mark_last_busy(q->dev);
3542 pm_request_autosuspend(q->dev);
3543 spin_unlock_irq(q->queue_lock);
3545 EXPORT_SYMBOL(blk_set_runtime_active);
3548 int __init blk_dev_init(void)
3550 BUILD_BUG_ON(REQ_OP_LAST >= (1 << REQ_OP_BITS));
3551 BUILD_BUG_ON(REQ_OP_BITS + REQ_FLAG_BITS > 8 *
3552 FIELD_SIZEOF(struct request, cmd_flags));
3553 BUILD_BUG_ON(REQ_OP_BITS + REQ_FLAG_BITS > 8 *
3554 FIELD_SIZEOF(struct bio, bi_opf));
3556 /* used for unplugging and affects IO latency/throughput - HIGHPRI */
3557 kblockd_workqueue = alloc_workqueue("kblockd",
3558 WQ_MEM_RECLAIM | WQ_HIGHPRI, 0);
3559 if (!kblockd_workqueue)
3560 panic("Failed to create kblockd\n");
3562 request_cachep = kmem_cache_create("blkdev_requests",
3563 sizeof(struct request), 0, SLAB_PANIC, NULL);
3565 blk_requestq_cachep = kmem_cache_create("request_queue",
3566 sizeof(struct request_queue), 0, SLAB_PANIC, NULL);
3568 #ifdef CONFIG_DEBUG_FS
3569 blk_debugfs_root = debugfs_create_dir("block", NULL);