bnxt_en: Reset device on RX buffer errors.
[linux/fpc-iii.git] / block / blk-core.c
blob77b99bf16c83cf169144f082b18b5b1f8a33e7a9
1 /*
2 * Copyright (C) 1991, 1992 Linus Torvalds
3 * Copyright (C) 1994, Karl Keyte: Added support for disk statistics
4 * Elevator latency, (C) 2000 Andrea Arcangeli <andrea@suse.de> SuSE
5 * Queue request tables / lock, selectable elevator, Jens Axboe <axboe@suse.de>
6 * kernel-doc documentation started by NeilBrown <neilb@cse.unsw.edu.au>
7 * - July2000
8 * bio rewrite, highmem i/o, etc, Jens Axboe <axboe@suse.de> - may 2001
9 */
12 * This handles all read/write requests to block devices
14 #include <linux/kernel.h>
15 #include <linux/module.h>
16 #include <linux/backing-dev.h>
17 #include <linux/bio.h>
18 #include <linux/blkdev.h>
19 #include <linux/blk-mq.h>
20 #include <linux/highmem.h>
21 #include <linux/mm.h>
22 #include <linux/kernel_stat.h>
23 #include <linux/string.h>
24 #include <linux/init.h>
25 #include <linux/completion.h>
26 #include <linux/slab.h>
27 #include <linux/swap.h>
28 #include <linux/writeback.h>
29 #include <linux/task_io_accounting_ops.h>
30 #include <linux/fault-inject.h>
31 #include <linux/list_sort.h>
32 #include <linux/delay.h>
33 #include <linux/ratelimit.h>
34 #include <linux/pm_runtime.h>
35 #include <linux/blk-cgroup.h>
37 #define CREATE_TRACE_POINTS
38 #include <trace/events/block.h>
40 #include "blk.h"
41 #include "blk-mq.h"
43 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_remap);
44 EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_remap);
45 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_complete);
46 EXPORT_TRACEPOINT_SYMBOL_GPL(block_split);
47 EXPORT_TRACEPOINT_SYMBOL_GPL(block_unplug);
49 DEFINE_IDA(blk_queue_ida);
52 * For the allocated request tables
54 struct kmem_cache *request_cachep;
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);
70 #else
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);
77 #endif
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);
84 #else
85 /* see blk_clear_congested() */
86 if (rl == &rl->q->root_rl)
87 set_wb_congested(rl->q->backing_dev_info.wb.congested, sync);
88 #endif
91 void blk_queue_congestion_threshold(struct request_queue *q)
93 int nr;
95 nr = q->nr_requests - (q->nr_requests / 8) + 1;
96 if (nr > q->nr_requests)
97 nr = q->nr_requests;
98 q->nr_congestion_on = nr;
100 nr = q->nr_requests - (q->nr_requests / 8) - (q->nr_requests / 16) - 1;
101 if (nr < 1)
102 nr = 1;
103 q->nr_congestion_off = nr;
107 * blk_get_backing_dev_info - get the address of a queue's backing_dev_info
108 * @bdev: device
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);
128 rq->cpu = -1;
129 rq->q = q;
130 rq->__sector = (sector_t) -1;
131 INIT_HLIST_NODE(&rq->hash);
132 RB_CLEAR_NODE(&rq->rb_node);
133 rq->cmd = rq->__cmd;
134 rq->cmd_len = BLK_MAX_CDB;
135 rq->tag = -1;
136 rq->start_time = jiffies;
137 set_start_time_ns(rq);
138 rq->part = NULL;
140 EXPORT_SYMBOL(blk_rq_init);
142 static void req_bio_endio(struct request *rq, struct bio *bio,
143 unsigned int nbytes, int error)
145 if (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))
155 bio_endio(bio);
158 void blk_dump_rq_flags(struct request *rq, char *msg)
160 int bit;
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]);
176 printk("\n");
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);
187 __blk_run_queue(q);
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
196 * Description:
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
213 * Description:
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
216 * context.
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
229 * Description:
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);
239 __blk_run_queue(q);
241 EXPORT_SYMBOL(blk_start_queue);
244 * blk_stop_queue - stop a queue
245 * @q: The &struct request_queue in question
247 * Description:
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
266 * @q: the queue
268 * Description:
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
275 * this function.
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);
287 if (q->mq_ops) {
288 struct blk_mq_hw_ctx *hctx;
289 int i;
291 queue_for_each_hw_ctx(q, hctx, i) {
292 cancel_work_sync(&hctx->run_work);
293 cancel_delayed_work_sync(&hctx->delay_work);
295 } else {
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
305 * Description:
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)))
315 return;
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++;
325 q->request_fn(q);
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
334 * Description:
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)))
341 return;
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
351 * Description:
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
366 * Description:
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)
372 unsigned long flags;
374 spin_lock_irqsave(q->queue_lock, flags);
375 __blk_run_queue(q);
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
388 * @q: queue to drain
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)
399 int i;
401 lockdep_assert_held(q->queue_lock);
403 while (true) {
404 bool drain = false;
407 * The caller might be trying to drain @q before its
408 * elevator is initialized.
410 if (q->elevator)
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)
423 __blk_run_queue(q);
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.
433 if (drain_all) {
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];
439 if (fq)
440 drain |= !list_empty(&fq->flush_queue[i]);
444 if (!drain)
445 break;
447 spin_unlock_irq(q->queue_lock);
449 msleep(10);
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.
459 if (q->request_fn) {
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);
481 q->bypass_depth++;
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 */
496 synchronize_rcu();
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);
523 if (q->mq_ops)
524 blk_mq_wake_waiters(q);
525 else {
526 struct request_list *rl;
528 blk_queue_for_each_rl(rl, q) {
529 if (rl->rq_pool) {
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);
552 spin_lock_irq(lock);
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.
563 q->bypass_depth++;
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.
576 blk_freeze_queue(q);
577 spin_lock_irq(lock);
578 if (!q->mq_ops)
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);
588 blk_sync_queue(q);
590 if (q->mq_ops)
591 blk_mq_free_queue(q);
592 percpu_ref_exit(&q->q_usage_counter);
594 spin_lock_irq(lock);
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 */
602 blk_put_queue(q);
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,
619 gfp_t gfp_mask)
621 if (unlikely(rl->rq_pool))
622 return 0;
624 rl->q = q;
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,
631 free_request_struct,
632 (void *)(long)q->node, gfp_mask,
633 q->node);
634 if (!rl->rq_pool)
635 return -ENOMEM;
637 return 0;
640 void blk_exit_rl(struct request_list *rl)
642 if (rl->rq_pool)
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)
654 while (true) {
656 if (percpu_ref_tryget_live(&q->q_usage_counter))
657 return 0;
659 if (nowait)
660 return -EBUSY;
662 wait_event(q->mq_freeze_wq,
663 !atomic_read(&q->mq_freeze_depth) ||
664 blk_queue_dying(q));
665 if (blk_queue_dying(q))
666 return -ENODEV;
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;
693 int err;
695 q = kmem_cache_alloc_node(blk_requestq_cachep,
696 gfp_mask | __GFP_ZERO, node_id);
697 if (!q)
698 return NULL;
700 q->id = ida_simple_get(&blk_queue_ida, 0, 0, gfp_mask);
701 if (q->id < 0)
702 goto fail_q;
704 q->bio_split = bioset_create(BIO_POOL_SIZE, 0);
705 if (!q->bio_split)
706 goto fail_id;
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";
712 q->node = node_id;
714 err = bdi_init(&q->backing_dev_info);
715 if (err)
716 goto fail_split;
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);
727 #endif
728 INIT_DELAYED_WORK(&q->delay_work, blk_delay_work);
730 kobject_init(&q->kobj, &blk_queue_ktype);
732 mutex_init(&q->sysfs_lock);
733 spin_lock_init(&q->__queue_lock);
736 * By default initialize queue_lock to internal lock and driver can
737 * override it later if need be.
739 q->queue_lock = &q->__queue_lock;
742 * A queue starts its life with bypass turned on to avoid
743 * unnecessary bypass on/off overhead and nasty surprises during
744 * init. The initial bypass will be finished when the queue is
745 * registered by blk_register_queue().
747 q->bypass_depth = 1;
748 __set_bit(QUEUE_FLAG_BYPASS, &q->queue_flags);
750 init_waitqueue_head(&q->mq_freeze_wq);
753 * Init percpu_ref in atomic mode so that it's faster to shutdown.
754 * See blk_register_queue() for details.
756 if (percpu_ref_init(&q->q_usage_counter,
757 blk_queue_usage_counter_release,
758 PERCPU_REF_INIT_ATOMIC, GFP_KERNEL))
759 goto fail_bdi;
761 if (blkcg_init_queue(q))
762 goto fail_ref;
764 return q;
766 fail_ref:
767 percpu_ref_exit(&q->q_usage_counter);
768 fail_bdi:
769 bdi_destroy(&q->backing_dev_info);
770 fail_split:
771 bioset_free(q->bio_split);
772 fail_id:
773 ida_simple_remove(&blk_queue_ida, q->id);
774 fail_q:
775 kmem_cache_free(blk_requestq_cachep, q);
776 return NULL;
778 EXPORT_SYMBOL(blk_alloc_queue_node);
781 * blk_init_queue - prepare a request queue for use with a block device
782 * @rfn: The function to be called to process requests that have been
783 * placed on the queue.
784 * @lock: Request queue spin lock
786 * Description:
787 * If a block device wishes to use the standard request handling procedures,
788 * which sorts requests and coalesces adjacent requests, then it must
789 * call blk_init_queue(). The function @rfn will be called when there
790 * are requests on the queue that need to be processed. If the device
791 * supports plugging, then @rfn may not be called immediately when requests
792 * are available on the queue, but may be called at some time later instead.
793 * Plugged queues are generally unplugged when a buffer belonging to one
794 * of the requests on the queue is needed, or due to memory pressure.
796 * @rfn is not required, or even expected, to remove all requests off the
797 * queue, but only as many as it can handle at a time. If it does leave
798 * requests on the queue, it is responsible for arranging that the requests
799 * get dealt with eventually.
801 * The queue spin lock must be held while manipulating the requests on the
802 * request queue; this lock will be taken also from interrupt context, so irq
803 * disabling is needed for it.
805 * Function returns a pointer to the initialized request queue, or %NULL if
806 * it didn't succeed.
808 * Note:
809 * blk_init_queue() must be paired with a blk_cleanup_queue() call
810 * when the block device is deactivated (such as at module unload).
813 struct request_queue *blk_init_queue(request_fn_proc *rfn, spinlock_t *lock)
815 return blk_init_queue_node(rfn, lock, NUMA_NO_NODE);
817 EXPORT_SYMBOL(blk_init_queue);
819 struct request_queue *
820 blk_init_queue_node(request_fn_proc *rfn, spinlock_t *lock, int node_id)
822 struct request_queue *uninit_q, *q;
824 uninit_q = blk_alloc_queue_node(GFP_KERNEL, node_id);
825 if (!uninit_q)
826 return NULL;
828 q = blk_init_allocated_queue(uninit_q, rfn, lock);
829 if (!q)
830 blk_cleanup_queue(uninit_q);
832 return q;
834 EXPORT_SYMBOL(blk_init_queue_node);
836 static blk_qc_t blk_queue_bio(struct request_queue *q, struct bio *bio);
838 struct request_queue *
839 blk_init_allocated_queue(struct request_queue *q, request_fn_proc *rfn,
840 spinlock_t *lock)
842 if (!q)
843 return NULL;
845 q->fq = blk_alloc_flush_queue(q, NUMA_NO_NODE, 0);
846 if (!q->fq)
847 return NULL;
849 if (blk_init_rl(&q->root_rl, q, GFP_KERNEL))
850 goto fail;
852 INIT_WORK(&q->timeout_work, blk_timeout_work);
853 q->request_fn = rfn;
854 q->prep_rq_fn = NULL;
855 q->unprep_rq_fn = NULL;
856 q->queue_flags |= QUEUE_FLAG_DEFAULT;
858 /* Override internal queue lock with supplied lock pointer */
859 if (lock)
860 q->queue_lock = lock;
863 * This also sets hw/phys segments, boundary and size
865 blk_queue_make_request(q, blk_queue_bio);
867 q->sg_reserved_size = INT_MAX;
869 /* Protect q->elevator from elevator_change */
870 mutex_lock(&q->sysfs_lock);
872 /* init elevator */
873 if (elevator_init(q, NULL)) {
874 mutex_unlock(&q->sysfs_lock);
875 goto fail;
878 mutex_unlock(&q->sysfs_lock);
880 return q;
882 fail:
883 blk_free_flush_queue(q->fq);
884 return NULL;
886 EXPORT_SYMBOL(blk_init_allocated_queue);
888 bool blk_get_queue(struct request_queue *q)
890 if (likely(!blk_queue_dying(q))) {
891 __blk_get_queue(q);
892 return true;
895 return false;
897 EXPORT_SYMBOL(blk_get_queue);
899 static inline void blk_free_request(struct request_list *rl, struct request *rq)
901 if (rq->cmd_flags & REQ_ELVPRIV) {
902 elv_put_request(rl->q, rq);
903 if (rq->elv.icq)
904 put_io_context(rq->elv.icq->ioc);
907 mempool_free(rq, rl->rq_pool);
911 * ioc_batching returns true if the ioc is a valid batching request and
912 * should be given priority access to a request.
914 static inline int ioc_batching(struct request_queue *q, struct io_context *ioc)
916 if (!ioc)
917 return 0;
920 * Make sure the process is able to allocate at least 1 request
921 * even if the batch times out, otherwise we could theoretically
922 * lose wakeups.
924 return ioc->nr_batch_requests == q->nr_batching ||
925 (ioc->nr_batch_requests > 0
926 && time_before(jiffies, ioc->last_waited + BLK_BATCH_TIME));
930 * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
931 * will cause the process to be a "batcher" on all queues in the system. This
932 * is the behaviour we want though - once it gets a wakeup it should be given
933 * a nice run.
935 static void ioc_set_batching(struct request_queue *q, struct io_context *ioc)
937 if (!ioc || ioc_batching(q, ioc))
938 return;
940 ioc->nr_batch_requests = q->nr_batching;
941 ioc->last_waited = jiffies;
944 static void __freed_request(struct request_list *rl, int sync)
946 struct request_queue *q = rl->q;
948 if (rl->count[sync] < queue_congestion_off_threshold(q))
949 blk_clear_congested(rl, sync);
951 if (rl->count[sync] + 1 <= q->nr_requests) {
952 if (waitqueue_active(&rl->wait[sync]))
953 wake_up(&rl->wait[sync]);
955 blk_clear_rl_full(rl, sync);
960 * A request has just been released. Account for it, update the full and
961 * congestion status, wake up any waiters. Called under q->queue_lock.
963 static void freed_request(struct request_list *rl, int op, unsigned int flags)
965 struct request_queue *q = rl->q;
966 int sync = rw_is_sync(op, flags);
968 q->nr_rqs[sync]--;
969 rl->count[sync]--;
970 if (flags & REQ_ELVPRIV)
971 q->nr_rqs_elvpriv--;
973 __freed_request(rl, sync);
975 if (unlikely(rl->starved[sync ^ 1]))
976 __freed_request(rl, sync ^ 1);
979 int blk_update_nr_requests(struct request_queue *q, unsigned int nr)
981 struct request_list *rl;
982 int on_thresh, off_thresh;
984 spin_lock_irq(q->queue_lock);
985 q->nr_requests = nr;
986 blk_queue_congestion_threshold(q);
987 on_thresh = queue_congestion_on_threshold(q);
988 off_thresh = queue_congestion_off_threshold(q);
990 blk_queue_for_each_rl(rl, q) {
991 if (rl->count[BLK_RW_SYNC] >= on_thresh)
992 blk_set_congested(rl, BLK_RW_SYNC);
993 else if (rl->count[BLK_RW_SYNC] < off_thresh)
994 blk_clear_congested(rl, BLK_RW_SYNC);
996 if (rl->count[BLK_RW_ASYNC] >= on_thresh)
997 blk_set_congested(rl, BLK_RW_ASYNC);
998 else if (rl->count[BLK_RW_ASYNC] < off_thresh)
999 blk_clear_congested(rl, BLK_RW_ASYNC);
1001 if (rl->count[BLK_RW_SYNC] >= q->nr_requests) {
1002 blk_set_rl_full(rl, BLK_RW_SYNC);
1003 } else {
1004 blk_clear_rl_full(rl, BLK_RW_SYNC);
1005 wake_up(&rl->wait[BLK_RW_SYNC]);
1008 if (rl->count[BLK_RW_ASYNC] >= q->nr_requests) {
1009 blk_set_rl_full(rl, BLK_RW_ASYNC);
1010 } else {
1011 blk_clear_rl_full(rl, BLK_RW_ASYNC);
1012 wake_up(&rl->wait[BLK_RW_ASYNC]);
1016 spin_unlock_irq(q->queue_lock);
1017 return 0;
1021 * Determine if elevator data should be initialized when allocating the
1022 * request associated with @bio.
1024 static bool blk_rq_should_init_elevator(struct bio *bio)
1026 if (!bio)
1027 return true;
1030 * Flush requests do not use the elevator so skip initialization.
1031 * This allows a request to share the flush and elevator data.
1033 if (bio->bi_opf & (REQ_PREFLUSH | REQ_FUA))
1034 return false;
1036 return true;
1040 * rq_ioc - determine io_context for request allocation
1041 * @bio: request being allocated is for this bio (can be %NULL)
1043 * Determine io_context to use for request allocation for @bio. May return
1044 * %NULL if %current->io_context doesn't exist.
1046 static struct io_context *rq_ioc(struct bio *bio)
1048 #ifdef CONFIG_BLK_CGROUP
1049 if (bio && bio->bi_ioc)
1050 return bio->bi_ioc;
1051 #endif
1052 return current->io_context;
1056 * __get_request - get a free request
1057 * @rl: request list to allocate from
1058 * @op: REQ_OP_READ/REQ_OP_WRITE
1059 * @op_flags: rq_flag_bits
1060 * @bio: bio to allocate request for (can be %NULL)
1061 * @gfp_mask: allocation mask
1063 * Get a free request from @q. This function may fail under memory
1064 * pressure or if @q is dead.
1066 * Must be called with @q->queue_lock held and,
1067 * Returns ERR_PTR on failure, with @q->queue_lock held.
1068 * Returns request pointer on success, with @q->queue_lock *not held*.
1070 static struct request *__get_request(struct request_list *rl, int op,
1071 int op_flags, struct bio *bio,
1072 gfp_t gfp_mask)
1074 struct request_queue *q = rl->q;
1075 struct request *rq;
1076 struct elevator_type *et = q->elevator->type;
1077 struct io_context *ioc = rq_ioc(bio);
1078 struct io_cq *icq = NULL;
1079 const bool is_sync = rw_is_sync(op, op_flags) != 0;
1080 int may_queue;
1082 if (unlikely(blk_queue_dying(q)))
1083 return ERR_PTR(-ENODEV);
1085 may_queue = elv_may_queue(q, op, op_flags);
1086 if (may_queue == ELV_MQUEUE_NO)
1087 goto rq_starved;
1089 if (rl->count[is_sync]+1 >= queue_congestion_on_threshold(q)) {
1090 if (rl->count[is_sync]+1 >= q->nr_requests) {
1092 * The queue will fill after this allocation, so set
1093 * it as full, and mark this process as "batching".
1094 * This process will be allowed to complete a batch of
1095 * requests, others will be blocked.
1097 if (!blk_rl_full(rl, is_sync)) {
1098 ioc_set_batching(q, ioc);
1099 blk_set_rl_full(rl, is_sync);
1100 } else {
1101 if (may_queue != ELV_MQUEUE_MUST
1102 && !ioc_batching(q, ioc)) {
1104 * The queue is full and the allocating
1105 * process is not a "batcher", and not
1106 * exempted by the IO scheduler
1108 return ERR_PTR(-ENOMEM);
1112 blk_set_congested(rl, is_sync);
1116 * Only allow batching queuers to allocate up to 50% over the defined
1117 * limit of requests, otherwise we could have thousands of requests
1118 * allocated with any setting of ->nr_requests
1120 if (rl->count[is_sync] >= (3 * q->nr_requests / 2))
1121 return ERR_PTR(-ENOMEM);
1123 q->nr_rqs[is_sync]++;
1124 rl->count[is_sync]++;
1125 rl->starved[is_sync] = 0;
1128 * Decide whether the new request will be managed by elevator. If
1129 * so, mark @op_flags and increment elvpriv. Non-zero elvpriv will
1130 * prevent the current elevator from being destroyed until the new
1131 * request is freed. This guarantees icq's won't be destroyed and
1132 * makes creating new ones safe.
1134 * Also, lookup icq while holding queue_lock. If it doesn't exist,
1135 * it will be created after releasing queue_lock.
1137 if (blk_rq_should_init_elevator(bio) && !blk_queue_bypass(q)) {
1138 op_flags |= REQ_ELVPRIV;
1139 q->nr_rqs_elvpriv++;
1140 if (et->icq_cache && ioc)
1141 icq = ioc_lookup_icq(ioc, q);
1144 if (blk_queue_io_stat(q))
1145 op_flags |= REQ_IO_STAT;
1146 spin_unlock_irq(q->queue_lock);
1148 /* allocate and init request */
1149 rq = mempool_alloc(rl->rq_pool, gfp_mask);
1150 if (!rq)
1151 goto fail_alloc;
1153 blk_rq_init(q, rq);
1154 blk_rq_set_rl(rq, rl);
1155 req_set_op_attrs(rq, op, op_flags | REQ_ALLOCED);
1157 /* init elvpriv */
1158 if (op_flags & REQ_ELVPRIV) {
1159 if (unlikely(et->icq_cache && !icq)) {
1160 if (ioc)
1161 icq = ioc_create_icq(ioc, q, gfp_mask);
1162 if (!icq)
1163 goto fail_elvpriv;
1166 rq->elv.icq = icq;
1167 if (unlikely(elv_set_request(q, rq, bio, gfp_mask)))
1168 goto fail_elvpriv;
1170 /* @rq->elv.icq holds io_context until @rq is freed */
1171 if (icq)
1172 get_io_context(icq->ioc);
1174 out:
1176 * ioc may be NULL here, and ioc_batching will be false. That's
1177 * OK, if the queue is under the request limit then requests need
1178 * not count toward the nr_batch_requests limit. There will always
1179 * be some limit enforced by BLK_BATCH_TIME.
1181 if (ioc_batching(q, ioc))
1182 ioc->nr_batch_requests--;
1184 trace_block_getrq(q, bio, op);
1185 return rq;
1187 fail_elvpriv:
1189 * elvpriv init failed. ioc, icq and elvpriv aren't mempool backed
1190 * and may fail indefinitely under memory pressure and thus
1191 * shouldn't stall IO. Treat this request as !elvpriv. This will
1192 * disturb iosched and blkcg but weird is bettern than dead.
1194 printk_ratelimited(KERN_WARNING "%s: dev %s: request aux data allocation failed, iosched may be disturbed\n",
1195 __func__, dev_name(q->backing_dev_info.dev));
1197 rq->cmd_flags &= ~REQ_ELVPRIV;
1198 rq->elv.icq = NULL;
1200 spin_lock_irq(q->queue_lock);
1201 q->nr_rqs_elvpriv--;
1202 spin_unlock_irq(q->queue_lock);
1203 goto out;
1205 fail_alloc:
1207 * Allocation failed presumably due to memory. Undo anything we
1208 * might have messed up.
1210 * Allocating task should really be put onto the front of the wait
1211 * queue, but this is pretty rare.
1213 spin_lock_irq(q->queue_lock);
1214 freed_request(rl, op, op_flags);
1217 * in the very unlikely event that allocation failed and no
1218 * requests for this direction was pending, mark us starved so that
1219 * freeing of a request in the other direction will notice
1220 * us. another possible fix would be to split the rq mempool into
1221 * READ and WRITE
1223 rq_starved:
1224 if (unlikely(rl->count[is_sync] == 0))
1225 rl->starved[is_sync] = 1;
1226 return ERR_PTR(-ENOMEM);
1230 * get_request - get a free request
1231 * @q: request_queue to allocate request from
1232 * @op: REQ_OP_READ/REQ_OP_WRITE
1233 * @op_flags: rq_flag_bits
1234 * @bio: bio to allocate request for (can be %NULL)
1235 * @gfp_mask: allocation mask
1237 * Get a free request from @q. If %__GFP_DIRECT_RECLAIM is set in @gfp_mask,
1238 * this function keeps retrying under memory pressure and fails iff @q is dead.
1240 * Must be called with @q->queue_lock held and,
1241 * Returns ERR_PTR on failure, with @q->queue_lock held.
1242 * Returns request pointer on success, with @q->queue_lock *not held*.
1244 static struct request *get_request(struct request_queue *q, int op,
1245 int op_flags, struct bio *bio,
1246 gfp_t gfp_mask)
1248 const bool is_sync = rw_is_sync(op, op_flags) != 0;
1249 DEFINE_WAIT(wait);
1250 struct request_list *rl;
1251 struct request *rq;
1253 rl = blk_get_rl(q, bio); /* transferred to @rq on success */
1254 retry:
1255 rq = __get_request(rl, op, op_flags, bio, gfp_mask);
1256 if (!IS_ERR(rq))
1257 return rq;
1259 if (!gfpflags_allow_blocking(gfp_mask) || unlikely(blk_queue_dying(q))) {
1260 blk_put_rl(rl);
1261 return rq;
1264 /* wait on @rl and retry */
1265 prepare_to_wait_exclusive(&rl->wait[is_sync], &wait,
1266 TASK_UNINTERRUPTIBLE);
1268 trace_block_sleeprq(q, bio, op);
1270 spin_unlock_irq(q->queue_lock);
1271 io_schedule();
1274 * After sleeping, we become a "batching" process and will be able
1275 * to allocate at least one request, and up to a big batch of them
1276 * for a small period time. See ioc_batching, ioc_set_batching
1278 ioc_set_batching(q, current->io_context);
1280 spin_lock_irq(q->queue_lock);
1281 finish_wait(&rl->wait[is_sync], &wait);
1283 goto retry;
1286 static struct request *blk_old_get_request(struct request_queue *q, int rw,
1287 gfp_t gfp_mask)
1289 struct request *rq;
1291 BUG_ON(rw != READ && rw != WRITE);
1293 /* create ioc upfront */
1294 create_io_context(gfp_mask, q->node);
1296 spin_lock_irq(q->queue_lock);
1297 rq = get_request(q, rw, 0, NULL, gfp_mask);
1298 if (IS_ERR(rq)) {
1299 spin_unlock_irq(q->queue_lock);
1300 return rq;
1303 /* q->queue_lock is unlocked at this point */
1304 rq->__data_len = 0;
1305 rq->__sector = (sector_t) -1;
1306 rq->bio = rq->biotail = NULL;
1307 return rq;
1310 struct request *blk_get_request(struct request_queue *q, int rw, gfp_t gfp_mask)
1312 if (q->mq_ops)
1313 return blk_mq_alloc_request(q, rw,
1314 (gfp_mask & __GFP_DIRECT_RECLAIM) ?
1315 0 : BLK_MQ_REQ_NOWAIT);
1316 else
1317 return blk_old_get_request(q, rw, gfp_mask);
1319 EXPORT_SYMBOL(blk_get_request);
1322 * blk_rq_set_block_pc - initialize a request to type BLOCK_PC
1323 * @rq: request to be initialized
1326 void blk_rq_set_block_pc(struct request *rq)
1328 rq->cmd_type = REQ_TYPE_BLOCK_PC;
1329 memset(rq->__cmd, 0, sizeof(rq->__cmd));
1331 EXPORT_SYMBOL(blk_rq_set_block_pc);
1334 * blk_requeue_request - put a request back on queue
1335 * @q: request queue where request should be inserted
1336 * @rq: request to be inserted
1338 * Description:
1339 * Drivers often keep queueing requests until the hardware cannot accept
1340 * more, when that condition happens we need to put the request back
1341 * on the queue. Must be called with queue lock held.
1343 void blk_requeue_request(struct request_queue *q, struct request *rq)
1345 blk_delete_timer(rq);
1346 blk_clear_rq_complete(rq);
1347 trace_block_rq_requeue(q, rq);
1349 if (rq->cmd_flags & REQ_QUEUED)
1350 blk_queue_end_tag(q, rq);
1352 BUG_ON(blk_queued_rq(rq));
1354 elv_requeue_request(q, rq);
1356 EXPORT_SYMBOL(blk_requeue_request);
1358 static void add_acct_request(struct request_queue *q, struct request *rq,
1359 int where)
1361 blk_account_io_start(rq, true);
1362 __elv_add_request(q, rq, where);
1365 static void part_round_stats_single(int cpu, struct hd_struct *part,
1366 unsigned long now)
1368 int inflight;
1370 if (now == part->stamp)
1371 return;
1373 inflight = part_in_flight(part);
1374 if (inflight) {
1375 __part_stat_add(cpu, part, time_in_queue,
1376 inflight * (now - part->stamp));
1377 __part_stat_add(cpu, part, io_ticks, (now - part->stamp));
1379 part->stamp = now;
1383 * part_round_stats() - Round off the performance stats on a struct disk_stats.
1384 * @cpu: cpu number for stats access
1385 * @part: target partition
1387 * The average IO queue length and utilisation statistics are maintained
1388 * by observing the current state of the queue length and the amount of
1389 * time it has been in this state for.
1391 * Normally, that accounting is done on IO completion, but that can result
1392 * in more than a second's worth of IO being accounted for within any one
1393 * second, leading to >100% utilisation. To deal with that, we call this
1394 * function to do a round-off before returning the results when reading
1395 * /proc/diskstats. This accounts immediately for all queue usage up to
1396 * the current jiffies and restarts the counters again.
1398 void part_round_stats(int cpu, struct hd_struct *part)
1400 unsigned long now = jiffies;
1402 if (part->partno)
1403 part_round_stats_single(cpu, &part_to_disk(part)->part0, now);
1404 part_round_stats_single(cpu, part, now);
1406 EXPORT_SYMBOL_GPL(part_round_stats);
1408 #ifdef CONFIG_PM
1409 static void blk_pm_put_request(struct request *rq)
1411 if (rq->q->dev && !(rq->cmd_flags & REQ_PM) && !--rq->q->nr_pending)
1412 pm_runtime_mark_last_busy(rq->q->dev);
1414 #else
1415 static inline void blk_pm_put_request(struct request *rq) {}
1416 #endif
1419 * queue lock must be held
1421 void __blk_put_request(struct request_queue *q, struct request *req)
1423 if (unlikely(!q))
1424 return;
1426 if (q->mq_ops) {
1427 blk_mq_free_request(req);
1428 return;
1431 blk_pm_put_request(req);
1433 elv_completed_request(q, req);
1435 /* this is a bio leak */
1436 WARN_ON(req->bio != NULL);
1439 * Request may not have originated from ll_rw_blk. if not,
1440 * it didn't come out of our reserved rq pools
1442 if (req->cmd_flags & REQ_ALLOCED) {
1443 unsigned int flags = req->cmd_flags;
1444 int op = req_op(req);
1445 struct request_list *rl = blk_rq_rl(req);
1447 BUG_ON(!list_empty(&req->queuelist));
1448 BUG_ON(ELV_ON_HASH(req));
1450 blk_free_request(rl, req);
1451 freed_request(rl, op, flags);
1452 blk_put_rl(rl);
1455 EXPORT_SYMBOL_GPL(__blk_put_request);
1457 void blk_put_request(struct request *req)
1459 struct request_queue *q = req->q;
1461 if (q->mq_ops)
1462 blk_mq_free_request(req);
1463 else {
1464 unsigned long flags;
1466 spin_lock_irqsave(q->queue_lock, flags);
1467 __blk_put_request(q, req);
1468 spin_unlock_irqrestore(q->queue_lock, flags);
1471 EXPORT_SYMBOL(blk_put_request);
1474 * blk_add_request_payload - add a payload to a request
1475 * @rq: request to update
1476 * @page: page backing the payload
1477 * @offset: offset in page
1478 * @len: length of the payload.
1480 * This allows to later add a payload to an already submitted request by
1481 * a block driver. The driver needs to take care of freeing the payload
1482 * itself.
1484 * Note that this is a quite horrible hack and nothing but handling of
1485 * discard requests should ever use it.
1487 void blk_add_request_payload(struct request *rq, struct page *page,
1488 int offset, unsigned int len)
1490 struct bio *bio = rq->bio;
1492 bio->bi_io_vec->bv_page = page;
1493 bio->bi_io_vec->bv_offset = offset;
1494 bio->bi_io_vec->bv_len = len;
1496 bio->bi_iter.bi_size = len;
1497 bio->bi_vcnt = 1;
1498 bio->bi_phys_segments = 1;
1500 rq->__data_len = rq->resid_len = len;
1501 rq->nr_phys_segments = 1;
1503 EXPORT_SYMBOL_GPL(blk_add_request_payload);
1505 bool bio_attempt_back_merge(struct request_queue *q, struct request *req,
1506 struct bio *bio)
1508 const int ff = bio->bi_opf & REQ_FAILFAST_MASK;
1510 if (!ll_back_merge_fn(q, req, bio))
1511 return false;
1513 trace_block_bio_backmerge(q, req, bio);
1515 if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
1516 blk_rq_set_mixed_merge(req);
1518 req->biotail->bi_next = bio;
1519 req->biotail = bio;
1520 req->__data_len += bio->bi_iter.bi_size;
1521 req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
1523 blk_account_io_start(req, false);
1524 return true;
1527 bool bio_attempt_front_merge(struct request_queue *q, struct request *req,
1528 struct bio *bio)
1530 const int ff = bio->bi_opf & REQ_FAILFAST_MASK;
1532 if (!ll_front_merge_fn(q, req, bio))
1533 return false;
1535 trace_block_bio_frontmerge(q, req, bio);
1537 if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
1538 blk_rq_set_mixed_merge(req);
1540 bio->bi_next = req->bio;
1541 req->bio = bio;
1543 req->__sector = bio->bi_iter.bi_sector;
1544 req->__data_len += bio->bi_iter.bi_size;
1545 req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
1547 blk_account_io_start(req, false);
1548 return true;
1552 * blk_attempt_plug_merge - try to merge with %current's plugged list
1553 * @q: request_queue new bio is being queued at
1554 * @bio: new bio being queued
1555 * @request_count: out parameter for number of traversed plugged requests
1556 * @same_queue_rq: pointer to &struct request that gets filled in when
1557 * another request associated with @q is found on the plug list
1558 * (optional, may be %NULL)
1560 * Determine whether @bio being queued on @q can be merged with a request
1561 * on %current's plugged list. Returns %true if merge was successful,
1562 * otherwise %false.
1564 * Plugging coalesces IOs from the same issuer for the same purpose without
1565 * going through @q->queue_lock. As such it's more of an issuing mechanism
1566 * than scheduling, and the request, while may have elvpriv data, is not
1567 * added on the elevator at this point. In addition, we don't have
1568 * reliable access to the elevator outside queue lock. Only check basic
1569 * merging parameters without querying the elevator.
1571 * Caller must ensure !blk_queue_nomerges(q) beforehand.
1573 bool blk_attempt_plug_merge(struct request_queue *q, struct bio *bio,
1574 unsigned int *request_count,
1575 struct request **same_queue_rq)
1577 struct blk_plug *plug;
1578 struct request *rq;
1579 bool ret = false;
1580 struct list_head *plug_list;
1582 plug = current->plug;
1583 if (!plug)
1584 goto out;
1585 *request_count = 0;
1587 if (q->mq_ops)
1588 plug_list = &plug->mq_list;
1589 else
1590 plug_list = &plug->list;
1592 list_for_each_entry_reverse(rq, plug_list, queuelist) {
1593 int el_ret;
1595 if (rq->q == q) {
1596 (*request_count)++;
1598 * Only blk-mq multiple hardware queues case checks the
1599 * rq in the same queue, there should be only one such
1600 * rq in a queue
1602 if (same_queue_rq)
1603 *same_queue_rq = rq;
1606 if (rq->q != q || !blk_rq_merge_ok(rq, bio))
1607 continue;
1609 el_ret = blk_try_merge(rq, bio);
1610 if (el_ret == ELEVATOR_BACK_MERGE) {
1611 ret = bio_attempt_back_merge(q, rq, bio);
1612 if (ret)
1613 break;
1614 } else if (el_ret == ELEVATOR_FRONT_MERGE) {
1615 ret = bio_attempt_front_merge(q, rq, bio);
1616 if (ret)
1617 break;
1620 out:
1621 return ret;
1624 unsigned int blk_plug_queued_count(struct request_queue *q)
1626 struct blk_plug *plug;
1627 struct request *rq;
1628 struct list_head *plug_list;
1629 unsigned int ret = 0;
1631 plug = current->plug;
1632 if (!plug)
1633 goto out;
1635 if (q->mq_ops)
1636 plug_list = &plug->mq_list;
1637 else
1638 plug_list = &plug->list;
1640 list_for_each_entry(rq, plug_list, queuelist) {
1641 if (rq->q == q)
1642 ret++;
1644 out:
1645 return ret;
1648 void init_request_from_bio(struct request *req, struct bio *bio)
1650 req->cmd_type = REQ_TYPE_FS;
1652 req->cmd_flags |= bio->bi_opf & REQ_COMMON_MASK;
1653 if (bio->bi_opf & REQ_RAHEAD)
1654 req->cmd_flags |= REQ_FAILFAST_MASK;
1656 req->errors = 0;
1657 req->__sector = bio->bi_iter.bi_sector;
1658 req->ioprio = bio_prio(bio);
1659 blk_rq_bio_prep(req->q, req, bio);
1662 static blk_qc_t blk_queue_bio(struct request_queue *q, struct bio *bio)
1664 const bool sync = !!(bio->bi_opf & REQ_SYNC);
1665 struct blk_plug *plug;
1666 int el_ret, rw_flags = 0, where = ELEVATOR_INSERT_SORT;
1667 struct request *req;
1668 unsigned int request_count = 0;
1671 * low level driver can indicate that it wants pages above a
1672 * certain limit bounced to low memory (ie for highmem, or even
1673 * ISA dma in theory)
1675 blk_queue_bounce(q, &bio);
1677 blk_queue_split(q, &bio, q->bio_split);
1679 if (bio_integrity_enabled(bio) && bio_integrity_prep(bio)) {
1680 bio->bi_error = -EIO;
1681 bio_endio(bio);
1682 return BLK_QC_T_NONE;
1685 if (bio->bi_opf & (REQ_PREFLUSH | REQ_FUA)) {
1686 spin_lock_irq(q->queue_lock);
1687 where = ELEVATOR_INSERT_FLUSH;
1688 goto get_rq;
1692 * Check if we can merge with the plugged list before grabbing
1693 * any locks.
1695 if (!blk_queue_nomerges(q)) {
1696 if (blk_attempt_plug_merge(q, bio, &request_count, NULL))
1697 return BLK_QC_T_NONE;
1698 } else
1699 request_count = blk_plug_queued_count(q);
1701 spin_lock_irq(q->queue_lock);
1703 el_ret = elv_merge(q, &req, bio);
1704 if (el_ret == ELEVATOR_BACK_MERGE) {
1705 if (bio_attempt_back_merge(q, req, bio)) {
1706 elv_bio_merged(q, req, bio);
1707 if (!attempt_back_merge(q, req))
1708 elv_merged_request(q, req, el_ret);
1709 goto out_unlock;
1711 } else if (el_ret == ELEVATOR_FRONT_MERGE) {
1712 if (bio_attempt_front_merge(q, req, bio)) {
1713 elv_bio_merged(q, req, bio);
1714 if (!attempt_front_merge(q, req))
1715 elv_merged_request(q, req, el_ret);
1716 goto out_unlock;
1720 get_rq:
1722 * This sync check and mask will be re-done in init_request_from_bio(),
1723 * but we need to set it earlier to expose the sync flag to the
1724 * rq allocator and io schedulers.
1726 if (sync)
1727 rw_flags |= REQ_SYNC;
1730 * Add in META/PRIO flags, if set, before we get to the IO scheduler
1732 rw_flags |= (bio->bi_opf & (REQ_META | REQ_PRIO));
1735 * Grab a free request. This is might sleep but can not fail.
1736 * Returns with the queue unlocked.
1738 req = get_request(q, bio_data_dir(bio), rw_flags, bio, GFP_NOIO);
1739 if (IS_ERR(req)) {
1740 bio->bi_error = PTR_ERR(req);
1741 bio_endio(bio);
1742 goto out_unlock;
1746 * After dropping the lock and possibly sleeping here, our request
1747 * may now be mergeable after it had proven unmergeable (above).
1748 * We don't worry about that case for efficiency. It won't happen
1749 * often, and the elevators are able to handle it.
1751 init_request_from_bio(req, bio);
1753 if (test_bit(QUEUE_FLAG_SAME_COMP, &q->queue_flags))
1754 req->cpu = raw_smp_processor_id();
1756 plug = current->plug;
1757 if (plug) {
1759 * If this is the first request added after a plug, fire
1760 * of a plug trace.
1762 if (!request_count)
1763 trace_block_plug(q);
1764 else {
1765 if (request_count >= BLK_MAX_REQUEST_COUNT) {
1766 blk_flush_plug_list(plug, false);
1767 trace_block_plug(q);
1770 list_add_tail(&req->queuelist, &plug->list);
1771 blk_account_io_start(req, true);
1772 } else {
1773 spin_lock_irq(q->queue_lock);
1774 add_acct_request(q, req, where);
1775 __blk_run_queue(q);
1776 out_unlock:
1777 spin_unlock_irq(q->queue_lock);
1780 return BLK_QC_T_NONE;
1784 * If bio->bi_dev is a partition, remap the location
1786 static inline void blk_partition_remap(struct bio *bio)
1788 struct block_device *bdev = bio->bi_bdev;
1790 if (bio_sectors(bio) && bdev != bdev->bd_contains) {
1791 struct hd_struct *p = bdev->bd_part;
1793 bio->bi_iter.bi_sector += p->start_sect;
1794 bio->bi_bdev = bdev->bd_contains;
1796 trace_block_bio_remap(bdev_get_queue(bio->bi_bdev), bio,
1797 bdev->bd_dev,
1798 bio->bi_iter.bi_sector - p->start_sect);
1802 static void handle_bad_sector(struct bio *bio)
1804 char b[BDEVNAME_SIZE];
1806 printk(KERN_INFO "attempt to access beyond end of device\n");
1807 printk(KERN_INFO "%s: rw=%d, want=%Lu, limit=%Lu\n",
1808 bdevname(bio->bi_bdev, b),
1809 bio->bi_opf,
1810 (unsigned long long)bio_end_sector(bio),
1811 (long long)(i_size_read(bio->bi_bdev->bd_inode) >> 9));
1814 #ifdef CONFIG_FAIL_MAKE_REQUEST
1816 static DECLARE_FAULT_ATTR(fail_make_request);
1818 static int __init setup_fail_make_request(char *str)
1820 return setup_fault_attr(&fail_make_request, str);
1822 __setup("fail_make_request=", setup_fail_make_request);
1824 static bool should_fail_request(struct hd_struct *part, unsigned int bytes)
1826 return part->make_it_fail && should_fail(&fail_make_request, bytes);
1829 static int __init fail_make_request_debugfs(void)
1831 struct dentry *dir = fault_create_debugfs_attr("fail_make_request",
1832 NULL, &fail_make_request);
1834 return PTR_ERR_OR_ZERO(dir);
1837 late_initcall(fail_make_request_debugfs);
1839 #else /* CONFIG_FAIL_MAKE_REQUEST */
1841 static inline bool should_fail_request(struct hd_struct *part,
1842 unsigned int bytes)
1844 return false;
1847 #endif /* CONFIG_FAIL_MAKE_REQUEST */
1850 * Check whether this bio extends beyond the end of the device.
1852 static inline int bio_check_eod(struct bio *bio, unsigned int nr_sectors)
1854 sector_t maxsector;
1856 if (!nr_sectors)
1857 return 0;
1859 /* Test device or partition size, when known. */
1860 maxsector = i_size_read(bio->bi_bdev->bd_inode) >> 9;
1861 if (maxsector) {
1862 sector_t sector = bio->bi_iter.bi_sector;
1864 if (maxsector < nr_sectors || maxsector - nr_sectors < sector) {
1866 * This may well happen - the kernel calls bread()
1867 * without checking the size of the device, e.g., when
1868 * mounting a device.
1870 handle_bad_sector(bio);
1871 return 1;
1875 return 0;
1878 static noinline_for_stack bool
1879 generic_make_request_checks(struct bio *bio)
1881 struct request_queue *q;
1882 int nr_sectors = bio_sectors(bio);
1883 int err = -EIO;
1884 char b[BDEVNAME_SIZE];
1885 struct hd_struct *part;
1887 might_sleep();
1889 if (bio_check_eod(bio, nr_sectors))
1890 goto end_io;
1892 q = bdev_get_queue(bio->bi_bdev);
1893 if (unlikely(!q)) {
1894 printk(KERN_ERR
1895 "generic_make_request: Trying to access "
1896 "nonexistent block-device %s (%Lu)\n",
1897 bdevname(bio->bi_bdev, b),
1898 (long long) bio->bi_iter.bi_sector);
1899 goto end_io;
1902 part = bio->bi_bdev->bd_part;
1903 if (should_fail_request(part, bio->bi_iter.bi_size) ||
1904 should_fail_request(&part_to_disk(part)->part0,
1905 bio->bi_iter.bi_size))
1906 goto end_io;
1909 * If this device has partitions, remap block n
1910 * of partition p to block n+start(p) of the disk.
1912 blk_partition_remap(bio);
1914 if (bio_check_eod(bio, nr_sectors))
1915 goto end_io;
1918 * Filter flush bio's early so that make_request based
1919 * drivers without flush support don't have to worry
1920 * about them.
1922 if ((bio->bi_opf & (REQ_PREFLUSH | REQ_FUA)) &&
1923 !test_bit(QUEUE_FLAG_WC, &q->queue_flags)) {
1924 bio->bi_opf &= ~(REQ_PREFLUSH | REQ_FUA);
1925 if (!nr_sectors) {
1926 err = 0;
1927 goto end_io;
1931 switch (bio_op(bio)) {
1932 case REQ_OP_DISCARD:
1933 if (!blk_queue_discard(q))
1934 goto not_supported;
1935 break;
1936 case REQ_OP_SECURE_ERASE:
1937 if (!blk_queue_secure_erase(q))
1938 goto not_supported;
1939 break;
1940 case REQ_OP_WRITE_SAME:
1941 if (!bdev_write_same(bio->bi_bdev))
1942 goto not_supported;
1943 break;
1944 default:
1945 break;
1949 * Various block parts want %current->io_context and lazy ioc
1950 * allocation ends up trading a lot of pain for a small amount of
1951 * memory. Just allocate it upfront. This may fail and block
1952 * layer knows how to live with it.
1954 create_io_context(GFP_ATOMIC, q->node);
1956 if (!blkcg_bio_issue_check(q, bio))
1957 return false;
1959 trace_block_bio_queue(q, bio);
1960 return true;
1962 not_supported:
1963 err = -EOPNOTSUPP;
1964 end_io:
1965 bio->bi_error = err;
1966 bio_endio(bio);
1967 return false;
1971 * generic_make_request - hand a buffer to its device driver for I/O
1972 * @bio: The bio describing the location in memory and on the device.
1974 * generic_make_request() is used to make I/O requests of block
1975 * devices. It is passed a &struct bio, which describes the I/O that needs
1976 * to be done.
1978 * generic_make_request() does not return any status. The
1979 * success/failure status of the request, along with notification of
1980 * completion, is delivered asynchronously through the bio->bi_end_io
1981 * function described (one day) else where.
1983 * The caller of generic_make_request must make sure that bi_io_vec
1984 * are set to describe the memory buffer, and that bi_dev and bi_sector are
1985 * set to describe the device address, and the
1986 * bi_end_io and optionally bi_private are set to describe how
1987 * completion notification should be signaled.
1989 * generic_make_request and the drivers it calls may use bi_next if this
1990 * bio happens to be merged with someone else, and may resubmit the bio to
1991 * a lower device by calling into generic_make_request recursively, which
1992 * means the bio should NOT be touched after the call to ->make_request_fn.
1994 blk_qc_t generic_make_request(struct bio *bio)
1997 * bio_list_on_stack[0] contains bios submitted by the current
1998 * make_request_fn.
1999 * bio_list_on_stack[1] contains bios that were submitted before
2000 * the current make_request_fn, but that haven't been processed
2001 * yet.
2003 struct bio_list bio_list_on_stack[2];
2004 blk_qc_t ret = BLK_QC_T_NONE;
2006 if (!generic_make_request_checks(bio))
2007 goto out;
2010 * We only want one ->make_request_fn to be active at a time, else
2011 * stack usage with stacked devices could be a problem. So use
2012 * current->bio_list to keep a list of requests submited by a
2013 * make_request_fn function. current->bio_list is also used as a
2014 * flag to say if generic_make_request is currently active in this
2015 * task or not. If it is NULL, then no make_request is active. If
2016 * it is non-NULL, then a make_request is active, and new requests
2017 * should be added at the tail
2019 if (current->bio_list) {
2020 bio_list_add(&current->bio_list[0], bio);
2021 goto out;
2024 /* following loop may be a bit non-obvious, and so deserves some
2025 * explanation.
2026 * Before entering the loop, bio->bi_next is NULL (as all callers
2027 * ensure that) so we have a list with a single bio.
2028 * We pretend that we have just taken it off a longer list, so
2029 * we assign bio_list to a pointer to the bio_list_on_stack,
2030 * thus initialising the bio_list of new bios to be
2031 * added. ->make_request() may indeed add some more bios
2032 * through a recursive call to generic_make_request. If it
2033 * did, we find a non-NULL value in bio_list and re-enter the loop
2034 * from the top. In this case we really did just take the bio
2035 * of the top of the list (no pretending) and so remove it from
2036 * bio_list, and call into ->make_request() again.
2038 BUG_ON(bio->bi_next);
2039 bio_list_init(&bio_list_on_stack[0]);
2040 current->bio_list = bio_list_on_stack;
2041 do {
2042 struct request_queue *q = bdev_get_queue(bio->bi_bdev);
2044 if (likely(blk_queue_enter(q, false) == 0)) {
2045 struct bio_list lower, same;
2047 /* Create a fresh bio_list for all subordinate requests */
2048 bio_list_on_stack[1] = bio_list_on_stack[0];
2049 bio_list_init(&bio_list_on_stack[0]);
2050 ret = q->make_request_fn(q, bio);
2052 blk_queue_exit(q);
2054 /* sort new bios into those for a lower level
2055 * and those for the same level
2057 bio_list_init(&lower);
2058 bio_list_init(&same);
2059 while ((bio = bio_list_pop(&bio_list_on_stack[0])) != NULL)
2060 if (q == bdev_get_queue(bio->bi_bdev))
2061 bio_list_add(&same, bio);
2062 else
2063 bio_list_add(&lower, bio);
2064 /* now assemble so we handle the lowest level first */
2065 bio_list_merge(&bio_list_on_stack[0], &lower);
2066 bio_list_merge(&bio_list_on_stack[0], &same);
2067 bio_list_merge(&bio_list_on_stack[0], &bio_list_on_stack[1]);
2068 } else {
2069 bio_io_error(bio);
2071 bio = bio_list_pop(&bio_list_on_stack[0]);
2072 } while (bio);
2073 current->bio_list = NULL; /* deactivate */
2075 out:
2076 return ret;
2078 EXPORT_SYMBOL(generic_make_request);
2081 * submit_bio - submit a bio to the block device layer for I/O
2082 * @bio: The &struct bio which describes the I/O
2084 * submit_bio() is very similar in purpose to generic_make_request(), and
2085 * uses that function to do most of the work. Both are fairly rough
2086 * interfaces; @bio must be presetup and ready for I/O.
2089 blk_qc_t submit_bio(struct bio *bio)
2092 * If it's a regular read/write or a barrier with data attached,
2093 * go through the normal accounting stuff before submission.
2095 if (bio_has_data(bio)) {
2096 unsigned int count;
2098 if (unlikely(bio_op(bio) == REQ_OP_WRITE_SAME))
2099 count = bdev_logical_block_size(bio->bi_bdev) >> 9;
2100 else
2101 count = bio_sectors(bio);
2103 if (op_is_write(bio_op(bio))) {
2104 count_vm_events(PGPGOUT, count);
2105 } else {
2106 task_io_account_read(bio->bi_iter.bi_size);
2107 count_vm_events(PGPGIN, count);
2110 if (unlikely(block_dump)) {
2111 char b[BDEVNAME_SIZE];
2112 printk(KERN_DEBUG "%s(%d): %s block %Lu on %s (%u sectors)\n",
2113 current->comm, task_pid_nr(current),
2114 op_is_write(bio_op(bio)) ? "WRITE" : "READ",
2115 (unsigned long long)bio->bi_iter.bi_sector,
2116 bdevname(bio->bi_bdev, b),
2117 count);
2121 return generic_make_request(bio);
2123 EXPORT_SYMBOL(submit_bio);
2126 * blk_cloned_rq_check_limits - Helper function to check a cloned request
2127 * for new the queue limits
2128 * @q: the queue
2129 * @rq: the request being checked
2131 * Description:
2132 * @rq may have been made based on weaker limitations of upper-level queues
2133 * in request stacking drivers, and it may violate the limitation of @q.
2134 * Since the block layer and the underlying device driver trust @rq
2135 * after it is inserted to @q, it should be checked against @q before
2136 * the insertion using this generic function.
2138 * Request stacking drivers like request-based dm may change the queue
2139 * limits when retrying requests on other queues. Those requests need
2140 * to be checked against the new queue limits again during dispatch.
2142 static int blk_cloned_rq_check_limits(struct request_queue *q,
2143 struct request *rq)
2145 if (blk_rq_sectors(rq) > blk_queue_get_max_sectors(q, req_op(rq))) {
2146 printk(KERN_ERR "%s: over max size limit.\n", __func__);
2147 return -EIO;
2151 * queue's settings related to segment counting like q->bounce_pfn
2152 * may differ from that of other stacking queues.
2153 * Recalculate it to check the request correctly on this queue's
2154 * limitation.
2156 blk_recalc_rq_segments(rq);
2157 if (rq->nr_phys_segments > queue_max_segments(q)) {
2158 printk(KERN_ERR "%s: over max segments limit.\n", __func__);
2159 return -EIO;
2162 return 0;
2166 * blk_insert_cloned_request - Helper for stacking drivers to submit a request
2167 * @q: the queue to submit the request
2168 * @rq: the request being queued
2170 int blk_insert_cloned_request(struct request_queue *q, struct request *rq)
2172 unsigned long flags;
2173 int where = ELEVATOR_INSERT_BACK;
2175 if (blk_cloned_rq_check_limits(q, rq))
2176 return -EIO;
2178 if (rq->rq_disk &&
2179 should_fail_request(&rq->rq_disk->part0, blk_rq_bytes(rq)))
2180 return -EIO;
2182 if (q->mq_ops) {
2183 if (blk_queue_io_stat(q))
2184 blk_account_io_start(rq, true);
2185 blk_mq_insert_request(rq, false, true, false);
2186 return 0;
2189 spin_lock_irqsave(q->queue_lock, flags);
2190 if (unlikely(blk_queue_dying(q))) {
2191 spin_unlock_irqrestore(q->queue_lock, flags);
2192 return -ENODEV;
2196 * Submitting request must be dequeued before calling this function
2197 * because it will be linked to another request_queue
2199 BUG_ON(blk_queued_rq(rq));
2201 if (rq->cmd_flags & (REQ_PREFLUSH | REQ_FUA))
2202 where = ELEVATOR_INSERT_FLUSH;
2204 add_acct_request(q, rq, where);
2205 if (where == ELEVATOR_INSERT_FLUSH)
2206 __blk_run_queue(q);
2207 spin_unlock_irqrestore(q->queue_lock, flags);
2209 return 0;
2211 EXPORT_SYMBOL_GPL(blk_insert_cloned_request);
2214 * blk_rq_err_bytes - determine number of bytes till the next failure boundary
2215 * @rq: request to examine
2217 * Description:
2218 * A request could be merge of IOs which require different failure
2219 * handling. This function determines the number of bytes which
2220 * can be failed from the beginning of the request without
2221 * crossing into area which need to be retried further.
2223 * Return:
2224 * The number of bytes to fail.
2226 * Context:
2227 * queue_lock must be held.
2229 unsigned int blk_rq_err_bytes(const struct request *rq)
2231 unsigned int ff = rq->cmd_flags & REQ_FAILFAST_MASK;
2232 unsigned int bytes = 0;
2233 struct bio *bio;
2235 if (!(rq->cmd_flags & REQ_MIXED_MERGE))
2236 return blk_rq_bytes(rq);
2239 * Currently the only 'mixing' which can happen is between
2240 * different fastfail types. We can safely fail portions
2241 * which have all the failfast bits that the first one has -
2242 * the ones which are at least as eager to fail as the first
2243 * one.
2245 for (bio = rq->bio; bio; bio = bio->bi_next) {
2246 if ((bio->bi_opf & ff) != ff)
2247 break;
2248 bytes += bio->bi_iter.bi_size;
2251 /* this could lead to infinite loop */
2252 BUG_ON(blk_rq_bytes(rq) && !bytes);
2253 return bytes;
2255 EXPORT_SYMBOL_GPL(blk_rq_err_bytes);
2257 void blk_account_io_completion(struct request *req, unsigned int bytes)
2259 if (blk_do_io_stat(req)) {
2260 const int rw = rq_data_dir(req);
2261 struct hd_struct *part;
2262 int cpu;
2264 cpu = part_stat_lock();
2265 part = req->part;
2266 part_stat_add(cpu, part, sectors[rw], bytes >> 9);
2267 part_stat_unlock();
2271 void blk_account_io_done(struct request *req)
2274 * Account IO completion. flush_rq isn't accounted as a
2275 * normal IO on queueing nor completion. Accounting the
2276 * containing request is enough.
2278 if (blk_do_io_stat(req) && !(req->cmd_flags & REQ_FLUSH_SEQ)) {
2279 unsigned long duration = jiffies - req->start_time;
2280 const int rw = rq_data_dir(req);
2281 struct hd_struct *part;
2282 int cpu;
2284 cpu = part_stat_lock();
2285 part = req->part;
2287 part_stat_inc(cpu, part, ios[rw]);
2288 part_stat_add(cpu, part, ticks[rw], duration);
2289 part_round_stats(cpu, part);
2290 part_dec_in_flight(part, rw);
2292 hd_struct_put(part);
2293 part_stat_unlock();
2297 #ifdef CONFIG_PM
2299 * Don't process normal requests when queue is suspended
2300 * or in the process of suspending/resuming
2302 static struct request *blk_pm_peek_request(struct request_queue *q,
2303 struct request *rq)
2305 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
2306 (q->rpm_status != RPM_ACTIVE && !(rq->cmd_flags & REQ_PM))))
2307 return NULL;
2308 else
2309 return rq;
2311 #else
2312 static inline struct request *blk_pm_peek_request(struct request_queue *q,
2313 struct request *rq)
2315 return rq;
2317 #endif
2319 void blk_account_io_start(struct request *rq, bool new_io)
2321 struct hd_struct *part;
2322 int rw = rq_data_dir(rq);
2323 int cpu;
2325 if (!blk_do_io_stat(rq))
2326 return;
2328 cpu = part_stat_lock();
2330 if (!new_io) {
2331 part = rq->part;
2332 part_stat_inc(cpu, part, merges[rw]);
2333 } else {
2334 part = disk_map_sector_rcu(rq->rq_disk, blk_rq_pos(rq));
2335 if (!hd_struct_try_get(part)) {
2337 * The partition is already being removed,
2338 * the request will be accounted on the disk only
2340 * We take a reference on disk->part0 although that
2341 * partition will never be deleted, so we can treat
2342 * it as any other partition.
2344 part = &rq->rq_disk->part0;
2345 hd_struct_get(part);
2347 part_round_stats(cpu, part);
2348 part_inc_in_flight(part, rw);
2349 rq->part = part;
2352 part_stat_unlock();
2356 * blk_peek_request - peek at the top of a request queue
2357 * @q: request queue to peek at
2359 * Description:
2360 * Return the request at the top of @q. The returned request
2361 * should be started using blk_start_request() before LLD starts
2362 * processing it.
2364 * Return:
2365 * Pointer to the request at the top of @q if available. Null
2366 * otherwise.
2368 * Context:
2369 * queue_lock must be held.
2371 struct request *blk_peek_request(struct request_queue *q)
2373 struct request *rq;
2374 int ret;
2376 while ((rq = __elv_next_request(q)) != NULL) {
2378 rq = blk_pm_peek_request(q, rq);
2379 if (!rq)
2380 break;
2382 if (!(rq->cmd_flags & REQ_STARTED)) {
2384 * This is the first time the device driver
2385 * sees this request (possibly after
2386 * requeueing). Notify IO scheduler.
2388 if (rq->cmd_flags & REQ_SORTED)
2389 elv_activate_rq(q, rq);
2392 * just mark as started even if we don't start
2393 * it, a request that has been delayed should
2394 * not be passed by new incoming requests
2396 rq->cmd_flags |= REQ_STARTED;
2397 trace_block_rq_issue(q, rq);
2400 if (!q->boundary_rq || q->boundary_rq == rq) {
2401 q->end_sector = rq_end_sector(rq);
2402 q->boundary_rq = NULL;
2405 if (rq->cmd_flags & REQ_DONTPREP)
2406 break;
2408 if (q->dma_drain_size && blk_rq_bytes(rq)) {
2410 * make sure space for the drain appears we
2411 * know we can do this because max_hw_segments
2412 * has been adjusted to be one fewer than the
2413 * device can handle
2415 rq->nr_phys_segments++;
2418 if (!q->prep_rq_fn)
2419 break;
2421 ret = q->prep_rq_fn(q, rq);
2422 if (ret == BLKPREP_OK) {
2423 break;
2424 } else if (ret == BLKPREP_DEFER) {
2426 * the request may have been (partially) prepped.
2427 * we need to keep this request in the front to
2428 * avoid resource deadlock. REQ_STARTED will
2429 * prevent other fs requests from passing this one.
2431 if (q->dma_drain_size && blk_rq_bytes(rq) &&
2432 !(rq->cmd_flags & REQ_DONTPREP)) {
2434 * remove the space for the drain we added
2435 * so that we don't add it again
2437 --rq->nr_phys_segments;
2440 rq = NULL;
2441 break;
2442 } else if (ret == BLKPREP_KILL || ret == BLKPREP_INVALID) {
2443 int err = (ret == BLKPREP_INVALID) ? -EREMOTEIO : -EIO;
2445 rq->cmd_flags |= REQ_QUIET;
2447 * Mark this request as started so we don't trigger
2448 * any debug logic in the end I/O path.
2450 blk_start_request(rq);
2451 __blk_end_request_all(rq, err);
2452 } else {
2453 printk(KERN_ERR "%s: bad return=%d\n", __func__, ret);
2454 break;
2458 return rq;
2460 EXPORT_SYMBOL(blk_peek_request);
2462 void blk_dequeue_request(struct request *rq)
2464 struct request_queue *q = rq->q;
2466 BUG_ON(list_empty(&rq->queuelist));
2467 BUG_ON(ELV_ON_HASH(rq));
2469 list_del_init(&rq->queuelist);
2472 * the time frame between a request being removed from the lists
2473 * and to it is freed is accounted as io that is in progress at
2474 * the driver side.
2476 if (blk_account_rq(rq)) {
2477 q->in_flight[rq_is_sync(rq)]++;
2478 set_io_start_time_ns(rq);
2483 * blk_start_request - start request processing on the driver
2484 * @req: request to dequeue
2486 * Description:
2487 * Dequeue @req and start timeout timer on it. This hands off the
2488 * request to the driver.
2490 * Block internal functions which don't want to start timer should
2491 * call blk_dequeue_request().
2493 * Context:
2494 * queue_lock must be held.
2496 void blk_start_request(struct request *req)
2498 blk_dequeue_request(req);
2501 * We are now handing the request to the hardware, initialize
2502 * resid_len to full count and add the timeout handler.
2504 req->resid_len = blk_rq_bytes(req);
2505 if (unlikely(blk_bidi_rq(req)))
2506 req->next_rq->resid_len = blk_rq_bytes(req->next_rq);
2508 BUG_ON(test_bit(REQ_ATOM_COMPLETE, &req->atomic_flags));
2509 blk_add_timer(req);
2511 EXPORT_SYMBOL(blk_start_request);
2514 * blk_fetch_request - fetch a request from a request queue
2515 * @q: request queue to fetch a request from
2517 * Description:
2518 * Return the request at the top of @q. The request is started on
2519 * return and LLD can start processing it immediately.
2521 * Return:
2522 * Pointer to the request at the top of @q if available. Null
2523 * otherwise.
2525 * Context:
2526 * queue_lock must be held.
2528 struct request *blk_fetch_request(struct request_queue *q)
2530 struct request *rq;
2532 rq = blk_peek_request(q);
2533 if (rq)
2534 blk_start_request(rq);
2535 return rq;
2537 EXPORT_SYMBOL(blk_fetch_request);
2540 * blk_update_request - Special helper function for request stacking drivers
2541 * @req: the request being processed
2542 * @error: %0 for success, < %0 for error
2543 * @nr_bytes: number of bytes to complete @req
2545 * Description:
2546 * Ends I/O on a number of bytes attached to @req, but doesn't complete
2547 * the request structure even if @req doesn't have leftover.
2548 * If @req has leftover, sets it up for the next range of segments.
2550 * This special helper function is only for request stacking drivers
2551 * (e.g. request-based dm) so that they can handle partial completion.
2552 * Actual device drivers should use blk_end_request instead.
2554 * Passing the result of blk_rq_bytes() as @nr_bytes guarantees
2555 * %false return from this function.
2557 * Return:
2558 * %false - this request doesn't have any more data
2559 * %true - this request has more data
2561 bool blk_update_request(struct request *req, int error, unsigned int nr_bytes)
2563 int total_bytes;
2565 trace_block_rq_complete(req->q, req, nr_bytes);
2567 if (!req->bio)
2568 return false;
2571 * For fs requests, rq is just carrier of independent bio's
2572 * and each partial completion should be handled separately.
2573 * Reset per-request error on each partial completion.
2575 * TODO: tj: This is too subtle. It would be better to let
2576 * low level drivers do what they see fit.
2578 if (req->cmd_type == REQ_TYPE_FS)
2579 req->errors = 0;
2581 if (error && req->cmd_type == REQ_TYPE_FS &&
2582 !(req->cmd_flags & REQ_QUIET)) {
2583 char *error_type;
2585 switch (error) {
2586 case -ENOLINK:
2587 error_type = "recoverable transport";
2588 break;
2589 case -EREMOTEIO:
2590 error_type = "critical target";
2591 break;
2592 case -EBADE:
2593 error_type = "critical nexus";
2594 break;
2595 case -ETIMEDOUT:
2596 error_type = "timeout";
2597 break;
2598 case -ENOSPC:
2599 error_type = "critical space allocation";
2600 break;
2601 case -ENODATA:
2602 error_type = "critical medium";
2603 break;
2604 case -EIO:
2605 default:
2606 error_type = "I/O";
2607 break;
2609 printk_ratelimited(KERN_ERR "%s: %s error, dev %s, sector %llu\n",
2610 __func__, error_type, req->rq_disk ?
2611 req->rq_disk->disk_name : "?",
2612 (unsigned long long)blk_rq_pos(req));
2616 blk_account_io_completion(req, nr_bytes);
2618 total_bytes = 0;
2619 while (req->bio) {
2620 struct bio *bio = req->bio;
2621 unsigned bio_bytes = min(bio->bi_iter.bi_size, nr_bytes);
2623 if (bio_bytes == bio->bi_iter.bi_size)
2624 req->bio = bio->bi_next;
2626 req_bio_endio(req, bio, bio_bytes, error);
2628 total_bytes += bio_bytes;
2629 nr_bytes -= bio_bytes;
2631 if (!nr_bytes)
2632 break;
2636 * completely done
2638 if (!req->bio) {
2640 * Reset counters so that the request stacking driver
2641 * can find how many bytes remain in the request
2642 * later.
2644 req->__data_len = 0;
2645 return false;
2648 req->__data_len -= total_bytes;
2650 /* update sector only for requests with clear definition of sector */
2651 if (req->cmd_type == REQ_TYPE_FS)
2652 req->__sector += total_bytes >> 9;
2654 /* mixed attributes always follow the first bio */
2655 if (req->cmd_flags & REQ_MIXED_MERGE) {
2656 req->cmd_flags &= ~REQ_FAILFAST_MASK;
2657 req->cmd_flags |= req->bio->bi_opf & REQ_FAILFAST_MASK;
2661 * If total number of sectors is less than the first segment
2662 * size, something has gone terribly wrong.
2664 if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {
2665 blk_dump_rq_flags(req, "request botched");
2666 req->__data_len = blk_rq_cur_bytes(req);
2669 /* recalculate the number of segments */
2670 blk_recalc_rq_segments(req);
2672 return true;
2674 EXPORT_SYMBOL_GPL(blk_update_request);
2676 static bool blk_update_bidi_request(struct request *rq, int error,
2677 unsigned int nr_bytes,
2678 unsigned int bidi_bytes)
2680 if (blk_update_request(rq, error, nr_bytes))
2681 return true;
2683 /* Bidi request must be completed as a whole */
2684 if (unlikely(blk_bidi_rq(rq)) &&
2685 blk_update_request(rq->next_rq, error, bidi_bytes))
2686 return true;
2688 if (blk_queue_add_random(rq->q))
2689 add_disk_randomness(rq->rq_disk);
2691 return false;
2695 * blk_unprep_request - unprepare a request
2696 * @req: the request
2698 * This function makes a request ready for complete resubmission (or
2699 * completion). It happens only after all error handling is complete,
2700 * so represents the appropriate moment to deallocate any resources
2701 * that were allocated to the request in the prep_rq_fn. The queue
2702 * lock is held when calling this.
2704 void blk_unprep_request(struct request *req)
2706 struct request_queue *q = req->q;
2708 req->cmd_flags &= ~REQ_DONTPREP;
2709 if (q->unprep_rq_fn)
2710 q->unprep_rq_fn(q, req);
2712 EXPORT_SYMBOL_GPL(blk_unprep_request);
2715 * queue lock must be held
2717 void blk_finish_request(struct request *req, int error)
2719 if (req->cmd_flags & REQ_QUEUED)
2720 blk_queue_end_tag(req->q, req);
2722 BUG_ON(blk_queued_rq(req));
2724 if (unlikely(laptop_mode) && req->cmd_type == REQ_TYPE_FS)
2725 laptop_io_completion(&req->q->backing_dev_info);
2727 blk_delete_timer(req);
2729 if (req->cmd_flags & REQ_DONTPREP)
2730 blk_unprep_request(req);
2732 blk_account_io_done(req);
2734 if (req->end_io)
2735 req->end_io(req, error);
2736 else {
2737 if (blk_bidi_rq(req))
2738 __blk_put_request(req->next_rq->q, req->next_rq);
2740 __blk_put_request(req->q, req);
2743 EXPORT_SYMBOL(blk_finish_request);
2746 * blk_end_bidi_request - Complete a bidi request
2747 * @rq: the request to complete
2748 * @error: %0 for success, < %0 for error
2749 * @nr_bytes: number of bytes to complete @rq
2750 * @bidi_bytes: number of bytes to complete @rq->next_rq
2752 * Description:
2753 * Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
2754 * Drivers that supports bidi can safely call this member for any
2755 * type of request, bidi or uni. In the later case @bidi_bytes is
2756 * just ignored.
2758 * Return:
2759 * %false - we are done with this request
2760 * %true - still buffers pending for this request
2762 static bool blk_end_bidi_request(struct request *rq, int error,
2763 unsigned int nr_bytes, unsigned int bidi_bytes)
2765 struct request_queue *q = rq->q;
2766 unsigned long flags;
2768 if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2769 return true;
2771 spin_lock_irqsave(q->queue_lock, flags);
2772 blk_finish_request(rq, error);
2773 spin_unlock_irqrestore(q->queue_lock, flags);
2775 return false;
2779 * __blk_end_bidi_request - Complete a bidi request with queue lock held
2780 * @rq: the request to complete
2781 * @error: %0 for success, < %0 for error
2782 * @nr_bytes: number of bytes to complete @rq
2783 * @bidi_bytes: number of bytes to complete @rq->next_rq
2785 * Description:
2786 * Identical to blk_end_bidi_request() except that queue lock is
2787 * assumed to be locked on entry and remains so on return.
2789 * Return:
2790 * %false - we are done with this request
2791 * %true - still buffers pending for this request
2793 bool __blk_end_bidi_request(struct request *rq, int error,
2794 unsigned int nr_bytes, unsigned int bidi_bytes)
2796 if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2797 return true;
2799 blk_finish_request(rq, error);
2801 return false;
2805 * blk_end_request - Helper function for drivers to complete the request.
2806 * @rq: the request being processed
2807 * @error: %0 for success, < %0 for error
2808 * @nr_bytes: number of bytes to complete
2810 * Description:
2811 * Ends I/O on a number of bytes attached to @rq.
2812 * If @rq has leftover, sets it up for the next range of segments.
2814 * Return:
2815 * %false - we are done with this request
2816 * %true - still buffers pending for this request
2818 bool blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
2820 return blk_end_bidi_request(rq, error, nr_bytes, 0);
2822 EXPORT_SYMBOL(blk_end_request);
2825 * blk_end_request_all - Helper function for drives to finish the request.
2826 * @rq: the request to finish
2827 * @error: %0 for success, < %0 for error
2829 * Description:
2830 * Completely finish @rq.
2832 void blk_end_request_all(struct request *rq, int error)
2834 bool pending;
2835 unsigned int bidi_bytes = 0;
2837 if (unlikely(blk_bidi_rq(rq)))
2838 bidi_bytes = blk_rq_bytes(rq->next_rq);
2840 pending = blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2841 BUG_ON(pending);
2843 EXPORT_SYMBOL(blk_end_request_all);
2846 * blk_end_request_cur - Helper function to finish the current request chunk.
2847 * @rq: the request to finish the current chunk for
2848 * @error: %0 for success, < %0 for error
2850 * Description:
2851 * Complete the current consecutively mapped chunk from @rq.
2853 * Return:
2854 * %false - we are done with this request
2855 * %true - still buffers pending for this request
2857 bool blk_end_request_cur(struct request *rq, int error)
2859 return blk_end_request(rq, error, blk_rq_cur_bytes(rq));
2861 EXPORT_SYMBOL(blk_end_request_cur);
2864 * blk_end_request_err - Finish a request till the next failure boundary.
2865 * @rq: the request to finish till the next failure boundary for
2866 * @error: must be negative errno
2868 * Description:
2869 * Complete @rq till the next failure boundary.
2871 * Return:
2872 * %false - we are done with this request
2873 * %true - still buffers pending for this request
2875 bool blk_end_request_err(struct request *rq, int error)
2877 WARN_ON(error >= 0);
2878 return blk_end_request(rq, error, blk_rq_err_bytes(rq));
2880 EXPORT_SYMBOL_GPL(blk_end_request_err);
2883 * __blk_end_request - Helper function for drivers to complete the request.
2884 * @rq: the request being processed
2885 * @error: %0 for success, < %0 for error
2886 * @nr_bytes: number of bytes to complete
2888 * Description:
2889 * Must be called with queue lock held unlike blk_end_request().
2891 * Return:
2892 * %false - we are done with this request
2893 * %true - still buffers pending for this request
2895 bool __blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
2897 return __blk_end_bidi_request(rq, error, nr_bytes, 0);
2899 EXPORT_SYMBOL(__blk_end_request);
2902 * __blk_end_request_all - Helper function for drives to finish the request.
2903 * @rq: the request to finish
2904 * @error: %0 for success, < %0 for error
2906 * Description:
2907 * Completely finish @rq. Must be called with queue lock held.
2909 void __blk_end_request_all(struct request *rq, int error)
2911 bool pending;
2912 unsigned int bidi_bytes = 0;
2914 if (unlikely(blk_bidi_rq(rq)))
2915 bidi_bytes = blk_rq_bytes(rq->next_rq);
2917 pending = __blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2918 BUG_ON(pending);
2920 EXPORT_SYMBOL(__blk_end_request_all);
2923 * __blk_end_request_cur - Helper function to finish the current request chunk.
2924 * @rq: the request to finish the current chunk for
2925 * @error: %0 for success, < %0 for error
2927 * Description:
2928 * Complete the current consecutively mapped chunk from @rq. Must
2929 * be called with queue lock held.
2931 * Return:
2932 * %false - we are done with this request
2933 * %true - still buffers pending for this request
2935 bool __blk_end_request_cur(struct request *rq, int error)
2937 return __blk_end_request(rq, error, blk_rq_cur_bytes(rq));
2939 EXPORT_SYMBOL(__blk_end_request_cur);
2942 * __blk_end_request_err - Finish a request till the next failure boundary.
2943 * @rq: the request to finish till the next failure boundary for
2944 * @error: must be negative errno
2946 * Description:
2947 * Complete @rq till the next failure boundary. Must be called
2948 * with queue lock held.
2950 * Return:
2951 * %false - we are done with this request
2952 * %true - still buffers pending for this request
2954 bool __blk_end_request_err(struct request *rq, int error)
2956 WARN_ON(error >= 0);
2957 return __blk_end_request(rq, error, blk_rq_err_bytes(rq));
2959 EXPORT_SYMBOL_GPL(__blk_end_request_err);
2961 void blk_rq_bio_prep(struct request_queue *q, struct request *rq,
2962 struct bio *bio)
2964 req_set_op(rq, bio_op(bio));
2966 if (bio_has_data(bio))
2967 rq->nr_phys_segments = bio_phys_segments(q, bio);
2969 rq->__data_len = bio->bi_iter.bi_size;
2970 rq->bio = rq->biotail = bio;
2972 if (bio->bi_bdev)
2973 rq->rq_disk = bio->bi_bdev->bd_disk;
2976 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE
2978 * rq_flush_dcache_pages - Helper function to flush all pages in a request
2979 * @rq: the request to be flushed
2981 * Description:
2982 * Flush all pages in @rq.
2984 void rq_flush_dcache_pages(struct request *rq)
2986 struct req_iterator iter;
2987 struct bio_vec bvec;
2989 rq_for_each_segment(bvec, rq, iter)
2990 flush_dcache_page(bvec.bv_page);
2992 EXPORT_SYMBOL_GPL(rq_flush_dcache_pages);
2993 #endif
2996 * blk_lld_busy - Check if underlying low-level drivers of a device are busy
2997 * @q : the queue of the device being checked
2999 * Description:
3000 * Check if underlying low-level drivers of a device are busy.
3001 * If the drivers want to export their busy state, they must set own
3002 * exporting function using blk_queue_lld_busy() first.
3004 * Basically, this function is used only by request stacking drivers
3005 * to stop dispatching requests to underlying devices when underlying
3006 * devices are busy. This behavior helps more I/O merging on the queue
3007 * of the request stacking driver and prevents I/O throughput regression
3008 * on burst I/O load.
3010 * Return:
3011 * 0 - Not busy (The request stacking driver should dispatch request)
3012 * 1 - Busy (The request stacking driver should stop dispatching request)
3014 int blk_lld_busy(struct request_queue *q)
3016 if (q->lld_busy_fn)
3017 return q->lld_busy_fn(q);
3019 return 0;
3021 EXPORT_SYMBOL_GPL(blk_lld_busy);
3024 * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
3025 * @rq: the clone request to be cleaned up
3027 * Description:
3028 * Free all bios in @rq for a cloned request.
3030 void blk_rq_unprep_clone(struct request *rq)
3032 struct bio *bio;
3034 while ((bio = rq->bio) != NULL) {
3035 rq->bio = bio->bi_next;
3037 bio_put(bio);
3040 EXPORT_SYMBOL_GPL(blk_rq_unprep_clone);
3043 * Copy attributes of the original request to the clone request.
3044 * The actual data parts (e.g. ->cmd, ->sense) are not copied.
3046 static void __blk_rq_prep_clone(struct request *dst, struct request *src)
3048 dst->cpu = src->cpu;
3049 req_set_op_attrs(dst, req_op(src),
3050 (src->cmd_flags & REQ_CLONE_MASK) | REQ_NOMERGE);
3051 dst->cmd_type = src->cmd_type;
3052 dst->__sector = blk_rq_pos(src);
3053 dst->__data_len = blk_rq_bytes(src);
3054 dst->nr_phys_segments = src->nr_phys_segments;
3055 dst->ioprio = src->ioprio;
3056 dst->extra_len = src->extra_len;
3060 * blk_rq_prep_clone - Helper function to setup clone request
3061 * @rq: the request to be setup
3062 * @rq_src: original request to be cloned
3063 * @bs: bio_set that bios for clone are allocated from
3064 * @gfp_mask: memory allocation mask for bio
3065 * @bio_ctr: setup function to be called for each clone bio.
3066 * Returns %0 for success, non %0 for failure.
3067 * @data: private data to be passed to @bio_ctr
3069 * Description:
3070 * Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
3071 * The actual data parts of @rq_src (e.g. ->cmd, ->sense)
3072 * are not copied, and copying such parts is the caller's responsibility.
3073 * Also, pages which the original bios are pointing to are not copied
3074 * and the cloned bios just point same pages.
3075 * So cloned bios must be completed before original bios, which means
3076 * the caller must complete @rq before @rq_src.
3078 int blk_rq_prep_clone(struct request *rq, struct request *rq_src,
3079 struct bio_set *bs, gfp_t gfp_mask,
3080 int (*bio_ctr)(struct bio *, struct bio *, void *),
3081 void *data)
3083 struct bio *bio, *bio_src;
3085 if (!bs)
3086 bs = fs_bio_set;
3088 __rq_for_each_bio(bio_src, rq_src) {
3089 bio = bio_clone_fast(bio_src, gfp_mask, bs);
3090 if (!bio)
3091 goto free_and_out;
3093 if (bio_ctr && bio_ctr(bio, bio_src, data))
3094 goto free_and_out;
3096 if (rq->bio) {
3097 rq->biotail->bi_next = bio;
3098 rq->biotail = bio;
3099 } else
3100 rq->bio = rq->biotail = bio;
3103 __blk_rq_prep_clone(rq, rq_src);
3105 return 0;
3107 free_and_out:
3108 if (bio)
3109 bio_put(bio);
3110 blk_rq_unprep_clone(rq);
3112 return -ENOMEM;
3114 EXPORT_SYMBOL_GPL(blk_rq_prep_clone);
3116 int kblockd_schedule_work(struct work_struct *work)
3118 return queue_work(kblockd_workqueue, work);
3120 EXPORT_SYMBOL(kblockd_schedule_work);
3122 int kblockd_schedule_work_on(int cpu, struct work_struct *work)
3124 return queue_work_on(cpu, kblockd_workqueue, work);
3126 EXPORT_SYMBOL(kblockd_schedule_work_on);
3128 int kblockd_schedule_delayed_work(struct delayed_work *dwork,
3129 unsigned long delay)
3131 return queue_delayed_work(kblockd_workqueue, dwork, delay);
3133 EXPORT_SYMBOL(kblockd_schedule_delayed_work);
3135 int kblockd_schedule_delayed_work_on(int cpu, struct delayed_work *dwork,
3136 unsigned long delay)
3138 return queue_delayed_work_on(cpu, kblockd_workqueue, dwork, delay);
3140 EXPORT_SYMBOL(kblockd_schedule_delayed_work_on);
3143 * blk_start_plug - initialize blk_plug and track it inside the task_struct
3144 * @plug: The &struct blk_plug that needs to be initialized
3146 * Description:
3147 * Tracking blk_plug inside the task_struct will help with auto-flushing the
3148 * pending I/O should the task end up blocking between blk_start_plug() and
3149 * blk_finish_plug(). This is important from a performance perspective, but
3150 * also ensures that we don't deadlock. For instance, if the task is blocking
3151 * for a memory allocation, memory reclaim could end up wanting to free a
3152 * page belonging to that request that is currently residing in our private
3153 * plug. By flushing the pending I/O when the process goes to sleep, we avoid
3154 * this kind of deadlock.
3156 void blk_start_plug(struct blk_plug *plug)
3158 struct task_struct *tsk = current;
3161 * If this is a nested plug, don't actually assign it.
3163 if (tsk->plug)
3164 return;
3166 INIT_LIST_HEAD(&plug->list);
3167 INIT_LIST_HEAD(&plug->mq_list);
3168 INIT_LIST_HEAD(&plug->cb_list);
3170 * Store ordering should not be needed here, since a potential
3171 * preempt will imply a full memory barrier
3173 tsk->plug = plug;
3175 EXPORT_SYMBOL(blk_start_plug);
3177 static int plug_rq_cmp(void *priv, struct list_head *a, struct list_head *b)
3179 struct request *rqa = container_of(a, struct request, queuelist);
3180 struct request *rqb = container_of(b, struct request, queuelist);
3182 return !(rqa->q < rqb->q ||
3183 (rqa->q == rqb->q && blk_rq_pos(rqa) < blk_rq_pos(rqb)));
3187 * If 'from_schedule' is true, then postpone the dispatch of requests
3188 * until a safe kblockd context. We due this to avoid accidental big
3189 * additional stack usage in driver dispatch, in places where the originally
3190 * plugger did not intend it.
3192 static void queue_unplugged(struct request_queue *q, unsigned int depth,
3193 bool from_schedule)
3194 __releases(q->queue_lock)
3196 trace_block_unplug(q, depth, !from_schedule);
3198 if (from_schedule)
3199 blk_run_queue_async(q);
3200 else
3201 __blk_run_queue(q);
3202 spin_unlock(q->queue_lock);
3205 static void flush_plug_callbacks(struct blk_plug *plug, bool from_schedule)
3207 LIST_HEAD(callbacks);
3209 while (!list_empty(&plug->cb_list)) {
3210 list_splice_init(&plug->cb_list, &callbacks);
3212 while (!list_empty(&callbacks)) {
3213 struct blk_plug_cb *cb = list_first_entry(&callbacks,
3214 struct blk_plug_cb,
3215 list);
3216 list_del(&cb->list);
3217 cb->callback(cb, from_schedule);
3222 struct blk_plug_cb *blk_check_plugged(blk_plug_cb_fn unplug, void *data,
3223 int size)
3225 struct blk_plug *plug = current->plug;
3226 struct blk_plug_cb *cb;
3228 if (!plug)
3229 return NULL;
3231 list_for_each_entry(cb, &plug->cb_list, list)
3232 if (cb->callback == unplug && cb->data == data)
3233 return cb;
3235 /* Not currently on the callback list */
3236 BUG_ON(size < sizeof(*cb));
3237 cb = kzalloc(size, GFP_ATOMIC);
3238 if (cb) {
3239 cb->data = data;
3240 cb->callback = unplug;
3241 list_add(&cb->list, &plug->cb_list);
3243 return cb;
3245 EXPORT_SYMBOL(blk_check_plugged);
3247 void blk_flush_plug_list(struct blk_plug *plug, bool from_schedule)
3249 struct request_queue *q;
3250 unsigned long flags;
3251 struct request *rq;
3252 LIST_HEAD(list);
3253 unsigned int depth;
3255 flush_plug_callbacks(plug, from_schedule);
3257 if (!list_empty(&plug->mq_list))
3258 blk_mq_flush_plug_list(plug, from_schedule);
3260 if (list_empty(&plug->list))
3261 return;
3263 list_splice_init(&plug->list, &list);
3265 list_sort(NULL, &list, plug_rq_cmp);
3267 q = NULL;
3268 depth = 0;
3271 * Save and disable interrupts here, to avoid doing it for every
3272 * queue lock we have to take.
3274 local_irq_save(flags);
3275 while (!list_empty(&list)) {
3276 rq = list_entry_rq(list.next);
3277 list_del_init(&rq->queuelist);
3278 BUG_ON(!rq->q);
3279 if (rq->q != q) {
3281 * This drops the queue lock
3283 if (q)
3284 queue_unplugged(q, depth, from_schedule);
3285 q = rq->q;
3286 depth = 0;
3287 spin_lock(q->queue_lock);
3291 * Short-circuit if @q is dead
3293 if (unlikely(blk_queue_dying(q))) {
3294 __blk_end_request_all(rq, -ENODEV);
3295 continue;
3299 * rq is already accounted, so use raw insert
3301 if (rq->cmd_flags & (REQ_PREFLUSH | REQ_FUA))
3302 __elv_add_request(q, rq, ELEVATOR_INSERT_FLUSH);
3303 else
3304 __elv_add_request(q, rq, ELEVATOR_INSERT_SORT_MERGE);
3306 depth++;
3310 * This drops the queue lock
3312 if (q)
3313 queue_unplugged(q, depth, from_schedule);
3315 local_irq_restore(flags);
3318 void blk_finish_plug(struct blk_plug *plug)
3320 if (plug != current->plug)
3321 return;
3322 blk_flush_plug_list(plug, false);
3324 current->plug = NULL;
3326 EXPORT_SYMBOL(blk_finish_plug);
3328 bool blk_poll(struct request_queue *q, blk_qc_t cookie)
3330 struct blk_plug *plug;
3331 long state;
3332 unsigned int queue_num;
3333 struct blk_mq_hw_ctx *hctx;
3335 if (!q->mq_ops || !q->mq_ops->poll || !blk_qc_t_valid(cookie) ||
3336 !test_bit(QUEUE_FLAG_POLL, &q->queue_flags))
3337 return false;
3339 queue_num = blk_qc_t_to_queue_num(cookie);
3340 hctx = q->queue_hw_ctx[queue_num];
3341 hctx->poll_considered++;
3343 plug = current->plug;
3344 if (plug)
3345 blk_flush_plug_list(plug, false);
3347 state = current->state;
3348 while (!need_resched()) {
3349 int ret;
3351 hctx->poll_invoked++;
3353 ret = q->mq_ops->poll(hctx, blk_qc_t_to_tag(cookie));
3354 if (ret > 0) {
3355 hctx->poll_success++;
3356 set_current_state(TASK_RUNNING);
3357 return true;
3360 if (signal_pending_state(state, current))
3361 set_current_state(TASK_RUNNING);
3363 if (current->state == TASK_RUNNING)
3364 return true;
3365 if (ret < 0)
3366 break;
3367 cpu_relax();
3370 return false;
3372 EXPORT_SYMBOL_GPL(blk_poll);
3374 #ifdef CONFIG_PM
3376 * blk_pm_runtime_init - Block layer runtime PM initialization routine
3377 * @q: the queue of the device
3378 * @dev: the device the queue belongs to
3380 * Description:
3381 * Initialize runtime-PM-related fields for @q and start auto suspend for
3382 * @dev. Drivers that want to take advantage of request-based runtime PM
3383 * should call this function after @dev has been initialized, and its
3384 * request queue @q has been allocated, and runtime PM for it can not happen
3385 * yet(either due to disabled/forbidden or its usage_count > 0). In most
3386 * cases, driver should call this function before any I/O has taken place.
3388 * This function takes care of setting up using auto suspend for the device,
3389 * the autosuspend delay is set to -1 to make runtime suspend impossible
3390 * until an updated value is either set by user or by driver. Drivers do
3391 * not need to touch other autosuspend settings.
3393 * The block layer runtime PM is request based, so only works for drivers
3394 * that use request as their IO unit instead of those directly use bio's.
3396 void blk_pm_runtime_init(struct request_queue *q, struct device *dev)
3398 q->dev = dev;
3399 q->rpm_status = RPM_ACTIVE;
3400 pm_runtime_set_autosuspend_delay(q->dev, -1);
3401 pm_runtime_use_autosuspend(q->dev);
3403 EXPORT_SYMBOL(blk_pm_runtime_init);
3406 * blk_pre_runtime_suspend - Pre runtime suspend check
3407 * @q: the queue of the device
3409 * Description:
3410 * This function will check if runtime suspend is allowed for the device
3411 * by examining if there are any requests pending in the queue. If there
3412 * are requests pending, the device can not be runtime suspended; otherwise,
3413 * the queue's status will be updated to SUSPENDING and the driver can
3414 * proceed to suspend the device.
3416 * For the not allowed case, we mark last busy for the device so that
3417 * runtime PM core will try to autosuspend it some time later.
3419 * This function should be called near the start of the device's
3420 * runtime_suspend callback.
3422 * Return:
3423 * 0 - OK to runtime suspend the device
3424 * -EBUSY - Device should not be runtime suspended
3426 int blk_pre_runtime_suspend(struct request_queue *q)
3428 int ret = 0;
3430 if (!q->dev)
3431 return ret;
3433 spin_lock_irq(q->queue_lock);
3434 if (q->nr_pending) {
3435 ret = -EBUSY;
3436 pm_runtime_mark_last_busy(q->dev);
3437 } else {
3438 q->rpm_status = RPM_SUSPENDING;
3440 spin_unlock_irq(q->queue_lock);
3441 return ret;
3443 EXPORT_SYMBOL(blk_pre_runtime_suspend);
3446 * blk_post_runtime_suspend - Post runtime suspend processing
3447 * @q: the queue of the device
3448 * @err: return value of the device's runtime_suspend function
3450 * Description:
3451 * Update the queue's runtime status according to the return value of the
3452 * device's runtime suspend function and mark last busy for the device so
3453 * that PM core will try to auto suspend the device at a later time.
3455 * This function should be called near the end of the device's
3456 * runtime_suspend callback.
3458 void blk_post_runtime_suspend(struct request_queue *q, int err)
3460 if (!q->dev)
3461 return;
3463 spin_lock_irq(q->queue_lock);
3464 if (!err) {
3465 q->rpm_status = RPM_SUSPENDED;
3466 } else {
3467 q->rpm_status = RPM_ACTIVE;
3468 pm_runtime_mark_last_busy(q->dev);
3470 spin_unlock_irq(q->queue_lock);
3472 EXPORT_SYMBOL(blk_post_runtime_suspend);
3475 * blk_pre_runtime_resume - Pre runtime resume processing
3476 * @q: the queue of the device
3478 * Description:
3479 * Update the queue's runtime status to RESUMING in preparation for the
3480 * runtime resume of the device.
3482 * This function should be called near the start of the device's
3483 * runtime_resume callback.
3485 void blk_pre_runtime_resume(struct request_queue *q)
3487 if (!q->dev)
3488 return;
3490 spin_lock_irq(q->queue_lock);
3491 q->rpm_status = RPM_RESUMING;
3492 spin_unlock_irq(q->queue_lock);
3494 EXPORT_SYMBOL(blk_pre_runtime_resume);
3497 * blk_post_runtime_resume - Post runtime resume processing
3498 * @q: the queue of the device
3499 * @err: return value of the device's runtime_resume function
3501 * Description:
3502 * Update the queue's runtime status according to the return value of the
3503 * device's runtime_resume function. If it is successfully resumed, process
3504 * the requests that are queued into the device's queue when it is resuming
3505 * and then mark last busy and initiate autosuspend for it.
3507 * This function should be called near the end of the device's
3508 * runtime_resume callback.
3510 void blk_post_runtime_resume(struct request_queue *q, int err)
3512 if (!q->dev)
3513 return;
3515 spin_lock_irq(q->queue_lock);
3516 if (!err) {
3517 q->rpm_status = RPM_ACTIVE;
3518 __blk_run_queue(q);
3519 pm_runtime_mark_last_busy(q->dev);
3520 pm_request_autosuspend(q->dev);
3521 } else {
3522 q->rpm_status = RPM_SUSPENDED;
3524 spin_unlock_irq(q->queue_lock);
3526 EXPORT_SYMBOL(blk_post_runtime_resume);
3529 * blk_set_runtime_active - Force runtime status of the queue to be active
3530 * @q: the queue of the device
3532 * If the device is left runtime suspended during system suspend the resume
3533 * hook typically resumes the device and corrects runtime status
3534 * accordingly. However, that does not affect the queue runtime PM status
3535 * which is still "suspended". This prevents processing requests from the
3536 * queue.
3538 * This function can be used in driver's resume hook to correct queue
3539 * runtime PM status and re-enable peeking requests from the queue. It
3540 * should be called before first request is added to the queue.
3542 void blk_set_runtime_active(struct request_queue *q)
3544 spin_lock_irq(q->queue_lock);
3545 q->rpm_status = RPM_ACTIVE;
3546 pm_runtime_mark_last_busy(q->dev);
3547 pm_request_autosuspend(q->dev);
3548 spin_unlock_irq(q->queue_lock);
3550 EXPORT_SYMBOL(blk_set_runtime_active);
3551 #endif
3553 int __init blk_dev_init(void)
3555 BUILD_BUG_ON(__REQ_NR_BITS > 8 *
3556 FIELD_SIZEOF(struct request, cmd_flags));
3558 /* used for unplugging and affects IO latency/throughput - HIGHPRI */
3559 kblockd_workqueue = alloc_workqueue("kblockd",
3560 WQ_MEM_RECLAIM | WQ_HIGHPRI, 0);
3561 if (!kblockd_workqueue)
3562 panic("Failed to create kblockd\n");
3564 request_cachep = kmem_cache_create("blkdev_requests",
3565 sizeof(struct request), 0, SLAB_PANIC, NULL);
3567 blk_requestq_cachep = kmem_cache_create("request_queue",
3568 sizeof(struct request_queue), 0, SLAB_PANIC, NULL);
3570 return 0;