]> git.proxmox.com Git - mirror_ubuntu-artful-kernel.git/blob - block/blk-core.c
UBUNTU: [config] update config for master changes
[mirror_ubuntu-artful-kernel.git] / block / blk-core.c
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 */
10
11 /*
12 * This handles all read/write requests to block devices
13 */
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>
36
37 #define CREATE_TRACE_POINTS
38 #include <trace/events/block.h>
39
40 #include "blk.h"
41 #include "blk-mq.h"
42
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);
48
49 DEFINE_IDA(blk_queue_ida);
50
51 /*
52 * For the allocated request tables
53 */
54 struct kmem_cache *request_cachep = NULL;
55
56 /*
57 * For queue allocation
58 */
59 struct kmem_cache *blk_requestq_cachep;
60
61 /*
62 * Controlling structure to kblockd
63 */
64 static struct workqueue_struct *kblockd_workqueue;
65
66 static void blk_clear_congested(struct request_list *rl, int sync)
67 {
68 #ifdef CONFIG_CGROUP_WRITEBACK
69 clear_wb_congested(rl->blkg->wb_congested, sync);
70 #else
71 /*
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.
74 */
75 if (rl == &rl->q->root_rl)
76 clear_wb_congested(rl->q->backing_dev_info->wb.congested, sync);
77 #endif
78 }
79
80 static void blk_set_congested(struct request_list *rl, int sync)
81 {
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
89 }
90
91 void blk_queue_congestion_threshold(struct request_queue *q)
92 {
93 int nr;
94
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;
99
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;
104 }
105
106 void blk_rq_init(struct request_queue *q, struct request *rq)
107 {
108 memset(rq, 0, sizeof(*rq));
109
110 INIT_LIST_HEAD(&rq->queuelist);
111 INIT_LIST_HEAD(&rq->timeout_list);
112 rq->cpu = -1;
113 rq->q = q;
114 rq->__sector = (sector_t) -1;
115 INIT_HLIST_NODE(&rq->hash);
116 RB_CLEAR_NODE(&rq->rb_node);
117 rq->cmd = rq->__cmd;
118 rq->cmd_len = BLK_MAX_CDB;
119 rq->tag = -1;
120 rq->start_time = jiffies;
121 set_start_time_ns(rq);
122 rq->part = NULL;
123 }
124 EXPORT_SYMBOL(blk_rq_init);
125
126 static void req_bio_endio(struct request *rq, struct bio *bio,
127 unsigned int nbytes, int error)
128 {
129 if (error)
130 bio->bi_error = error;
131
132 if (unlikely(rq->cmd_flags & REQ_QUIET))
133 bio_set_flag(bio, BIO_QUIET);
134
135 bio_advance(bio, nbytes);
136
137 /* don't actually finish bio if it's part of flush sequence */
138 if (bio->bi_iter.bi_size == 0 && !(rq->cmd_flags & REQ_FLUSH_SEQ))
139 bio_endio(bio);
140 }
141
142 void blk_dump_rq_flags(struct request *rq, char *msg)
143 {
144 int bit;
145
146 printk(KERN_INFO "%s: dev %s: type=%x, flags=%llx\n", msg,
147 rq->rq_disk ? rq->rq_disk->disk_name : "?", rq->cmd_type,
148 (unsigned long long) rq->cmd_flags);
149
150 printk(KERN_INFO " sector %llu, nr/cnr %u/%u\n",
151 (unsigned long long)blk_rq_pos(rq),
152 blk_rq_sectors(rq), blk_rq_cur_sectors(rq));
153 printk(KERN_INFO " bio %p, biotail %p, len %u\n",
154 rq->bio, rq->biotail, blk_rq_bytes(rq));
155
156 if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
157 printk(KERN_INFO " cdb: ");
158 for (bit = 0; bit < BLK_MAX_CDB; bit++)
159 printk("%02x ", rq->cmd[bit]);
160 printk("\n");
161 }
162 }
163 EXPORT_SYMBOL(blk_dump_rq_flags);
164
165 static void blk_delay_work(struct work_struct *work)
166 {
167 struct request_queue *q;
168
169 q = container_of(work, struct request_queue, delay_work.work);
170 spin_lock_irq(q->queue_lock);
171 __blk_run_queue(q);
172 spin_unlock_irq(q->queue_lock);
173 }
174
175 /**
176 * blk_delay_queue - restart queueing after defined interval
177 * @q: The &struct request_queue in question
178 * @msecs: Delay in msecs
179 *
180 * Description:
181 * Sometimes queueing needs to be postponed for a little while, to allow
182 * resources to come back. This function will make sure that queueing is
183 * restarted around the specified time. Queue lock must be held.
184 */
185 void blk_delay_queue(struct request_queue *q, unsigned long msecs)
186 {
187 if (likely(!blk_queue_dead(q)))
188 queue_delayed_work(kblockd_workqueue, &q->delay_work,
189 msecs_to_jiffies(msecs));
190 }
191 EXPORT_SYMBOL(blk_delay_queue);
192
193 /**
194 * blk_start_queue_async - asynchronously restart a previously stopped queue
195 * @q: The &struct request_queue in question
196 *
197 * Description:
198 * blk_start_queue_async() will clear the stop flag on the queue, and
199 * ensure that the request_fn for the queue is run from an async
200 * context.
201 **/
202 void blk_start_queue_async(struct request_queue *q)
203 {
204 queue_flag_clear(QUEUE_FLAG_STOPPED, q);
205 blk_run_queue_async(q);
206 }
207 EXPORT_SYMBOL(blk_start_queue_async);
208
209 /**
210 * blk_start_queue - restart a previously stopped queue
211 * @q: The &struct request_queue in question
212 *
213 * Description:
214 * blk_start_queue() will clear the stop flag on the queue, and call
215 * the request_fn for the queue if it was in a stopped state when
216 * entered. Also see blk_stop_queue(). Queue lock must be held.
217 **/
218 void blk_start_queue(struct request_queue *q)
219 {
220 WARN_ON(!in_interrupt() && !irqs_disabled());
221
222 queue_flag_clear(QUEUE_FLAG_STOPPED, q);
223 __blk_run_queue(q);
224 }
225 EXPORT_SYMBOL(blk_start_queue);
226
227 /**
228 * blk_stop_queue - stop a queue
229 * @q: The &struct request_queue in question
230 *
231 * Description:
232 * The Linux block layer assumes that a block driver will consume all
233 * entries on the request queue when the request_fn strategy is called.
234 * Often this will not happen, because of hardware limitations (queue
235 * depth settings). If a device driver gets a 'queue full' response,
236 * or if it simply chooses not to queue more I/O at one point, it can
237 * call this function to prevent the request_fn from being called until
238 * the driver has signalled it's ready to go again. This happens by calling
239 * blk_start_queue() to restart queue operations. Queue lock must be held.
240 **/
241 void blk_stop_queue(struct request_queue *q)
242 {
243 cancel_delayed_work(&q->delay_work);
244 queue_flag_set(QUEUE_FLAG_STOPPED, q);
245 }
246 EXPORT_SYMBOL(blk_stop_queue);
247
248 /**
249 * blk_sync_queue - cancel any pending callbacks on a queue
250 * @q: the queue
251 *
252 * Description:
253 * The block layer may perform asynchronous callback activity
254 * on a queue, such as calling the unplug function after a timeout.
255 * A block device may call blk_sync_queue to ensure that any
256 * such activity is cancelled, thus allowing it to release resources
257 * that the callbacks might use. The caller must already have made sure
258 * that its ->make_request_fn will not re-add plugging prior to calling
259 * this function.
260 *
261 * This function does not cancel any asynchronous activity arising
262 * out of elevator or throttling code. That would require elevator_exit()
263 * and blkcg_exit_queue() to be called with queue lock initialized.
264 *
265 */
266 void blk_sync_queue(struct request_queue *q)
267 {
268 del_timer_sync(&q->timeout);
269
270 if (q->mq_ops) {
271 struct blk_mq_hw_ctx *hctx;
272 int i;
273
274 queue_for_each_hw_ctx(q, hctx, i) {
275 cancel_delayed_work_sync(&hctx->run_work);
276 cancel_delayed_work_sync(&hctx->delay_work);
277 }
278 } else {
279 cancel_delayed_work_sync(&q->delay_work);
280 }
281 }
282 EXPORT_SYMBOL(blk_sync_queue);
283
284 /**
285 * __blk_run_queue_uncond - run a queue whether or not it has been stopped
286 * @q: The queue to run
287 *
288 * Description:
289 * Invoke request handling on a queue if there are any pending requests.
290 * May be used to restart request handling after a request has completed.
291 * This variant runs the queue whether or not the queue has been
292 * stopped. Must be called with the queue lock held and interrupts
293 * disabled. See also @blk_run_queue.
294 */
295 inline void __blk_run_queue_uncond(struct request_queue *q)
296 {
297 if (unlikely(blk_queue_dead(q)))
298 return;
299
300 /*
301 * Some request_fn implementations, e.g. scsi_request_fn(), unlock
302 * the queue lock internally. As a result multiple threads may be
303 * running such a request function concurrently. Keep track of the
304 * number of active request_fn invocations such that blk_drain_queue()
305 * can wait until all these request_fn calls have finished.
306 */
307 q->request_fn_active++;
308 q->request_fn(q);
309 q->request_fn_active--;
310 }
311 EXPORT_SYMBOL_GPL(__blk_run_queue_uncond);
312
313 /**
314 * __blk_run_queue - run a single device queue
315 * @q: The queue to run
316 *
317 * Description:
318 * See @blk_run_queue. This variant must be called with the queue lock
319 * held and interrupts disabled.
320 */
321 void __blk_run_queue(struct request_queue *q)
322 {
323 if (unlikely(blk_queue_stopped(q)))
324 return;
325
326 __blk_run_queue_uncond(q);
327 }
328 EXPORT_SYMBOL(__blk_run_queue);
329
330 /**
331 * blk_run_queue_async - run a single device queue in workqueue context
332 * @q: The queue to run
333 *
334 * Description:
335 * Tells kblockd to perform the equivalent of @blk_run_queue on behalf
336 * of us. The caller must hold the queue lock.
337 */
338 void blk_run_queue_async(struct request_queue *q)
339 {
340 if (likely(!blk_queue_stopped(q) && !blk_queue_dead(q)))
341 mod_delayed_work(kblockd_workqueue, &q->delay_work, 0);
342 }
343 EXPORT_SYMBOL(blk_run_queue_async);
344
345 /**
346 * blk_run_queue - run a single device queue
347 * @q: The queue to run
348 *
349 * Description:
350 * Invoke request handling on this queue, if it has pending work to do.
351 * May be used to restart queueing when a request has completed.
352 */
353 void blk_run_queue(struct request_queue *q)
354 {
355 unsigned long flags;
356
357 spin_lock_irqsave(q->queue_lock, flags);
358 __blk_run_queue(q);
359 spin_unlock_irqrestore(q->queue_lock, flags);
360 }
361 EXPORT_SYMBOL(blk_run_queue);
362
363 void blk_put_queue(struct request_queue *q)
364 {
365 kobject_put(&q->kobj);
366 }
367 EXPORT_SYMBOL(blk_put_queue);
368
369 /**
370 * __blk_drain_queue - drain requests from request_queue
371 * @q: queue to drain
372 * @drain_all: whether to drain all requests or only the ones w/ ELVPRIV
373 *
374 * Drain requests from @q. If @drain_all is set, all requests are drained.
375 * If not, only ELVPRIV requests are drained. The caller is responsible
376 * for ensuring that no new requests which need to be drained are queued.
377 */
378 static void __blk_drain_queue(struct request_queue *q, bool drain_all)
379 __releases(q->queue_lock)
380 __acquires(q->queue_lock)
381 {
382 int i;
383
384 lockdep_assert_held(q->queue_lock);
385
386 while (true) {
387 bool drain = false;
388
389 /*
390 * The caller might be trying to drain @q before its
391 * elevator is initialized.
392 */
393 if (q->elevator)
394 elv_drain_elevator(q);
395
396 blkcg_drain_queue(q);
397
398 /*
399 * This function might be called on a queue which failed
400 * driver init after queue creation or is not yet fully
401 * active yet. Some drivers (e.g. fd and loop) get unhappy
402 * in such cases. Kick queue iff dispatch queue has
403 * something on it and @q has request_fn set.
404 */
405 if (!list_empty(&q->queue_head) && q->request_fn)
406 __blk_run_queue(q);
407
408 drain |= q->nr_rqs_elvpriv;
409 drain |= q->request_fn_active;
410
411 /*
412 * Unfortunately, requests are queued at and tracked from
413 * multiple places and there's no single counter which can
414 * be drained. Check all the queues and counters.
415 */
416 if (drain_all) {
417 struct blk_flush_queue *fq = blk_get_flush_queue(q, NULL);
418 drain |= !list_empty(&q->queue_head);
419 for (i = 0; i < 2; i++) {
420 drain |= q->nr_rqs[i];
421 drain |= q->in_flight[i];
422 if (fq)
423 drain |= !list_empty(&fq->flush_queue[i]);
424 }
425 }
426
427 if (!drain)
428 break;
429
430 spin_unlock_irq(q->queue_lock);
431
432 msleep(10);
433
434 spin_lock_irq(q->queue_lock);
435 }
436
437 /*
438 * With queue marked dead, any woken up waiter will fail the
439 * allocation path, so the wakeup chaining is lost and we're
440 * left with hung waiters. We need to wake up those waiters.
441 */
442 if (q->request_fn) {
443 struct request_list *rl;
444
445 blk_queue_for_each_rl(rl, q)
446 for (i = 0; i < ARRAY_SIZE(rl->wait); i++)
447 wake_up_all(&rl->wait[i]);
448 }
449 }
450
451 /**
452 * blk_queue_bypass_start - enter queue bypass mode
453 * @q: queue of interest
454 *
455 * In bypass mode, only the dispatch FIFO queue of @q is used. This
456 * function makes @q enter bypass mode and drains all requests which were
457 * throttled or issued before. On return, it's guaranteed that no request
458 * is being throttled or has ELVPRIV set and blk_queue_bypass() %true
459 * inside queue or RCU read lock.
460 */
461 void blk_queue_bypass_start(struct request_queue *q)
462 {
463 spin_lock_irq(q->queue_lock);
464 q->bypass_depth++;
465 queue_flag_set(QUEUE_FLAG_BYPASS, q);
466 spin_unlock_irq(q->queue_lock);
467
468 /*
469 * Queues start drained. Skip actual draining till init is
470 * complete. This avoids lenghty delays during queue init which
471 * can happen many times during boot.
472 */
473 if (blk_queue_init_done(q)) {
474 spin_lock_irq(q->queue_lock);
475 __blk_drain_queue(q, false);
476 spin_unlock_irq(q->queue_lock);
477
478 /* ensure blk_queue_bypass() is %true inside RCU read lock */
479 synchronize_rcu();
480 }
481 }
482 EXPORT_SYMBOL_GPL(blk_queue_bypass_start);
483
484 /**
485 * blk_queue_bypass_end - leave queue bypass mode
486 * @q: queue of interest
487 *
488 * Leave bypass mode and restore the normal queueing behavior.
489 */
490 void blk_queue_bypass_end(struct request_queue *q)
491 {
492 spin_lock_irq(q->queue_lock);
493 if (!--q->bypass_depth)
494 queue_flag_clear(QUEUE_FLAG_BYPASS, q);
495 WARN_ON_ONCE(q->bypass_depth < 0);
496 spin_unlock_irq(q->queue_lock);
497 }
498 EXPORT_SYMBOL_GPL(blk_queue_bypass_end);
499
500 void blk_set_queue_dying(struct request_queue *q)
501 {
502 spin_lock_irq(q->queue_lock);
503 queue_flag_set(QUEUE_FLAG_DYING, q);
504 spin_unlock_irq(q->queue_lock);
505
506 if (q->mq_ops)
507 blk_mq_wake_waiters(q);
508 else {
509 struct request_list *rl;
510
511 blk_queue_for_each_rl(rl, q) {
512 if (rl->rq_pool) {
513 wake_up_all(&rl->wait[BLK_RW_SYNC]);
514 wake_up_all(&rl->wait[BLK_RW_ASYNC]);
515 }
516 }
517 }
518 }
519 EXPORT_SYMBOL_GPL(blk_set_queue_dying);
520
521 /**
522 * blk_cleanup_queue - shutdown a request queue
523 * @q: request queue to shutdown
524 *
525 * Mark @q DYING, drain all pending requests, mark @q DEAD, destroy and
526 * put it. All future requests will be failed immediately with -ENODEV.
527 */
528 void blk_cleanup_queue(struct request_queue *q)
529 {
530 spinlock_t *lock = q->queue_lock;
531
532 /* mark @q DYING, no new request or merges will be allowed afterwards */
533 mutex_lock(&q->sysfs_lock);
534 blk_set_queue_dying(q);
535 spin_lock_irq(lock);
536
537 /*
538 * A dying queue is permanently in bypass mode till released. Note
539 * that, unlike blk_queue_bypass_start(), we aren't performing
540 * synchronize_rcu() after entering bypass mode to avoid the delay
541 * as some drivers create and destroy a lot of queues while
542 * probing. This is still safe because blk_release_queue() will be
543 * called only after the queue refcnt drops to zero and nothing,
544 * RCU or not, would be traversing the queue by then.
545 */
546 q->bypass_depth++;
547 queue_flag_set(QUEUE_FLAG_BYPASS, q);
548
549 queue_flag_set(QUEUE_FLAG_NOMERGES, q);
550 queue_flag_set(QUEUE_FLAG_NOXMERGES, q);
551 queue_flag_set(QUEUE_FLAG_DYING, q);
552 spin_unlock_irq(lock);
553 mutex_unlock(&q->sysfs_lock);
554
555 /*
556 * Drain all requests queued before DYING marking. Set DEAD flag to
557 * prevent that q->request_fn() gets invoked after draining finished.
558 */
559 blk_freeze_queue(q);
560 spin_lock_irq(lock);
561 if (!q->mq_ops)
562 __blk_drain_queue(q, true);
563 queue_flag_set(QUEUE_FLAG_DEAD, q);
564 spin_unlock_irq(lock);
565
566 /* for synchronous bio-based driver finish in-flight integrity i/o */
567 blk_flush_integrity();
568
569 /* @q won't process any more request, flush async actions */
570 del_timer_sync(&q->backing_dev_info->laptop_mode_wb_timer);
571 blk_sync_queue(q);
572
573 if (q->mq_ops)
574 blk_mq_free_queue(q);
575 percpu_ref_exit(&q->q_usage_counter);
576
577 spin_lock_irq(lock);
578 if (q->queue_lock != &q->__queue_lock)
579 q->queue_lock = &q->__queue_lock;
580 spin_unlock_irq(lock);
581
582 /* @q is and will stay empty, shutdown and put */
583 blk_put_queue(q);
584 }
585 EXPORT_SYMBOL(blk_cleanup_queue);
586
587 /* Allocate memory local to the request queue */
588 static void *alloc_request_struct(gfp_t gfp_mask, void *data)
589 {
590 int nid = (int)(long)data;
591 return kmem_cache_alloc_node(request_cachep, gfp_mask, nid);
592 }
593
594 static void free_request_struct(void *element, void *unused)
595 {
596 kmem_cache_free(request_cachep, element);
597 }
598
599 int blk_init_rl(struct request_list *rl, struct request_queue *q,
600 gfp_t gfp_mask)
601 {
602 if (unlikely(rl->rq_pool))
603 return 0;
604
605 rl->q = q;
606 rl->count[BLK_RW_SYNC] = rl->count[BLK_RW_ASYNC] = 0;
607 rl->starved[BLK_RW_SYNC] = rl->starved[BLK_RW_ASYNC] = 0;
608 init_waitqueue_head(&rl->wait[BLK_RW_SYNC]);
609 init_waitqueue_head(&rl->wait[BLK_RW_ASYNC]);
610
611 rl->rq_pool = mempool_create_node(BLKDEV_MIN_RQ, alloc_request_struct,
612 free_request_struct,
613 (void *)(long)q->node, gfp_mask,
614 q->node);
615 if (!rl->rq_pool)
616 return -ENOMEM;
617
618 return 0;
619 }
620
621 void blk_exit_rl(struct request_list *rl)
622 {
623 if (rl->rq_pool)
624 mempool_destroy(rl->rq_pool);
625 }
626
627 struct request_queue *blk_alloc_queue(gfp_t gfp_mask)
628 {
629 return blk_alloc_queue_node(gfp_mask, NUMA_NO_NODE);
630 }
631 EXPORT_SYMBOL(blk_alloc_queue);
632
633 int blk_queue_enter(struct request_queue *q, bool nowait)
634 {
635 while (true) {
636 int ret;
637
638 if (percpu_ref_tryget_live(&q->q_usage_counter))
639 return 0;
640
641 if (nowait)
642 return -EBUSY;
643
644 ret = wait_event_interruptible(q->mq_freeze_wq,
645 !atomic_read(&q->mq_freeze_depth) ||
646 blk_queue_dying(q));
647 if (blk_queue_dying(q))
648 return -ENODEV;
649 if (ret)
650 return ret;
651 }
652 }
653
654 void blk_queue_exit(struct request_queue *q)
655 {
656 percpu_ref_put(&q->q_usage_counter);
657 }
658
659 static void blk_queue_usage_counter_release(struct percpu_ref *ref)
660 {
661 struct request_queue *q =
662 container_of(ref, struct request_queue, q_usage_counter);
663
664 wake_up_all(&q->mq_freeze_wq);
665 }
666
667 static void blk_rq_timed_out_timer(unsigned long data)
668 {
669 struct request_queue *q = (struct request_queue *)data;
670
671 kblockd_schedule_work(&q->timeout_work);
672 }
673
674 struct request_queue *blk_alloc_queue_node(gfp_t gfp_mask, int node_id)
675 {
676 struct request_queue *q;
677
678 q = kmem_cache_alloc_node(blk_requestq_cachep,
679 gfp_mask | __GFP_ZERO, node_id);
680 if (!q)
681 return NULL;
682
683 q->id = ida_simple_get(&blk_queue_ida, 0, 0, gfp_mask);
684 if (q->id < 0)
685 goto fail_q;
686
687 q->bio_split = bioset_create(BIO_POOL_SIZE, 0);
688 if (!q->bio_split)
689 goto fail_id;
690
691 q->backing_dev_info = bdi_alloc_node(gfp_mask, node_id);
692 if (!q->backing_dev_info)
693 goto fail_split;
694
695 q->backing_dev_info->ra_pages =
696 (VM_MAX_READAHEAD * 1024) / PAGE_CACHE_SIZE;
697 q->backing_dev_info->capabilities = BDI_CAP_CGROUP_WRITEBACK;
698 q->backing_dev_info->name = "block";
699 q->node = node_id;
700
701 setup_timer(&q->backing_dev_info->laptop_mode_wb_timer,
702 laptop_mode_timer_fn, (unsigned long) q);
703 setup_timer(&q->timeout, blk_rq_timed_out_timer, (unsigned long) q);
704 INIT_LIST_HEAD(&q->queue_head);
705 INIT_LIST_HEAD(&q->timeout_list);
706 INIT_LIST_HEAD(&q->icq_list);
707 #ifdef CONFIG_BLK_CGROUP
708 INIT_LIST_HEAD(&q->blkg_list);
709 #endif
710 INIT_DELAYED_WORK(&q->delay_work, blk_delay_work);
711
712 kobject_init(&q->kobj, &blk_queue_ktype);
713
714 mutex_init(&q->sysfs_lock);
715 spin_lock_init(&q->__queue_lock);
716
717 /*
718 * By default initialize queue_lock to internal lock and driver can
719 * override it later if need be.
720 */
721 q->queue_lock = &q->__queue_lock;
722
723 /*
724 * A queue starts its life with bypass turned on to avoid
725 * unnecessary bypass on/off overhead and nasty surprises during
726 * init. The initial bypass will be finished when the queue is
727 * registered by blk_register_queue().
728 */
729 q->bypass_depth = 1;
730 __set_bit(QUEUE_FLAG_BYPASS, &q->queue_flags);
731
732 init_waitqueue_head(&q->mq_freeze_wq);
733
734 /*
735 * Init percpu_ref in atomic mode so that it's faster to shutdown.
736 * See blk_register_queue() for details.
737 */
738 if (percpu_ref_init(&q->q_usage_counter,
739 blk_queue_usage_counter_release,
740 PERCPU_REF_INIT_ATOMIC, GFP_KERNEL))
741 goto fail_bdi;
742
743 if (blkcg_init_queue(q))
744 goto fail_ref;
745
746 return q;
747
748 fail_ref:
749 percpu_ref_exit(&q->q_usage_counter);
750 fail_bdi:
751 bdi_put(q->backing_dev_info);
752 fail_split:
753 bioset_free(q->bio_split);
754 fail_id:
755 ida_simple_remove(&blk_queue_ida, q->id);
756 fail_q:
757 kmem_cache_free(blk_requestq_cachep, q);
758 return NULL;
759 }
760 EXPORT_SYMBOL(blk_alloc_queue_node);
761
762 /**
763 * blk_init_queue - prepare a request queue for use with a block device
764 * @rfn: The function to be called to process requests that have been
765 * placed on the queue.
766 * @lock: Request queue spin lock
767 *
768 * Description:
769 * If a block device wishes to use the standard request handling procedures,
770 * which sorts requests and coalesces adjacent requests, then it must
771 * call blk_init_queue(). The function @rfn will be called when there
772 * are requests on the queue that need to be processed. If the device
773 * supports plugging, then @rfn may not be called immediately when requests
774 * are available on the queue, but may be called at some time later instead.
775 * Plugged queues are generally unplugged when a buffer belonging to one
776 * of the requests on the queue is needed, or due to memory pressure.
777 *
778 * @rfn is not required, or even expected, to remove all requests off the
779 * queue, but only as many as it can handle at a time. If it does leave
780 * requests on the queue, it is responsible for arranging that the requests
781 * get dealt with eventually.
782 *
783 * The queue spin lock must be held while manipulating the requests on the
784 * request queue; this lock will be taken also from interrupt context, so irq
785 * disabling is needed for it.
786 *
787 * Function returns a pointer to the initialized request queue, or %NULL if
788 * it didn't succeed.
789 *
790 * Note:
791 * blk_init_queue() must be paired with a blk_cleanup_queue() call
792 * when the block device is deactivated (such as at module unload).
793 **/
794
795 struct request_queue *blk_init_queue(request_fn_proc *rfn, spinlock_t *lock)
796 {
797 return blk_init_queue_node(rfn, lock, NUMA_NO_NODE);
798 }
799 EXPORT_SYMBOL(blk_init_queue);
800
801 struct request_queue *
802 blk_init_queue_node(request_fn_proc *rfn, spinlock_t *lock, int node_id)
803 {
804 struct request_queue *uninit_q, *q;
805
806 uninit_q = blk_alloc_queue_node(GFP_KERNEL, node_id);
807 if (!uninit_q)
808 return NULL;
809
810 q = blk_init_allocated_queue(uninit_q, rfn, lock);
811 if (!q)
812 blk_cleanup_queue(uninit_q);
813
814 return q;
815 }
816 EXPORT_SYMBOL(blk_init_queue_node);
817
818 static blk_qc_t blk_queue_bio(struct request_queue *q, struct bio *bio);
819
820 struct request_queue *
821 blk_init_allocated_queue(struct request_queue *q, request_fn_proc *rfn,
822 spinlock_t *lock)
823 {
824 if (!q)
825 return NULL;
826
827 q->fq = blk_alloc_flush_queue(q, NUMA_NO_NODE, 0);
828 if (!q->fq)
829 return NULL;
830
831 if (blk_init_rl(&q->root_rl, q, GFP_KERNEL))
832 goto fail;
833
834 INIT_WORK(&q->timeout_work, blk_timeout_work);
835 q->request_fn = rfn;
836 q->prep_rq_fn = NULL;
837 q->unprep_rq_fn = NULL;
838 q->queue_flags |= QUEUE_FLAG_DEFAULT;
839
840 /* Override internal queue lock with supplied lock pointer */
841 if (lock)
842 q->queue_lock = lock;
843
844 /*
845 * This also sets hw/phys segments, boundary and size
846 */
847 blk_queue_make_request(q, blk_queue_bio);
848
849 q->sg_reserved_size = INT_MAX;
850
851 /* Protect q->elevator from elevator_change */
852 mutex_lock(&q->sysfs_lock);
853
854 /* init elevator */
855 if (elevator_init(q, NULL)) {
856 mutex_unlock(&q->sysfs_lock);
857 goto fail;
858 }
859
860 mutex_unlock(&q->sysfs_lock);
861
862 return q;
863
864 fail:
865 blk_free_flush_queue(q->fq);
866 return NULL;
867 }
868 EXPORT_SYMBOL(blk_init_allocated_queue);
869
870 bool blk_get_queue(struct request_queue *q)
871 {
872 if (likely(!blk_queue_dying(q))) {
873 __blk_get_queue(q);
874 return true;
875 }
876
877 return false;
878 }
879 EXPORT_SYMBOL(blk_get_queue);
880
881 static inline void blk_free_request(struct request_list *rl, struct request *rq)
882 {
883 if (rq->cmd_flags & REQ_ELVPRIV) {
884 elv_put_request(rl->q, rq);
885 if (rq->elv.icq)
886 put_io_context(rq->elv.icq->ioc);
887 }
888
889 mempool_free(rq, rl->rq_pool);
890 }
891
892 /*
893 * ioc_batching returns true if the ioc is a valid batching request and
894 * should be given priority access to a request.
895 */
896 static inline int ioc_batching(struct request_queue *q, struct io_context *ioc)
897 {
898 if (!ioc)
899 return 0;
900
901 /*
902 * Make sure the process is able to allocate at least 1 request
903 * even if the batch times out, otherwise we could theoretically
904 * lose wakeups.
905 */
906 return ioc->nr_batch_requests == q->nr_batching ||
907 (ioc->nr_batch_requests > 0
908 && time_before(jiffies, ioc->last_waited + BLK_BATCH_TIME));
909 }
910
911 /*
912 * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
913 * will cause the process to be a "batcher" on all queues in the system. This
914 * is the behaviour we want though - once it gets a wakeup it should be given
915 * a nice run.
916 */
917 static void ioc_set_batching(struct request_queue *q, struct io_context *ioc)
918 {
919 if (!ioc || ioc_batching(q, ioc))
920 return;
921
922 ioc->nr_batch_requests = q->nr_batching;
923 ioc->last_waited = jiffies;
924 }
925
926 static void __freed_request(struct request_list *rl, int sync)
927 {
928 struct request_queue *q = rl->q;
929
930 if (rl->count[sync] < queue_congestion_off_threshold(q))
931 blk_clear_congested(rl, sync);
932
933 if (rl->count[sync] + 1 <= q->nr_requests) {
934 if (waitqueue_active(&rl->wait[sync]))
935 wake_up(&rl->wait[sync]);
936
937 blk_clear_rl_full(rl, sync);
938 }
939 }
940
941 /*
942 * A request has just been released. Account for it, update the full and
943 * congestion status, wake up any waiters. Called under q->queue_lock.
944 */
945 static void freed_request(struct request_list *rl, unsigned int flags)
946 {
947 struct request_queue *q = rl->q;
948 int sync = rw_is_sync(flags);
949
950 q->nr_rqs[sync]--;
951 rl->count[sync]--;
952 if (flags & REQ_ELVPRIV)
953 q->nr_rqs_elvpriv--;
954
955 __freed_request(rl, sync);
956
957 if (unlikely(rl->starved[sync ^ 1]))
958 __freed_request(rl, sync ^ 1);
959 }
960
961 int blk_update_nr_requests(struct request_queue *q, unsigned int nr)
962 {
963 struct request_list *rl;
964 int on_thresh, off_thresh;
965
966 spin_lock_irq(q->queue_lock);
967 q->nr_requests = nr;
968 blk_queue_congestion_threshold(q);
969 on_thresh = queue_congestion_on_threshold(q);
970 off_thresh = queue_congestion_off_threshold(q);
971
972 blk_queue_for_each_rl(rl, q) {
973 if (rl->count[BLK_RW_SYNC] >= on_thresh)
974 blk_set_congested(rl, BLK_RW_SYNC);
975 else if (rl->count[BLK_RW_SYNC] < off_thresh)
976 blk_clear_congested(rl, BLK_RW_SYNC);
977
978 if (rl->count[BLK_RW_ASYNC] >= on_thresh)
979 blk_set_congested(rl, BLK_RW_ASYNC);
980 else if (rl->count[BLK_RW_ASYNC] < off_thresh)
981 blk_clear_congested(rl, BLK_RW_ASYNC);
982
983 if (rl->count[BLK_RW_SYNC] >= q->nr_requests) {
984 blk_set_rl_full(rl, BLK_RW_SYNC);
985 } else {
986 blk_clear_rl_full(rl, BLK_RW_SYNC);
987 wake_up(&rl->wait[BLK_RW_SYNC]);
988 }
989
990 if (rl->count[BLK_RW_ASYNC] >= q->nr_requests) {
991 blk_set_rl_full(rl, BLK_RW_ASYNC);
992 } else {
993 blk_clear_rl_full(rl, BLK_RW_ASYNC);
994 wake_up(&rl->wait[BLK_RW_ASYNC]);
995 }
996 }
997
998 spin_unlock_irq(q->queue_lock);
999 return 0;
1000 }
1001
1002 /*
1003 * Determine if elevator data should be initialized when allocating the
1004 * request associated with @bio.
1005 */
1006 static bool blk_rq_should_init_elevator(struct bio *bio)
1007 {
1008 if (!bio)
1009 return true;
1010
1011 /*
1012 * Flush requests do not use the elevator so skip initialization.
1013 * This allows a request to share the flush and elevator data.
1014 */
1015 if (bio->bi_rw & (REQ_FLUSH | REQ_FUA))
1016 return false;
1017
1018 return true;
1019 }
1020
1021 /**
1022 * rq_ioc - determine io_context for request allocation
1023 * @bio: request being allocated is for this bio (can be %NULL)
1024 *
1025 * Determine io_context to use for request allocation for @bio. May return
1026 * %NULL if %current->io_context doesn't exist.
1027 */
1028 static struct io_context *rq_ioc(struct bio *bio)
1029 {
1030 #ifdef CONFIG_BLK_CGROUP
1031 if (bio && bio->bi_ioc)
1032 return bio->bi_ioc;
1033 #endif
1034 return current->io_context;
1035 }
1036
1037 /**
1038 * __get_request - get a free request
1039 * @rl: request list to allocate from
1040 * @rw_flags: RW and SYNC flags
1041 * @bio: bio to allocate request for (can be %NULL)
1042 * @gfp_mask: allocation mask
1043 *
1044 * Get a free request from @q. This function may fail under memory
1045 * pressure or if @q is dead.
1046 *
1047 * Must be called with @q->queue_lock held and,
1048 * Returns ERR_PTR on failure, with @q->queue_lock held.
1049 * Returns request pointer on success, with @q->queue_lock *not held*.
1050 */
1051 static struct request *__get_request(struct request_list *rl, int rw_flags,
1052 struct bio *bio, gfp_t gfp_mask)
1053 {
1054 struct request_queue *q = rl->q;
1055 struct request *rq;
1056 struct elevator_type *et = q->elevator->type;
1057 struct io_context *ioc = rq_ioc(bio);
1058 struct io_cq *icq = NULL;
1059 const bool is_sync = rw_is_sync(rw_flags) != 0;
1060 int may_queue;
1061
1062 if (unlikely(blk_queue_dying(q)))
1063 return ERR_PTR(-ENODEV);
1064
1065 may_queue = elv_may_queue(q, rw_flags);
1066 if (may_queue == ELV_MQUEUE_NO)
1067 goto rq_starved;
1068
1069 if (rl->count[is_sync]+1 >= queue_congestion_on_threshold(q)) {
1070 if (rl->count[is_sync]+1 >= q->nr_requests) {
1071 /*
1072 * The queue will fill after this allocation, so set
1073 * it as full, and mark this process as "batching".
1074 * This process will be allowed to complete a batch of
1075 * requests, others will be blocked.
1076 */
1077 if (!blk_rl_full(rl, is_sync)) {
1078 ioc_set_batching(q, ioc);
1079 blk_set_rl_full(rl, is_sync);
1080 } else {
1081 if (may_queue != ELV_MQUEUE_MUST
1082 && !ioc_batching(q, ioc)) {
1083 /*
1084 * The queue is full and the allocating
1085 * process is not a "batcher", and not
1086 * exempted by the IO scheduler
1087 */
1088 return ERR_PTR(-ENOMEM);
1089 }
1090 }
1091 }
1092 blk_set_congested(rl, is_sync);
1093 }
1094
1095 /*
1096 * Only allow batching queuers to allocate up to 50% over the defined
1097 * limit of requests, otherwise we could have thousands of requests
1098 * allocated with any setting of ->nr_requests
1099 */
1100 if (rl->count[is_sync] >= (3 * q->nr_requests / 2))
1101 return ERR_PTR(-ENOMEM);
1102
1103 q->nr_rqs[is_sync]++;
1104 rl->count[is_sync]++;
1105 rl->starved[is_sync] = 0;
1106
1107 /*
1108 * Decide whether the new request will be managed by elevator. If
1109 * so, mark @rw_flags and increment elvpriv. Non-zero elvpriv will
1110 * prevent the current elevator from being destroyed until the new
1111 * request is freed. This guarantees icq's won't be destroyed and
1112 * makes creating new ones safe.
1113 *
1114 * Also, lookup icq while holding queue_lock. If it doesn't exist,
1115 * it will be created after releasing queue_lock.
1116 */
1117 if (blk_rq_should_init_elevator(bio) && !blk_queue_bypass(q)) {
1118 rw_flags |= REQ_ELVPRIV;
1119 q->nr_rqs_elvpriv++;
1120 if (et->icq_cache && ioc)
1121 icq = ioc_lookup_icq(ioc, q);
1122 }
1123
1124 if (blk_queue_io_stat(q))
1125 rw_flags |= REQ_IO_STAT;
1126 spin_unlock_irq(q->queue_lock);
1127
1128 /* allocate and init request */
1129 rq = mempool_alloc(rl->rq_pool, gfp_mask);
1130 if (!rq)
1131 goto fail_alloc;
1132
1133 blk_rq_init(q, rq);
1134 blk_rq_set_rl(rq, rl);
1135 rq->cmd_flags = rw_flags | REQ_ALLOCED;
1136
1137 /* init elvpriv */
1138 if (rw_flags & REQ_ELVPRIV) {
1139 if (unlikely(et->icq_cache && !icq)) {
1140 if (ioc)
1141 icq = ioc_create_icq(ioc, q, gfp_mask);
1142 if (!icq)
1143 goto fail_elvpriv;
1144 }
1145
1146 rq->elv.icq = icq;
1147 if (unlikely(elv_set_request(q, rq, bio, gfp_mask)))
1148 goto fail_elvpriv;
1149
1150 /* @rq->elv.icq holds io_context until @rq is freed */
1151 if (icq)
1152 get_io_context(icq->ioc);
1153 }
1154 out:
1155 /*
1156 * ioc may be NULL here, and ioc_batching will be false. That's
1157 * OK, if the queue is under the request limit then requests need
1158 * not count toward the nr_batch_requests limit. There will always
1159 * be some limit enforced by BLK_BATCH_TIME.
1160 */
1161 if (ioc_batching(q, ioc))
1162 ioc->nr_batch_requests--;
1163
1164 trace_block_getrq(q, bio, rw_flags & 1);
1165 return rq;
1166
1167 fail_elvpriv:
1168 /*
1169 * elvpriv init failed. ioc, icq and elvpriv aren't mempool backed
1170 * and may fail indefinitely under memory pressure and thus
1171 * shouldn't stall IO. Treat this request as !elvpriv. This will
1172 * disturb iosched and blkcg but weird is bettern than dead.
1173 */
1174 printk_ratelimited(KERN_WARNING "%s: dev %s: request aux data allocation failed, iosched may be disturbed\n",
1175 __func__, dev_name(q->backing_dev_info->dev));
1176
1177 rq->cmd_flags &= ~REQ_ELVPRIV;
1178 rq->elv.icq = NULL;
1179
1180 spin_lock_irq(q->queue_lock);
1181 q->nr_rqs_elvpriv--;
1182 spin_unlock_irq(q->queue_lock);
1183 goto out;
1184
1185 fail_alloc:
1186 /*
1187 * Allocation failed presumably due to memory. Undo anything we
1188 * might have messed up.
1189 *
1190 * Allocating task should really be put onto the front of the wait
1191 * queue, but this is pretty rare.
1192 */
1193 spin_lock_irq(q->queue_lock);
1194 freed_request(rl, rw_flags);
1195
1196 /*
1197 * in the very unlikely event that allocation failed and no
1198 * requests for this direction was pending, mark us starved so that
1199 * freeing of a request in the other direction will notice
1200 * us. another possible fix would be to split the rq mempool into
1201 * READ and WRITE
1202 */
1203 rq_starved:
1204 if (unlikely(rl->count[is_sync] == 0))
1205 rl->starved[is_sync] = 1;
1206 return ERR_PTR(-ENOMEM);
1207 }
1208
1209 /**
1210 * get_request - get a free request
1211 * @q: request_queue to allocate request from
1212 * @rw_flags: RW and SYNC flags
1213 * @bio: bio to allocate request for (can be %NULL)
1214 * @gfp_mask: allocation mask
1215 *
1216 * Get a free request from @q. If %__GFP_DIRECT_RECLAIM is set in @gfp_mask,
1217 * this function keeps retrying under memory pressure and fails iff @q is dead.
1218 *
1219 * Must be called with @q->queue_lock held and,
1220 * Returns ERR_PTR on failure, with @q->queue_lock held.
1221 * Returns request pointer on success, with @q->queue_lock *not held*.
1222 */
1223 static struct request *get_request(struct request_queue *q, int rw_flags,
1224 struct bio *bio, gfp_t gfp_mask)
1225 {
1226 const bool is_sync = rw_is_sync(rw_flags) != 0;
1227 DEFINE_WAIT(wait);
1228 struct request_list *rl;
1229 struct request *rq;
1230
1231 rl = blk_get_rl(q, bio); /* transferred to @rq on success */
1232 retry:
1233 rq = __get_request(rl, rw_flags, bio, gfp_mask);
1234 if (!IS_ERR(rq))
1235 return rq;
1236
1237 if (!gfpflags_allow_blocking(gfp_mask) || unlikely(blk_queue_dying(q))) {
1238 blk_put_rl(rl);
1239 return rq;
1240 }
1241
1242 /* wait on @rl and retry */
1243 prepare_to_wait_exclusive(&rl->wait[is_sync], &wait,
1244 TASK_UNINTERRUPTIBLE);
1245
1246 trace_block_sleeprq(q, bio, rw_flags & 1);
1247
1248 spin_unlock_irq(q->queue_lock);
1249 io_schedule();
1250
1251 /*
1252 * After sleeping, we become a "batching" process and will be able
1253 * to allocate at least one request, and up to a big batch of them
1254 * for a small period time. See ioc_batching, ioc_set_batching
1255 */
1256 ioc_set_batching(q, current->io_context);
1257
1258 spin_lock_irq(q->queue_lock);
1259 finish_wait(&rl->wait[is_sync], &wait);
1260
1261 goto retry;
1262 }
1263
1264 static struct request *blk_old_get_request(struct request_queue *q, int rw,
1265 gfp_t gfp_mask)
1266 {
1267 struct request *rq;
1268
1269 BUG_ON(rw != READ && rw != WRITE);
1270
1271 /* create ioc upfront */
1272 create_io_context(gfp_mask, q->node);
1273
1274 spin_lock_irq(q->queue_lock);
1275 rq = get_request(q, rw, NULL, gfp_mask);
1276 if (IS_ERR(rq))
1277 spin_unlock_irq(q->queue_lock);
1278 /* q->queue_lock is unlocked at this point */
1279
1280 return rq;
1281 }
1282
1283 struct request *blk_get_request(struct request_queue *q, int rw, gfp_t gfp_mask)
1284 {
1285 if (q->mq_ops)
1286 return blk_mq_alloc_request(q, rw,
1287 (gfp_mask & __GFP_DIRECT_RECLAIM) ?
1288 0 : BLK_MQ_REQ_NOWAIT);
1289 else
1290 return blk_old_get_request(q, rw, gfp_mask);
1291 }
1292 EXPORT_SYMBOL(blk_get_request);
1293
1294 /**
1295 * blk_make_request - given a bio, allocate a corresponding struct request.
1296 * @q: target request queue
1297 * @bio: The bio describing the memory mappings that will be submitted for IO.
1298 * It may be a chained-bio properly constructed by block/bio layer.
1299 * @gfp_mask: gfp flags to be used for memory allocation
1300 *
1301 * blk_make_request is the parallel of generic_make_request for BLOCK_PC
1302 * type commands. Where the struct request needs to be farther initialized by
1303 * the caller. It is passed a &struct bio, which describes the memory info of
1304 * the I/O transfer.
1305 *
1306 * The caller of blk_make_request must make sure that bi_io_vec
1307 * are set to describe the memory buffers. That bio_data_dir() will return
1308 * the needed direction of the request. (And all bio's in the passed bio-chain
1309 * are properly set accordingly)
1310 *
1311 * If called under none-sleepable conditions, mapped bio buffers must not
1312 * need bouncing, by calling the appropriate masked or flagged allocator,
1313 * suitable for the target device. Otherwise the call to blk_queue_bounce will
1314 * BUG.
1315 *
1316 * WARNING: When allocating/cloning a bio-chain, careful consideration should be
1317 * given to how you allocate bios. In particular, you cannot use
1318 * __GFP_DIRECT_RECLAIM for anything but the first bio in the chain. Otherwise
1319 * you risk waiting for IO completion of a bio that hasn't been submitted yet,
1320 * thus resulting in a deadlock. Alternatively bios should be allocated using
1321 * bio_kmalloc() instead of bio_alloc(), as that avoids the mempool deadlock.
1322 * If possible a big IO should be split into smaller parts when allocation
1323 * fails. Partial allocation should not be an error, or you risk a live-lock.
1324 */
1325 struct request *blk_make_request(struct request_queue *q, struct bio *bio,
1326 gfp_t gfp_mask)
1327 {
1328 struct request *rq = blk_get_request(q, bio_data_dir(bio), gfp_mask);
1329
1330 if (IS_ERR(rq))
1331 return rq;
1332
1333 blk_rq_set_block_pc(rq);
1334
1335 for_each_bio(bio) {
1336 struct bio *bounce_bio = bio;
1337 int ret;
1338
1339 blk_queue_bounce(q, &bounce_bio);
1340 ret = blk_rq_append_bio(q, rq, bounce_bio);
1341 if (unlikely(ret)) {
1342 blk_put_request(rq);
1343 return ERR_PTR(ret);
1344 }
1345 }
1346
1347 return rq;
1348 }
1349 EXPORT_SYMBOL(blk_make_request);
1350
1351 /**
1352 * blk_rq_set_block_pc - initialize a request to type BLOCK_PC
1353 * @rq: request to be initialized
1354 *
1355 */
1356 void blk_rq_set_block_pc(struct request *rq)
1357 {
1358 rq->cmd_type = REQ_TYPE_BLOCK_PC;
1359 rq->__data_len = 0;
1360 rq->__sector = (sector_t) -1;
1361 rq->bio = rq->biotail = NULL;
1362 memset(rq->__cmd, 0, sizeof(rq->__cmd));
1363 }
1364 EXPORT_SYMBOL(blk_rq_set_block_pc);
1365
1366 /**
1367 * blk_requeue_request - put a request back on queue
1368 * @q: request queue where request should be inserted
1369 * @rq: request to be inserted
1370 *
1371 * Description:
1372 * Drivers often keep queueing requests until the hardware cannot accept
1373 * more, when that condition happens we need to put the request back
1374 * on the queue. Must be called with queue lock held.
1375 */
1376 void blk_requeue_request(struct request_queue *q, struct request *rq)
1377 {
1378 blk_delete_timer(rq);
1379 blk_clear_rq_complete(rq);
1380 trace_block_rq_requeue(q, rq);
1381
1382 if (rq->cmd_flags & REQ_QUEUED)
1383 blk_queue_end_tag(q, rq);
1384
1385 BUG_ON(blk_queued_rq(rq));
1386
1387 elv_requeue_request(q, rq);
1388 }
1389 EXPORT_SYMBOL(blk_requeue_request);
1390
1391 static void add_acct_request(struct request_queue *q, struct request *rq,
1392 int where)
1393 {
1394 blk_account_io_start(rq, true);
1395 __elv_add_request(q, rq, where);
1396 }
1397
1398 static void part_round_stats_single(int cpu, struct hd_struct *part,
1399 unsigned long now)
1400 {
1401 int inflight;
1402
1403 if (now == part->stamp)
1404 return;
1405
1406 inflight = part_in_flight(part);
1407 if (inflight) {
1408 __part_stat_add(cpu, part, time_in_queue,
1409 inflight * (now - part->stamp));
1410 __part_stat_add(cpu, part, io_ticks, (now - part->stamp));
1411 }
1412 part->stamp = now;
1413 }
1414
1415 /**
1416 * part_round_stats() - Round off the performance stats on a struct disk_stats.
1417 * @cpu: cpu number for stats access
1418 * @part: target partition
1419 *
1420 * The average IO queue length and utilisation statistics are maintained
1421 * by observing the current state of the queue length and the amount of
1422 * time it has been in this state for.
1423 *
1424 * Normally, that accounting is done on IO completion, but that can result
1425 * in more than a second's worth of IO being accounted for within any one
1426 * second, leading to >100% utilisation. To deal with that, we call this
1427 * function to do a round-off before returning the results when reading
1428 * /proc/diskstats. This accounts immediately for all queue usage up to
1429 * the current jiffies and restarts the counters again.
1430 */
1431 void part_round_stats(int cpu, struct hd_struct *part)
1432 {
1433 unsigned long now = jiffies;
1434
1435 if (part->partno)
1436 part_round_stats_single(cpu, &part_to_disk(part)->part0, now);
1437 part_round_stats_single(cpu, part, now);
1438 }
1439 EXPORT_SYMBOL_GPL(part_round_stats);
1440
1441 #ifdef CONFIG_PM
1442 static void blk_pm_put_request(struct request *rq)
1443 {
1444 if (rq->q->dev && !(rq->cmd_flags & REQ_PM) && !--rq->q->nr_pending)
1445 pm_runtime_mark_last_busy(rq->q->dev);
1446 }
1447 #else
1448 static inline void blk_pm_put_request(struct request *rq) {}
1449 #endif
1450
1451 /*
1452 * queue lock must be held
1453 */
1454 void __blk_put_request(struct request_queue *q, struct request *req)
1455 {
1456 if (unlikely(!q))
1457 return;
1458
1459 if (q->mq_ops) {
1460 blk_mq_free_request(req);
1461 return;
1462 }
1463
1464 blk_pm_put_request(req);
1465
1466 elv_completed_request(q, req);
1467
1468 /* this is a bio leak */
1469 WARN_ON(req->bio != NULL);
1470
1471 /*
1472 * Request may not have originated from ll_rw_blk. if not,
1473 * it didn't come out of our reserved rq pools
1474 */
1475 if (req->cmd_flags & REQ_ALLOCED) {
1476 unsigned int flags = req->cmd_flags;
1477 struct request_list *rl = blk_rq_rl(req);
1478
1479 BUG_ON(!list_empty(&req->queuelist));
1480 BUG_ON(ELV_ON_HASH(req));
1481
1482 blk_free_request(rl, req);
1483 freed_request(rl, flags);
1484 blk_put_rl(rl);
1485 }
1486 }
1487 EXPORT_SYMBOL_GPL(__blk_put_request);
1488
1489 void blk_put_request(struct request *req)
1490 {
1491 struct request_queue *q = req->q;
1492
1493 if (q->mq_ops)
1494 blk_mq_free_request(req);
1495 else {
1496 unsigned long flags;
1497
1498 spin_lock_irqsave(q->queue_lock, flags);
1499 __blk_put_request(q, req);
1500 spin_unlock_irqrestore(q->queue_lock, flags);
1501 }
1502 }
1503 EXPORT_SYMBOL(blk_put_request);
1504
1505 /**
1506 * blk_add_request_payload - add a payload to a request
1507 * @rq: request to update
1508 * @page: page backing the payload
1509 * @len: length of the payload.
1510 *
1511 * This allows to later add a payload to an already submitted request by
1512 * a block driver. The driver needs to take care of freeing the payload
1513 * itself.
1514 *
1515 * Note that this is a quite horrible hack and nothing but handling of
1516 * discard requests should ever use it.
1517 */
1518 void blk_add_request_payload(struct request *rq, struct page *page,
1519 unsigned int len)
1520 {
1521 struct bio *bio = rq->bio;
1522
1523 bio->bi_io_vec->bv_page = page;
1524 bio->bi_io_vec->bv_offset = 0;
1525 bio->bi_io_vec->bv_len = len;
1526
1527 bio->bi_iter.bi_size = len;
1528 bio->bi_vcnt = 1;
1529 bio->bi_phys_segments = 1;
1530
1531 rq->__data_len = rq->resid_len = len;
1532 rq->nr_phys_segments = 1;
1533 }
1534 EXPORT_SYMBOL_GPL(blk_add_request_payload);
1535
1536 bool bio_attempt_back_merge(struct request_queue *q, struct request *req,
1537 struct bio *bio)
1538 {
1539 const int ff = bio->bi_rw & REQ_FAILFAST_MASK;
1540
1541 if (!ll_back_merge_fn(q, req, bio))
1542 return false;
1543
1544 trace_block_bio_backmerge(q, req, bio);
1545
1546 if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
1547 blk_rq_set_mixed_merge(req);
1548
1549 req->biotail->bi_next = bio;
1550 req->biotail = bio;
1551 req->__data_len += bio->bi_iter.bi_size;
1552 req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
1553
1554 blk_account_io_start(req, false);
1555 return true;
1556 }
1557
1558 bool bio_attempt_front_merge(struct request_queue *q, struct request *req,
1559 struct bio *bio)
1560 {
1561 const int ff = bio->bi_rw & REQ_FAILFAST_MASK;
1562
1563 if (!ll_front_merge_fn(q, req, bio))
1564 return false;
1565
1566 trace_block_bio_frontmerge(q, req, bio);
1567
1568 if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
1569 blk_rq_set_mixed_merge(req);
1570
1571 bio->bi_next = req->bio;
1572 req->bio = bio;
1573
1574 req->__sector = bio->bi_iter.bi_sector;
1575 req->__data_len += bio->bi_iter.bi_size;
1576 req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
1577
1578 blk_account_io_start(req, false);
1579 return true;
1580 }
1581
1582 /**
1583 * blk_attempt_plug_merge - try to merge with %current's plugged list
1584 * @q: request_queue new bio is being queued at
1585 * @bio: new bio being queued
1586 * @request_count: out parameter for number of traversed plugged requests
1587 * @same_queue_rq: pointer to &struct request that gets filled in when
1588 * another request associated with @q is found on the plug list
1589 * (optional, may be %NULL)
1590 *
1591 * Determine whether @bio being queued on @q can be merged with a request
1592 * on %current's plugged list. Returns %true if merge was successful,
1593 * otherwise %false.
1594 *
1595 * Plugging coalesces IOs from the same issuer for the same purpose without
1596 * going through @q->queue_lock. As such it's more of an issuing mechanism
1597 * than scheduling, and the request, while may have elvpriv data, is not
1598 * added on the elevator at this point. In addition, we don't have
1599 * reliable access to the elevator outside queue lock. Only check basic
1600 * merging parameters without querying the elevator.
1601 *
1602 * Caller must ensure !blk_queue_nomerges(q) beforehand.
1603 */
1604 bool blk_attempt_plug_merge(struct request_queue *q, struct bio *bio,
1605 unsigned int *request_count,
1606 struct request **same_queue_rq)
1607 {
1608 struct blk_plug *plug;
1609 struct request *rq;
1610 bool ret = false;
1611 struct list_head *plug_list;
1612
1613 plug = current->plug;
1614 if (!plug)
1615 goto out;
1616 *request_count = 0;
1617
1618 if (q->mq_ops)
1619 plug_list = &plug->mq_list;
1620 else
1621 plug_list = &plug->list;
1622
1623 list_for_each_entry_reverse(rq, plug_list, queuelist) {
1624 int el_ret;
1625
1626 if (rq->q == q) {
1627 (*request_count)++;
1628 /*
1629 * Only blk-mq multiple hardware queues case checks the
1630 * rq in the same queue, there should be only one such
1631 * rq in a queue
1632 **/
1633 if (same_queue_rq)
1634 *same_queue_rq = rq;
1635 }
1636
1637 if (rq->q != q || !blk_rq_merge_ok(rq, bio))
1638 continue;
1639
1640 el_ret = blk_try_merge(rq, bio);
1641 if (el_ret == ELEVATOR_BACK_MERGE) {
1642 ret = bio_attempt_back_merge(q, rq, bio);
1643 if (ret)
1644 break;
1645 } else if (el_ret == ELEVATOR_FRONT_MERGE) {
1646 ret = bio_attempt_front_merge(q, rq, bio);
1647 if (ret)
1648 break;
1649 }
1650 }
1651 out:
1652 return ret;
1653 }
1654
1655 unsigned int blk_plug_queued_count(struct request_queue *q)
1656 {
1657 struct blk_plug *plug;
1658 struct request *rq;
1659 struct list_head *plug_list;
1660 unsigned int ret = 0;
1661
1662 plug = current->plug;
1663 if (!plug)
1664 goto out;
1665
1666 if (q->mq_ops)
1667 plug_list = &plug->mq_list;
1668 else
1669 plug_list = &plug->list;
1670
1671 list_for_each_entry(rq, plug_list, queuelist) {
1672 if (rq->q == q)
1673 ret++;
1674 }
1675 out:
1676 return ret;
1677 }
1678
1679 void init_request_from_bio(struct request *req, struct bio *bio)
1680 {
1681 req->cmd_type = REQ_TYPE_FS;
1682
1683 req->cmd_flags |= bio->bi_rw & REQ_COMMON_MASK;
1684 if (bio->bi_rw & REQ_RAHEAD)
1685 req->cmd_flags |= REQ_FAILFAST_MASK;
1686
1687 req->errors = 0;
1688 req->__sector = bio->bi_iter.bi_sector;
1689 req->ioprio = bio_prio(bio);
1690 blk_rq_bio_prep(req->q, req, bio);
1691 }
1692
1693 static blk_qc_t blk_queue_bio(struct request_queue *q, struct bio *bio)
1694 {
1695 const bool sync = !!(bio->bi_rw & REQ_SYNC);
1696 struct blk_plug *plug;
1697 int el_ret, rw_flags, where = ELEVATOR_INSERT_SORT;
1698 struct request *req;
1699 unsigned int request_count = 0;
1700
1701 /*
1702 * low level driver can indicate that it wants pages above a
1703 * certain limit bounced to low memory (ie for highmem, or even
1704 * ISA dma in theory)
1705 */
1706 blk_queue_bounce(q, &bio);
1707
1708 blk_queue_split(q, &bio, q->bio_split);
1709
1710 if (bio_integrity_enabled(bio) && bio_integrity_prep(bio)) {
1711 bio->bi_error = -EIO;
1712 bio_endio(bio);
1713 return BLK_QC_T_NONE;
1714 }
1715
1716 if (bio->bi_rw & (REQ_FLUSH | REQ_FUA)) {
1717 spin_lock_irq(q->queue_lock);
1718 where = ELEVATOR_INSERT_FLUSH;
1719 goto get_rq;
1720 }
1721
1722 /*
1723 * Check if we can merge with the plugged list before grabbing
1724 * any locks.
1725 */
1726 if (!blk_queue_nomerges(q)) {
1727 if (blk_attempt_plug_merge(q, bio, &request_count, NULL))
1728 return BLK_QC_T_NONE;
1729 } else
1730 request_count = blk_plug_queued_count(q);
1731
1732 spin_lock_irq(q->queue_lock);
1733
1734 el_ret = elv_merge(q, &req, bio);
1735 if (el_ret == ELEVATOR_BACK_MERGE) {
1736 if (bio_attempt_back_merge(q, req, bio)) {
1737 elv_bio_merged(q, req, bio);
1738 if (!attempt_back_merge(q, req))
1739 elv_merged_request(q, req, el_ret);
1740 goto out_unlock;
1741 }
1742 } else if (el_ret == ELEVATOR_FRONT_MERGE) {
1743 if (bio_attempt_front_merge(q, req, bio)) {
1744 elv_bio_merged(q, req, bio);
1745 if (!attempt_front_merge(q, req))
1746 elv_merged_request(q, req, el_ret);
1747 goto out_unlock;
1748 }
1749 }
1750
1751 get_rq:
1752 /*
1753 * This sync check and mask will be re-done in init_request_from_bio(),
1754 * but we need to set it earlier to expose the sync flag to the
1755 * rq allocator and io schedulers.
1756 */
1757 rw_flags = bio_data_dir(bio);
1758 if (sync)
1759 rw_flags |= REQ_SYNC;
1760
1761 /*
1762 * Grab a free request. This is might sleep but can not fail.
1763 * Returns with the queue unlocked.
1764 */
1765 req = get_request(q, rw_flags, bio, GFP_NOIO);
1766 if (IS_ERR(req)) {
1767 bio->bi_error = PTR_ERR(req);
1768 bio_endio(bio);
1769 goto out_unlock;
1770 }
1771
1772 /*
1773 * After dropping the lock and possibly sleeping here, our request
1774 * may now be mergeable after it had proven unmergeable (above).
1775 * We don't worry about that case for efficiency. It won't happen
1776 * often, and the elevators are able to handle it.
1777 */
1778 init_request_from_bio(req, bio);
1779
1780 if (test_bit(QUEUE_FLAG_SAME_COMP, &q->queue_flags))
1781 req->cpu = raw_smp_processor_id();
1782
1783 plug = current->plug;
1784 if (plug) {
1785 /*
1786 * If this is the first request added after a plug, fire
1787 * of a plug trace.
1788 */
1789 if (!request_count)
1790 trace_block_plug(q);
1791 else {
1792 if (request_count >= BLK_MAX_REQUEST_COUNT) {
1793 blk_flush_plug_list(plug, false);
1794 trace_block_plug(q);
1795 }
1796 }
1797 list_add_tail(&req->queuelist, &plug->list);
1798 blk_account_io_start(req, true);
1799 } else {
1800 spin_lock_irq(q->queue_lock);
1801 add_acct_request(q, req, where);
1802 __blk_run_queue(q);
1803 out_unlock:
1804 spin_unlock_irq(q->queue_lock);
1805 }
1806
1807 return BLK_QC_T_NONE;
1808 }
1809
1810 /*
1811 * If bio->bi_dev is a partition, remap the location
1812 */
1813 static inline void blk_partition_remap(struct bio *bio)
1814 {
1815 struct block_device *bdev = bio->bi_bdev;
1816
1817 if (bio_sectors(bio) && bdev != bdev->bd_contains) {
1818 struct hd_struct *p = bdev->bd_part;
1819
1820 bio->bi_iter.bi_sector += p->start_sect;
1821 bio->bi_bdev = bdev->bd_contains;
1822
1823 trace_block_bio_remap(bdev_get_queue(bio->bi_bdev), bio,
1824 bdev->bd_dev,
1825 bio->bi_iter.bi_sector - p->start_sect);
1826 }
1827 }
1828
1829 static void handle_bad_sector(struct bio *bio)
1830 {
1831 char b[BDEVNAME_SIZE];
1832
1833 printk(KERN_INFO "attempt to access beyond end of device\n");
1834 printk(KERN_INFO "%s: rw=%ld, want=%Lu, limit=%Lu\n",
1835 bdevname(bio->bi_bdev, b),
1836 bio->bi_rw,
1837 (unsigned long long)bio_end_sector(bio),
1838 (long long)(i_size_read(bio->bi_bdev->bd_inode) >> 9));
1839 }
1840
1841 #ifdef CONFIG_FAIL_MAKE_REQUEST
1842
1843 static DECLARE_FAULT_ATTR(fail_make_request);
1844
1845 static int __init setup_fail_make_request(char *str)
1846 {
1847 return setup_fault_attr(&fail_make_request, str);
1848 }
1849 __setup("fail_make_request=", setup_fail_make_request);
1850
1851 static bool should_fail_request(struct hd_struct *part, unsigned int bytes)
1852 {
1853 return part->make_it_fail && should_fail(&fail_make_request, bytes);
1854 }
1855
1856 static int __init fail_make_request_debugfs(void)
1857 {
1858 struct dentry *dir = fault_create_debugfs_attr("fail_make_request",
1859 NULL, &fail_make_request);
1860
1861 return PTR_ERR_OR_ZERO(dir);
1862 }
1863
1864 late_initcall(fail_make_request_debugfs);
1865
1866 #else /* CONFIG_FAIL_MAKE_REQUEST */
1867
1868 static inline bool should_fail_request(struct hd_struct *part,
1869 unsigned int bytes)
1870 {
1871 return false;
1872 }
1873
1874 #endif /* CONFIG_FAIL_MAKE_REQUEST */
1875
1876 /*
1877 * Check whether this bio extends beyond the end of the device.
1878 */
1879 static inline int bio_check_eod(struct bio *bio, unsigned int nr_sectors)
1880 {
1881 sector_t maxsector;
1882
1883 if (!nr_sectors)
1884 return 0;
1885
1886 /* Test device or partition size, when known. */
1887 maxsector = i_size_read(bio->bi_bdev->bd_inode) >> 9;
1888 if (maxsector) {
1889 sector_t sector = bio->bi_iter.bi_sector;
1890
1891 if (maxsector < nr_sectors || maxsector - nr_sectors < sector) {
1892 /*
1893 * This may well happen - the kernel calls bread()
1894 * without checking the size of the device, e.g., when
1895 * mounting a device.
1896 */
1897 handle_bad_sector(bio);
1898 return 1;
1899 }
1900 }
1901
1902 return 0;
1903 }
1904
1905 static noinline_for_stack bool
1906 generic_make_request_checks(struct bio *bio)
1907 {
1908 struct request_queue *q;
1909 int nr_sectors = bio_sectors(bio);
1910 int err = -EIO;
1911 char b[BDEVNAME_SIZE];
1912 struct hd_struct *part;
1913
1914 might_sleep();
1915
1916 if (bio_check_eod(bio, nr_sectors))
1917 goto end_io;
1918
1919 q = bdev_get_queue(bio->bi_bdev);
1920 if (unlikely(!q)) {
1921 printk(KERN_ERR
1922 "generic_make_request: Trying to access "
1923 "nonexistent block-device %s (%Lu)\n",
1924 bdevname(bio->bi_bdev, b),
1925 (long long) bio->bi_iter.bi_sector);
1926 goto end_io;
1927 }
1928
1929 part = bio->bi_bdev->bd_part;
1930 if (should_fail_request(part, bio->bi_iter.bi_size) ||
1931 should_fail_request(&part_to_disk(part)->part0,
1932 bio->bi_iter.bi_size))
1933 goto end_io;
1934
1935 /*
1936 * If this device has partitions, remap block n
1937 * of partition p to block n+start(p) of the disk.
1938 */
1939 blk_partition_remap(bio);
1940
1941 if (bio_check_eod(bio, nr_sectors))
1942 goto end_io;
1943
1944 /*
1945 * Filter flush bio's early so that make_request based
1946 * drivers without flush support don't have to worry
1947 * about them.
1948 */
1949 if ((bio->bi_rw & (REQ_FLUSH | REQ_FUA)) && !q->flush_flags) {
1950 bio->bi_rw &= ~(REQ_FLUSH | REQ_FUA);
1951 if (!nr_sectors) {
1952 err = 0;
1953 goto end_io;
1954 }
1955 }
1956
1957 if ((bio->bi_rw & REQ_DISCARD) &&
1958 (!blk_queue_discard(q) ||
1959 ((bio->bi_rw & REQ_SECURE) && !blk_queue_secdiscard(q)))) {
1960 err = -EOPNOTSUPP;
1961 goto end_io;
1962 }
1963
1964 if (bio->bi_rw & REQ_WRITE_SAME && !bdev_write_same(bio->bi_bdev)) {
1965 err = -EOPNOTSUPP;
1966 goto end_io;
1967 }
1968
1969 /*
1970 * Various block parts want %current->io_context and lazy ioc
1971 * allocation ends up trading a lot of pain for a small amount of
1972 * memory. Just allocate it upfront. This may fail and block
1973 * layer knows how to live with it.
1974 */
1975 create_io_context(GFP_ATOMIC, q->node);
1976
1977 if (!blkcg_bio_issue_check(q, bio))
1978 return false;
1979
1980 trace_block_bio_queue(q, bio);
1981 return true;
1982
1983 end_io:
1984 bio->bi_error = err;
1985 bio_endio(bio);
1986 return false;
1987 }
1988
1989 /**
1990 * generic_make_request - hand a buffer to its device driver for I/O
1991 * @bio: The bio describing the location in memory and on the device.
1992 *
1993 * generic_make_request() is used to make I/O requests of block
1994 * devices. It is passed a &struct bio, which describes the I/O that needs
1995 * to be done.
1996 *
1997 * generic_make_request() does not return any status. The
1998 * success/failure status of the request, along with notification of
1999 * completion, is delivered asynchronously through the bio->bi_end_io
2000 * function described (one day) else where.
2001 *
2002 * The caller of generic_make_request must make sure that bi_io_vec
2003 * are set to describe the memory buffer, and that bi_dev and bi_sector are
2004 * set to describe the device address, and the
2005 * bi_end_io and optionally bi_private are set to describe how
2006 * completion notification should be signaled.
2007 *
2008 * generic_make_request and the drivers it calls may use bi_next if this
2009 * bio happens to be merged with someone else, and may resubmit the bio to
2010 * a lower device by calling into generic_make_request recursively, which
2011 * means the bio should NOT be touched after the call to ->make_request_fn.
2012 */
2013 blk_qc_t generic_make_request(struct bio *bio)
2014 {
2015 /*
2016 * bio_list_on_stack[0] contains bios submitted by the current
2017 * make_request_fn.
2018 * bio_list_on_stack[1] contains bios that were submitted before
2019 * the current make_request_fn, but that haven't been processed
2020 * yet.
2021 */
2022 struct bio_list bio_list_on_stack[2];
2023 blk_qc_t ret = BLK_QC_T_NONE;
2024
2025 if (!generic_make_request_checks(bio))
2026 goto out;
2027
2028 /*
2029 * We only want one ->make_request_fn to be active at a time, else
2030 * stack usage with stacked devices could be a problem. So use
2031 * current->bio_list to keep a list of requests submited by a
2032 * make_request_fn function. current->bio_list is also used as a
2033 * flag to say if generic_make_request is currently active in this
2034 * task or not. If it is NULL, then no make_request is active. If
2035 * it is non-NULL, then a make_request is active, and new requests
2036 * should be added at the tail
2037 */
2038 if (current->bio_list) {
2039 bio_list_add(&current->bio_list[0], bio);
2040 goto out;
2041 }
2042
2043 /* following loop may be a bit non-obvious, and so deserves some
2044 * explanation.
2045 * Before entering the loop, bio->bi_next is NULL (as all callers
2046 * ensure that) so we have a list with a single bio.
2047 * We pretend that we have just taken it off a longer list, so
2048 * we assign bio_list to a pointer to the bio_list_on_stack,
2049 * thus initialising the bio_list of new bios to be
2050 * added. ->make_request() may indeed add some more bios
2051 * through a recursive call to generic_make_request. If it
2052 * did, we find a non-NULL value in bio_list and re-enter the loop
2053 * from the top. In this case we really did just take the bio
2054 * of the top of the list (no pretending) and so remove it from
2055 * bio_list, and call into ->make_request() again.
2056 */
2057 BUG_ON(bio->bi_next);
2058 bio_list_init(&bio_list_on_stack[0]);
2059 current->bio_list = bio_list_on_stack;
2060 do {
2061 struct request_queue *q = bdev_get_queue(bio->bi_bdev);
2062
2063 if (likely(blk_queue_enter(q, false) == 0)) {
2064 struct bio_list lower, same;
2065
2066 /* Create a fresh bio_list for all subordinate requests */
2067 bio_list_on_stack[1] = bio_list_on_stack[0];
2068 bio_list_init(&bio_list_on_stack[0]);
2069
2070 ret = q->make_request_fn(q, bio);
2071
2072 blk_queue_exit(q);
2073
2074 /* sort new bios into those for a lower level
2075 * and those for the same level
2076 */
2077 bio_list_init(&lower);
2078 bio_list_init(&same);
2079 while ((bio = bio_list_pop(&bio_list_on_stack[0])) != NULL)
2080 if (q == bdev_get_queue(bio->bi_bdev))
2081 bio_list_add(&same, bio);
2082 else
2083 bio_list_add(&lower, bio);
2084 /* now assemble so we handle the lowest level first */
2085 bio_list_merge(&bio_list_on_stack[0], &lower);
2086 bio_list_merge(&bio_list_on_stack[0], &same);
2087 bio_list_merge(&bio_list_on_stack[0], &bio_list_on_stack[1]);
2088 } else {
2089 bio_io_error(bio);
2090 }
2091 bio = bio_list_pop(&bio_list_on_stack[0]);
2092 } while (bio);
2093 current->bio_list = NULL; /* deactivate */
2094
2095 out:
2096 return ret;
2097 }
2098 EXPORT_SYMBOL(generic_make_request);
2099
2100 /**
2101 * submit_bio - submit a bio to the block device layer for I/O
2102 * @rw: whether to %READ or %WRITE, or maybe to %READA (read ahead)
2103 * @bio: The &struct bio which describes the I/O
2104 *
2105 * submit_bio() is very similar in purpose to generic_make_request(), and
2106 * uses that function to do most of the work. Both are fairly rough
2107 * interfaces; @bio must be presetup and ready for I/O.
2108 *
2109 */
2110 blk_qc_t submit_bio(int rw, struct bio *bio)
2111 {
2112 bio->bi_rw |= rw;
2113
2114 /*
2115 * If it's a regular read/write or a barrier with data attached,
2116 * go through the normal accounting stuff before submission.
2117 */
2118 if (bio_has_data(bio)) {
2119 unsigned int count;
2120
2121 if (unlikely(rw & REQ_WRITE_SAME))
2122 count = bdev_logical_block_size(bio->bi_bdev) >> 9;
2123 else
2124 count = bio_sectors(bio);
2125
2126 if (rw & WRITE) {
2127 count_vm_events(PGPGOUT, count);
2128 } else {
2129 task_io_account_read(bio->bi_iter.bi_size);
2130 count_vm_events(PGPGIN, count);
2131 }
2132
2133 if (unlikely(block_dump)) {
2134 char b[BDEVNAME_SIZE];
2135 printk(KERN_DEBUG "%s(%d): %s block %Lu on %s (%u sectors)\n",
2136 current->comm, task_pid_nr(current),
2137 (rw & WRITE) ? "WRITE" : "READ",
2138 (unsigned long long)bio->bi_iter.bi_sector,
2139 bdevname(bio->bi_bdev, b),
2140 count);
2141 }
2142 }
2143
2144 return generic_make_request(bio);
2145 }
2146 EXPORT_SYMBOL(submit_bio);
2147
2148 /**
2149 * blk_cloned_rq_check_limits - Helper function to check a cloned request
2150 * for new the queue limits
2151 * @q: the queue
2152 * @rq: the request being checked
2153 *
2154 * Description:
2155 * @rq may have been made based on weaker limitations of upper-level queues
2156 * in request stacking drivers, and it may violate the limitation of @q.
2157 * Since the block layer and the underlying device driver trust @rq
2158 * after it is inserted to @q, it should be checked against @q before
2159 * the insertion using this generic function.
2160 *
2161 * Request stacking drivers like request-based dm may change the queue
2162 * limits when retrying requests on other queues. Those requests need
2163 * to be checked against the new queue limits again during dispatch.
2164 */
2165 static int blk_cloned_rq_check_limits(struct request_queue *q,
2166 struct request *rq)
2167 {
2168 if (blk_rq_sectors(rq) > blk_queue_get_max_sectors(q, rq->cmd_flags)) {
2169 printk(KERN_ERR "%s: over max size limit.\n", __func__);
2170 return -EIO;
2171 }
2172
2173 /*
2174 * queue's settings related to segment counting like q->bounce_pfn
2175 * may differ from that of other stacking queues.
2176 * Recalculate it to check the request correctly on this queue's
2177 * limitation.
2178 */
2179 blk_recalc_rq_segments(rq);
2180 if (rq->nr_phys_segments > queue_max_segments(q)) {
2181 printk(KERN_ERR "%s: over max segments limit.\n", __func__);
2182 return -EIO;
2183 }
2184
2185 return 0;
2186 }
2187
2188 /**
2189 * blk_insert_cloned_request - Helper for stacking drivers to submit a request
2190 * @q: the queue to submit the request
2191 * @rq: the request being queued
2192 */
2193 int blk_insert_cloned_request(struct request_queue *q, struct request *rq)
2194 {
2195 unsigned long flags;
2196 int where = ELEVATOR_INSERT_BACK;
2197
2198 if (blk_cloned_rq_check_limits(q, rq))
2199 return -EIO;
2200
2201 if (rq->rq_disk &&
2202 should_fail_request(&rq->rq_disk->part0, blk_rq_bytes(rq)))
2203 return -EIO;
2204
2205 if (q->mq_ops) {
2206 if (blk_queue_io_stat(q))
2207 blk_account_io_start(rq, true);
2208 blk_mq_insert_request(rq, false, true, false);
2209 return 0;
2210 }
2211
2212 spin_lock_irqsave(q->queue_lock, flags);
2213 if (unlikely(blk_queue_dying(q))) {
2214 spin_unlock_irqrestore(q->queue_lock, flags);
2215 return -ENODEV;
2216 }
2217
2218 /*
2219 * Submitting request must be dequeued before calling this function
2220 * because it will be linked to another request_queue
2221 */
2222 BUG_ON(blk_queued_rq(rq));
2223
2224 if (rq->cmd_flags & (REQ_FLUSH|REQ_FUA))
2225 where = ELEVATOR_INSERT_FLUSH;
2226
2227 add_acct_request(q, rq, where);
2228 if (where == ELEVATOR_INSERT_FLUSH)
2229 __blk_run_queue(q);
2230 spin_unlock_irqrestore(q->queue_lock, flags);
2231
2232 return 0;
2233 }
2234 EXPORT_SYMBOL_GPL(blk_insert_cloned_request);
2235
2236 /**
2237 * blk_rq_err_bytes - determine number of bytes till the next failure boundary
2238 * @rq: request to examine
2239 *
2240 * Description:
2241 * A request could be merge of IOs which require different failure
2242 * handling. This function determines the number of bytes which
2243 * can be failed from the beginning of the request without
2244 * crossing into area which need to be retried further.
2245 *
2246 * Return:
2247 * The number of bytes to fail.
2248 *
2249 * Context:
2250 * queue_lock must be held.
2251 */
2252 unsigned int blk_rq_err_bytes(const struct request *rq)
2253 {
2254 unsigned int ff = rq->cmd_flags & REQ_FAILFAST_MASK;
2255 unsigned int bytes = 0;
2256 struct bio *bio;
2257
2258 if (!(rq->cmd_flags & REQ_MIXED_MERGE))
2259 return blk_rq_bytes(rq);
2260
2261 /*
2262 * Currently the only 'mixing' which can happen is between
2263 * different fastfail types. We can safely fail portions
2264 * which have all the failfast bits that the first one has -
2265 * the ones which are at least as eager to fail as the first
2266 * one.
2267 */
2268 for (bio = rq->bio; bio; bio = bio->bi_next) {
2269 if ((bio->bi_rw & ff) != ff)
2270 break;
2271 bytes += bio->bi_iter.bi_size;
2272 }
2273
2274 /* this could lead to infinite loop */
2275 BUG_ON(blk_rq_bytes(rq) && !bytes);
2276 return bytes;
2277 }
2278 EXPORT_SYMBOL_GPL(blk_rq_err_bytes);
2279
2280 void blk_account_io_completion(struct request *req, unsigned int bytes)
2281 {
2282 if (blk_do_io_stat(req)) {
2283 const int rw = rq_data_dir(req);
2284 struct hd_struct *part;
2285 int cpu;
2286
2287 cpu = part_stat_lock();
2288 part = req->part;
2289 part_stat_add(cpu, part, sectors[rw], bytes >> 9);
2290 part_stat_unlock();
2291 }
2292 }
2293
2294 void blk_account_io_done(struct request *req)
2295 {
2296 /*
2297 * Account IO completion. flush_rq isn't accounted as a
2298 * normal IO on queueing nor completion. Accounting the
2299 * containing request is enough.
2300 */
2301 if (blk_do_io_stat(req) && !(req->cmd_flags & REQ_FLUSH_SEQ)) {
2302 unsigned long duration = jiffies - req->start_time;
2303 const int rw = rq_data_dir(req);
2304 struct hd_struct *part;
2305 int cpu;
2306
2307 cpu = part_stat_lock();
2308 part = req->part;
2309
2310 part_stat_inc(cpu, part, ios[rw]);
2311 part_stat_add(cpu, part, ticks[rw], duration);
2312 part_round_stats(cpu, part);
2313 part_dec_in_flight(part, rw);
2314
2315 hd_struct_put(part);
2316 part_stat_unlock();
2317 }
2318 }
2319
2320 #ifdef CONFIG_PM
2321 /*
2322 * Don't process normal requests when queue is suspended
2323 * or in the process of suspending/resuming
2324 */
2325 static struct request *blk_pm_peek_request(struct request_queue *q,
2326 struct request *rq)
2327 {
2328 if (q->dev && (q->rpm_status == RPM_SUSPENDED ||
2329 (q->rpm_status != RPM_ACTIVE && !(rq->cmd_flags & REQ_PM))))
2330 return NULL;
2331 else
2332 return rq;
2333 }
2334 #else
2335 static inline struct request *blk_pm_peek_request(struct request_queue *q,
2336 struct request *rq)
2337 {
2338 return rq;
2339 }
2340 #endif
2341
2342 void blk_account_io_start(struct request *rq, bool new_io)
2343 {
2344 struct hd_struct *part;
2345 int rw = rq_data_dir(rq);
2346 int cpu;
2347
2348 if (!blk_do_io_stat(rq))
2349 return;
2350
2351 cpu = part_stat_lock();
2352
2353 if (!new_io) {
2354 part = rq->part;
2355 part_stat_inc(cpu, part, merges[rw]);
2356 } else {
2357 part = disk_map_sector_rcu(rq->rq_disk, blk_rq_pos(rq));
2358 if (!hd_struct_try_get(part)) {
2359 /*
2360 * The partition is already being removed,
2361 * the request will be accounted on the disk only
2362 *
2363 * We take a reference on disk->part0 although that
2364 * partition will never be deleted, so we can treat
2365 * it as any other partition.
2366 */
2367 part = &rq->rq_disk->part0;
2368 hd_struct_get(part);
2369 }
2370 part_round_stats(cpu, part);
2371 part_inc_in_flight(part, rw);
2372 rq->part = part;
2373 }
2374
2375 part_stat_unlock();
2376 }
2377
2378 /**
2379 * blk_peek_request - peek at the top of a request queue
2380 * @q: request queue to peek at
2381 *
2382 * Description:
2383 * Return the request at the top of @q. The returned request
2384 * should be started using blk_start_request() before LLD starts
2385 * processing it.
2386 *
2387 * Return:
2388 * Pointer to the request at the top of @q if available. Null
2389 * otherwise.
2390 *
2391 * Context:
2392 * queue_lock must be held.
2393 */
2394 struct request *blk_peek_request(struct request_queue *q)
2395 {
2396 struct request *rq;
2397 int ret;
2398
2399 while ((rq = __elv_next_request(q)) != NULL) {
2400
2401 rq = blk_pm_peek_request(q, rq);
2402 if (!rq)
2403 break;
2404
2405 if (!(rq->cmd_flags & REQ_STARTED)) {
2406 /*
2407 * This is the first time the device driver
2408 * sees this request (possibly after
2409 * requeueing). Notify IO scheduler.
2410 */
2411 if (rq->cmd_flags & REQ_SORTED)
2412 elv_activate_rq(q, rq);
2413
2414 /*
2415 * just mark as started even if we don't start
2416 * it, a request that has been delayed should
2417 * not be passed by new incoming requests
2418 */
2419 rq->cmd_flags |= REQ_STARTED;
2420 trace_block_rq_issue(q, rq);
2421 }
2422
2423 if (!q->boundary_rq || q->boundary_rq == rq) {
2424 q->end_sector = rq_end_sector(rq);
2425 q->boundary_rq = NULL;
2426 }
2427
2428 if (rq->cmd_flags & REQ_DONTPREP)
2429 break;
2430
2431 if (q->dma_drain_size && blk_rq_bytes(rq)) {
2432 /*
2433 * make sure space for the drain appears we
2434 * know we can do this because max_hw_segments
2435 * has been adjusted to be one fewer than the
2436 * device can handle
2437 */
2438 rq->nr_phys_segments++;
2439 }
2440
2441 if (!q->prep_rq_fn)
2442 break;
2443
2444 ret = q->prep_rq_fn(q, rq);
2445 if (ret == BLKPREP_OK) {
2446 break;
2447 } else if (ret == BLKPREP_DEFER) {
2448 /*
2449 * the request may have been (partially) prepped.
2450 * we need to keep this request in the front to
2451 * avoid resource deadlock. REQ_STARTED will
2452 * prevent other fs requests from passing this one.
2453 */
2454 if (q->dma_drain_size && blk_rq_bytes(rq) &&
2455 !(rq->cmd_flags & REQ_DONTPREP)) {
2456 /*
2457 * remove the space for the drain we added
2458 * so that we don't add it again
2459 */
2460 --rq->nr_phys_segments;
2461 }
2462
2463 rq = NULL;
2464 break;
2465 } else if (ret == BLKPREP_KILL) {
2466 rq->cmd_flags |= REQ_QUIET;
2467 /*
2468 * Mark this request as started so we don't trigger
2469 * any debug logic in the end I/O path.
2470 */
2471 blk_start_request(rq);
2472 __blk_end_request_all(rq, -EIO);
2473 } else {
2474 printk(KERN_ERR "%s: bad return=%d\n", __func__, ret);
2475 break;
2476 }
2477 }
2478
2479 return rq;
2480 }
2481 EXPORT_SYMBOL(blk_peek_request);
2482
2483 void blk_dequeue_request(struct request *rq)
2484 {
2485 struct request_queue *q = rq->q;
2486
2487 BUG_ON(list_empty(&rq->queuelist));
2488 BUG_ON(ELV_ON_HASH(rq));
2489
2490 list_del_init(&rq->queuelist);
2491
2492 /*
2493 * the time frame between a request being removed from the lists
2494 * and to it is freed is accounted as io that is in progress at
2495 * the driver side.
2496 */
2497 if (blk_account_rq(rq)) {
2498 q->in_flight[rq_is_sync(rq)]++;
2499 set_io_start_time_ns(rq);
2500 }
2501 }
2502
2503 /**
2504 * blk_start_request - start request processing on the driver
2505 * @req: request to dequeue
2506 *
2507 * Description:
2508 * Dequeue @req and start timeout timer on it. This hands off the
2509 * request to the driver.
2510 *
2511 * Block internal functions which don't want to start timer should
2512 * call blk_dequeue_request().
2513 *
2514 * Context:
2515 * queue_lock must be held.
2516 */
2517 void blk_start_request(struct request *req)
2518 {
2519 blk_dequeue_request(req);
2520
2521 /*
2522 * We are now handing the request to the hardware, initialize
2523 * resid_len to full count and add the timeout handler.
2524 */
2525 req->resid_len = blk_rq_bytes(req);
2526 if (unlikely(blk_bidi_rq(req)))
2527 req->next_rq->resid_len = blk_rq_bytes(req->next_rq);
2528
2529 BUG_ON(test_bit(REQ_ATOM_COMPLETE, &req->atomic_flags));
2530 blk_add_timer(req);
2531 }
2532 EXPORT_SYMBOL(blk_start_request);
2533
2534 /**
2535 * blk_fetch_request - fetch a request from a request queue
2536 * @q: request queue to fetch a request from
2537 *
2538 * Description:
2539 * Return the request at the top of @q. The request is started on
2540 * return and LLD can start processing it immediately.
2541 *
2542 * Return:
2543 * Pointer to the request at the top of @q if available. Null
2544 * otherwise.
2545 *
2546 * Context:
2547 * queue_lock must be held.
2548 */
2549 struct request *blk_fetch_request(struct request_queue *q)
2550 {
2551 struct request *rq;
2552
2553 rq = blk_peek_request(q);
2554 if (rq)
2555 blk_start_request(rq);
2556 return rq;
2557 }
2558 EXPORT_SYMBOL(blk_fetch_request);
2559
2560 /**
2561 * blk_update_request - Special helper function for request stacking drivers
2562 * @req: the request being processed
2563 * @error: %0 for success, < %0 for error
2564 * @nr_bytes: number of bytes to complete @req
2565 *
2566 * Description:
2567 * Ends I/O on a number of bytes attached to @req, but doesn't complete
2568 * the request structure even if @req doesn't have leftover.
2569 * If @req has leftover, sets it up for the next range of segments.
2570 *
2571 * This special helper function is only for request stacking drivers
2572 * (e.g. request-based dm) so that they can handle partial completion.
2573 * Actual device drivers should use blk_end_request instead.
2574 *
2575 * Passing the result of blk_rq_bytes() as @nr_bytes guarantees
2576 * %false return from this function.
2577 *
2578 * Return:
2579 * %false - this request doesn't have any more data
2580 * %true - this request has more data
2581 **/
2582 bool blk_update_request(struct request *req, int error, unsigned int nr_bytes)
2583 {
2584 int total_bytes;
2585
2586 trace_block_rq_complete(req->q, req, nr_bytes);
2587
2588 if (!req->bio)
2589 return false;
2590
2591 /*
2592 * For fs requests, rq is just carrier of independent bio's
2593 * and each partial completion should be handled separately.
2594 * Reset per-request error on each partial completion.
2595 *
2596 * TODO: tj: This is too subtle. It would be better to let
2597 * low level drivers do what they see fit.
2598 */
2599 if (req->cmd_type == REQ_TYPE_FS)
2600 req->errors = 0;
2601
2602 if (error && req->cmd_type == REQ_TYPE_FS &&
2603 !(req->cmd_flags & REQ_QUIET)) {
2604 char *error_type;
2605
2606 switch (error) {
2607 case -ENOLINK:
2608 error_type = "recoverable transport";
2609 break;
2610 case -EREMOTEIO:
2611 error_type = "critical target";
2612 break;
2613 case -EBADE:
2614 error_type = "critical nexus";
2615 break;
2616 case -ETIMEDOUT:
2617 error_type = "timeout";
2618 break;
2619 case -ENOSPC:
2620 error_type = "critical space allocation";
2621 break;
2622 case -ENODATA:
2623 error_type = "critical medium";
2624 break;
2625 case -EIO:
2626 default:
2627 error_type = "I/O";
2628 break;
2629 }
2630 printk_ratelimited(KERN_ERR "%s: %s error, dev %s, sector %llu\n",
2631 __func__, error_type, req->rq_disk ?
2632 req->rq_disk->disk_name : "?",
2633 (unsigned long long)blk_rq_pos(req));
2634
2635 }
2636
2637 blk_account_io_completion(req, nr_bytes);
2638
2639 total_bytes = 0;
2640 while (req->bio) {
2641 struct bio *bio = req->bio;
2642 unsigned bio_bytes = min(bio->bi_iter.bi_size, nr_bytes);
2643
2644 if (bio_bytes == bio->bi_iter.bi_size)
2645 req->bio = bio->bi_next;
2646
2647 req_bio_endio(req, bio, bio_bytes, error);
2648
2649 total_bytes += bio_bytes;
2650 nr_bytes -= bio_bytes;
2651
2652 if (!nr_bytes)
2653 break;
2654 }
2655
2656 /*
2657 * completely done
2658 */
2659 if (!req->bio) {
2660 /*
2661 * Reset counters so that the request stacking driver
2662 * can find how many bytes remain in the request
2663 * later.
2664 */
2665 req->__data_len = 0;
2666 return false;
2667 }
2668
2669 req->__data_len -= total_bytes;
2670
2671 /* update sector only for requests with clear definition of sector */
2672 if (req->cmd_type == REQ_TYPE_FS)
2673 req->__sector += total_bytes >> 9;
2674
2675 /* mixed attributes always follow the first bio */
2676 if (req->cmd_flags & REQ_MIXED_MERGE) {
2677 req->cmd_flags &= ~REQ_FAILFAST_MASK;
2678 req->cmd_flags |= req->bio->bi_rw & REQ_FAILFAST_MASK;
2679 }
2680
2681 /*
2682 * If total number of sectors is less than the first segment
2683 * size, something has gone terribly wrong.
2684 */
2685 if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {
2686 blk_dump_rq_flags(req, "request botched");
2687 req->__data_len = blk_rq_cur_bytes(req);
2688 }
2689
2690 /* recalculate the number of segments */
2691 blk_recalc_rq_segments(req);
2692
2693 return true;
2694 }
2695 EXPORT_SYMBOL_GPL(blk_update_request);
2696
2697 static bool blk_update_bidi_request(struct request *rq, int error,
2698 unsigned int nr_bytes,
2699 unsigned int bidi_bytes)
2700 {
2701 if (blk_update_request(rq, error, nr_bytes))
2702 return true;
2703
2704 /* Bidi request must be completed as a whole */
2705 if (unlikely(blk_bidi_rq(rq)) &&
2706 blk_update_request(rq->next_rq, error, bidi_bytes))
2707 return true;
2708
2709 if (blk_queue_add_random(rq->q))
2710 add_disk_randomness(rq->rq_disk);
2711
2712 return false;
2713 }
2714
2715 /**
2716 * blk_unprep_request - unprepare a request
2717 * @req: the request
2718 *
2719 * This function makes a request ready for complete resubmission (or
2720 * completion). It happens only after all error handling is complete,
2721 * so represents the appropriate moment to deallocate any resources
2722 * that were allocated to the request in the prep_rq_fn. The queue
2723 * lock is held when calling this.
2724 */
2725 void blk_unprep_request(struct request *req)
2726 {
2727 struct request_queue *q = req->q;
2728
2729 req->cmd_flags &= ~REQ_DONTPREP;
2730 if (q->unprep_rq_fn)
2731 q->unprep_rq_fn(q, req);
2732 }
2733 EXPORT_SYMBOL_GPL(blk_unprep_request);
2734
2735 /*
2736 * queue lock must be held
2737 */
2738 void blk_finish_request(struct request *req, int error)
2739 {
2740 if (req->cmd_flags & REQ_QUEUED)
2741 blk_queue_end_tag(req->q, req);
2742
2743 BUG_ON(blk_queued_rq(req));
2744
2745 if (unlikely(laptop_mode) && req->cmd_type == REQ_TYPE_FS)
2746 laptop_io_completion(req->q->backing_dev_info);
2747
2748 blk_delete_timer(req);
2749
2750 if (req->cmd_flags & REQ_DONTPREP)
2751 blk_unprep_request(req);
2752
2753 blk_account_io_done(req);
2754
2755 if (req->end_io)
2756 req->end_io(req, error);
2757 else {
2758 if (blk_bidi_rq(req))
2759 __blk_put_request(req->next_rq->q, req->next_rq);
2760
2761 __blk_put_request(req->q, req);
2762 }
2763 }
2764 EXPORT_SYMBOL(blk_finish_request);
2765
2766 /**
2767 * blk_end_bidi_request - Complete a bidi request
2768 * @rq: the request to complete
2769 * @error: %0 for success, < %0 for error
2770 * @nr_bytes: number of bytes to complete @rq
2771 * @bidi_bytes: number of bytes to complete @rq->next_rq
2772 *
2773 * Description:
2774 * Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
2775 * Drivers that supports bidi can safely call this member for any
2776 * type of request, bidi or uni. In the later case @bidi_bytes is
2777 * just ignored.
2778 *
2779 * Return:
2780 * %false - we are done with this request
2781 * %true - still buffers pending for this request
2782 **/
2783 static bool blk_end_bidi_request(struct request *rq, int error,
2784 unsigned int nr_bytes, unsigned int bidi_bytes)
2785 {
2786 struct request_queue *q = rq->q;
2787 unsigned long flags;
2788
2789 if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2790 return true;
2791
2792 spin_lock_irqsave(q->queue_lock, flags);
2793 blk_finish_request(rq, error);
2794 spin_unlock_irqrestore(q->queue_lock, flags);
2795
2796 return false;
2797 }
2798
2799 /**
2800 * __blk_end_bidi_request - Complete a bidi request with queue lock held
2801 * @rq: the request to complete
2802 * @error: %0 for success, < %0 for error
2803 * @nr_bytes: number of bytes to complete @rq
2804 * @bidi_bytes: number of bytes to complete @rq->next_rq
2805 *
2806 * Description:
2807 * Identical to blk_end_bidi_request() except that queue lock is
2808 * assumed to be locked on entry and remains so on return.
2809 *
2810 * Return:
2811 * %false - we are done with this request
2812 * %true - still buffers pending for this request
2813 **/
2814 bool __blk_end_bidi_request(struct request *rq, int error,
2815 unsigned int nr_bytes, unsigned int bidi_bytes)
2816 {
2817 if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
2818 return true;
2819
2820 blk_finish_request(rq, error);
2821
2822 return false;
2823 }
2824
2825 /**
2826 * blk_end_request - Helper function for drivers to complete the request.
2827 * @rq: the request being processed
2828 * @error: %0 for success, < %0 for error
2829 * @nr_bytes: number of bytes to complete
2830 *
2831 * Description:
2832 * Ends I/O on a number of bytes attached to @rq.
2833 * If @rq has leftover, sets it up for the next range of segments.
2834 *
2835 * Return:
2836 * %false - we are done with this request
2837 * %true - still buffers pending for this request
2838 **/
2839 bool blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
2840 {
2841 return blk_end_bidi_request(rq, error, nr_bytes, 0);
2842 }
2843 EXPORT_SYMBOL(blk_end_request);
2844
2845 /**
2846 * blk_end_request_all - Helper function for drives to finish the request.
2847 * @rq: the request to finish
2848 * @error: %0 for success, < %0 for error
2849 *
2850 * Description:
2851 * Completely finish @rq.
2852 */
2853 void blk_end_request_all(struct request *rq, int error)
2854 {
2855 bool pending;
2856 unsigned int bidi_bytes = 0;
2857
2858 if (unlikely(blk_bidi_rq(rq)))
2859 bidi_bytes = blk_rq_bytes(rq->next_rq);
2860
2861 pending = blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2862 BUG_ON(pending);
2863 }
2864 EXPORT_SYMBOL(blk_end_request_all);
2865
2866 /**
2867 * blk_end_request_cur - Helper function to finish the current request chunk.
2868 * @rq: the request to finish the current chunk for
2869 * @error: %0 for success, < %0 for error
2870 *
2871 * Description:
2872 * Complete the current consecutively mapped chunk from @rq.
2873 *
2874 * Return:
2875 * %false - we are done with this request
2876 * %true - still buffers pending for this request
2877 */
2878 bool blk_end_request_cur(struct request *rq, int error)
2879 {
2880 return blk_end_request(rq, error, blk_rq_cur_bytes(rq));
2881 }
2882 EXPORT_SYMBOL(blk_end_request_cur);
2883
2884 /**
2885 * blk_end_request_err - Finish a request till the next failure boundary.
2886 * @rq: the request to finish till the next failure boundary for
2887 * @error: must be negative errno
2888 *
2889 * Description:
2890 * Complete @rq till the next failure boundary.
2891 *
2892 * Return:
2893 * %false - we are done with this request
2894 * %true - still buffers pending for this request
2895 */
2896 bool blk_end_request_err(struct request *rq, int error)
2897 {
2898 WARN_ON(error >= 0);
2899 return blk_end_request(rq, error, blk_rq_err_bytes(rq));
2900 }
2901 EXPORT_SYMBOL_GPL(blk_end_request_err);
2902
2903 /**
2904 * __blk_end_request - Helper function for drivers to complete the request.
2905 * @rq: the request being processed
2906 * @error: %0 for success, < %0 for error
2907 * @nr_bytes: number of bytes to complete
2908 *
2909 * Description:
2910 * Must be called with queue lock held unlike blk_end_request().
2911 *
2912 * Return:
2913 * %false - we are done with this request
2914 * %true - still buffers pending for this request
2915 **/
2916 bool __blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
2917 {
2918 return __blk_end_bidi_request(rq, error, nr_bytes, 0);
2919 }
2920 EXPORT_SYMBOL(__blk_end_request);
2921
2922 /**
2923 * __blk_end_request_all - Helper function for drives to finish the request.
2924 * @rq: the request to finish
2925 * @error: %0 for success, < %0 for error
2926 *
2927 * Description:
2928 * Completely finish @rq. Must be called with queue lock held.
2929 */
2930 void __blk_end_request_all(struct request *rq, int error)
2931 {
2932 bool pending;
2933 unsigned int bidi_bytes = 0;
2934
2935 if (unlikely(blk_bidi_rq(rq)))
2936 bidi_bytes = blk_rq_bytes(rq->next_rq);
2937
2938 pending = __blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
2939 BUG_ON(pending);
2940 }
2941 EXPORT_SYMBOL(__blk_end_request_all);
2942
2943 /**
2944 * __blk_end_request_cur - Helper function to finish the current request chunk.
2945 * @rq: the request to finish the current chunk for
2946 * @error: %0 for success, < %0 for error
2947 *
2948 * Description:
2949 * Complete the current consecutively mapped chunk from @rq. Must
2950 * be called with queue lock held.
2951 *
2952 * Return:
2953 * %false - we are done with this request
2954 * %true - still buffers pending for this request
2955 */
2956 bool __blk_end_request_cur(struct request *rq, int error)
2957 {
2958 return __blk_end_request(rq, error, blk_rq_cur_bytes(rq));
2959 }
2960 EXPORT_SYMBOL(__blk_end_request_cur);
2961
2962 /**
2963 * __blk_end_request_err - Finish a request till the next failure boundary.
2964 * @rq: the request to finish till the next failure boundary for
2965 * @error: must be negative errno
2966 *
2967 * Description:
2968 * Complete @rq till the next failure boundary. Must be called
2969 * with queue lock held.
2970 *
2971 * Return:
2972 * %false - we are done with this request
2973 * %true - still buffers pending for this request
2974 */
2975 bool __blk_end_request_err(struct request *rq, int error)
2976 {
2977 WARN_ON(error >= 0);
2978 return __blk_end_request(rq, error, blk_rq_err_bytes(rq));
2979 }
2980 EXPORT_SYMBOL_GPL(__blk_end_request_err);
2981
2982 void blk_rq_bio_prep(struct request_queue *q, struct request *rq,
2983 struct bio *bio)
2984 {
2985 /* Bit 0 (R/W) is identical in rq->cmd_flags and bio->bi_rw */
2986 rq->cmd_flags |= bio->bi_rw & REQ_WRITE;
2987
2988 if (bio_has_data(bio))
2989 rq->nr_phys_segments = bio_phys_segments(q, bio);
2990
2991 rq->__data_len = bio->bi_iter.bi_size;
2992 rq->bio = rq->biotail = bio;
2993
2994 if (bio->bi_bdev)
2995 rq->rq_disk = bio->bi_bdev->bd_disk;
2996 }
2997
2998 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE
2999 /**
3000 * rq_flush_dcache_pages - Helper function to flush all pages in a request
3001 * @rq: the request to be flushed
3002 *
3003 * Description:
3004 * Flush all pages in @rq.
3005 */
3006 void rq_flush_dcache_pages(struct request *rq)
3007 {
3008 struct req_iterator iter;
3009 struct bio_vec bvec;
3010
3011 rq_for_each_segment(bvec, rq, iter)
3012 flush_dcache_page(bvec.bv_page);
3013 }
3014 EXPORT_SYMBOL_GPL(rq_flush_dcache_pages);
3015 #endif
3016
3017 /**
3018 * blk_lld_busy - Check if underlying low-level drivers of a device are busy
3019 * @q : the queue of the device being checked
3020 *
3021 * Description:
3022 * Check if underlying low-level drivers of a device are busy.
3023 * If the drivers want to export their busy state, they must set own
3024 * exporting function using blk_queue_lld_busy() first.
3025 *
3026 * Basically, this function is used only by request stacking drivers
3027 * to stop dispatching requests to underlying devices when underlying
3028 * devices are busy. This behavior helps more I/O merging on the queue
3029 * of the request stacking driver and prevents I/O throughput regression
3030 * on burst I/O load.
3031 *
3032 * Return:
3033 * 0 - Not busy (The request stacking driver should dispatch request)
3034 * 1 - Busy (The request stacking driver should stop dispatching request)
3035 */
3036 int blk_lld_busy(struct request_queue *q)
3037 {
3038 if (q->lld_busy_fn)
3039 return q->lld_busy_fn(q);
3040
3041 return 0;
3042 }
3043 EXPORT_SYMBOL_GPL(blk_lld_busy);
3044
3045 /**
3046 * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
3047 * @rq: the clone request to be cleaned up
3048 *
3049 * Description:
3050 * Free all bios in @rq for a cloned request.
3051 */
3052 void blk_rq_unprep_clone(struct request *rq)
3053 {
3054 struct bio *bio;
3055
3056 while ((bio = rq->bio) != NULL) {
3057 rq->bio = bio->bi_next;
3058
3059 bio_put(bio);
3060 }
3061 }
3062 EXPORT_SYMBOL_GPL(blk_rq_unprep_clone);
3063
3064 /*
3065 * Copy attributes of the original request to the clone request.
3066 * The actual data parts (e.g. ->cmd, ->sense) are not copied.
3067 */
3068 static void __blk_rq_prep_clone(struct request *dst, struct request *src)
3069 {
3070 dst->cpu = src->cpu;
3071 dst->cmd_flags |= (src->cmd_flags & REQ_CLONE_MASK) | REQ_NOMERGE;
3072 dst->cmd_type = src->cmd_type;
3073 dst->__sector = blk_rq_pos(src);
3074 dst->__data_len = blk_rq_bytes(src);
3075 dst->nr_phys_segments = src->nr_phys_segments;
3076 dst->ioprio = src->ioprio;
3077 dst->extra_len = src->extra_len;
3078 }
3079
3080 /**
3081 * blk_rq_prep_clone - Helper function to setup clone request
3082 * @rq: the request to be setup
3083 * @rq_src: original request to be cloned
3084 * @bs: bio_set that bios for clone are allocated from
3085 * @gfp_mask: memory allocation mask for bio
3086 * @bio_ctr: setup function to be called for each clone bio.
3087 * Returns %0 for success, non %0 for failure.
3088 * @data: private data to be passed to @bio_ctr
3089 *
3090 * Description:
3091 * Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
3092 * The actual data parts of @rq_src (e.g. ->cmd, ->sense)
3093 * are not copied, and copying such parts is the caller's responsibility.
3094 * Also, pages which the original bios are pointing to are not copied
3095 * and the cloned bios just point same pages.
3096 * So cloned bios must be completed before original bios, which means
3097 * the caller must complete @rq before @rq_src.
3098 */
3099 int blk_rq_prep_clone(struct request *rq, struct request *rq_src,
3100 struct bio_set *bs, gfp_t gfp_mask,
3101 int (*bio_ctr)(struct bio *, struct bio *, void *),
3102 void *data)
3103 {
3104 struct bio *bio, *bio_src;
3105
3106 if (!bs)
3107 bs = fs_bio_set;
3108
3109 __rq_for_each_bio(bio_src, rq_src) {
3110 bio = bio_clone_fast(bio_src, gfp_mask, bs);
3111 if (!bio)
3112 goto free_and_out;
3113
3114 if (bio_ctr && bio_ctr(bio, bio_src, data))
3115 goto free_and_out;
3116
3117 if (rq->bio) {
3118 rq->biotail->bi_next = bio;
3119 rq->biotail = bio;
3120 } else
3121 rq->bio = rq->biotail = bio;
3122 }
3123
3124 __blk_rq_prep_clone(rq, rq_src);
3125
3126 return 0;
3127
3128 free_and_out:
3129 if (bio)
3130 bio_put(bio);
3131 blk_rq_unprep_clone(rq);
3132
3133 return -ENOMEM;
3134 }
3135 EXPORT_SYMBOL_GPL(blk_rq_prep_clone);
3136
3137 int kblockd_schedule_work(struct work_struct *work)
3138 {
3139 return queue_work(kblockd_workqueue, work);
3140 }
3141 EXPORT_SYMBOL(kblockd_schedule_work);
3142
3143 int kblockd_schedule_delayed_work(struct delayed_work *dwork,
3144 unsigned long delay)
3145 {
3146 return queue_delayed_work(kblockd_workqueue, dwork, delay);
3147 }
3148 EXPORT_SYMBOL(kblockd_schedule_delayed_work);
3149
3150 int kblockd_schedule_delayed_work_on(int cpu, struct delayed_work *dwork,
3151 unsigned long delay)
3152 {
3153 return queue_delayed_work_on(cpu, kblockd_workqueue, dwork, delay);
3154 }
3155 EXPORT_SYMBOL(kblockd_schedule_delayed_work_on);
3156
3157 /**
3158 * blk_start_plug - initialize blk_plug and track it inside the task_struct
3159 * @plug: The &struct blk_plug that needs to be initialized
3160 *
3161 * Description:
3162 * Tracking blk_plug inside the task_struct will help with auto-flushing the
3163 * pending I/O should the task end up blocking between blk_start_plug() and
3164 * blk_finish_plug(). This is important from a performance perspective, but
3165 * also ensures that we don't deadlock. For instance, if the task is blocking
3166 * for a memory allocation, memory reclaim could end up wanting to free a
3167 * page belonging to that request that is currently residing in our private
3168 * plug. By flushing the pending I/O when the process goes to sleep, we avoid
3169 * this kind of deadlock.
3170 */
3171 void blk_start_plug(struct blk_plug *plug)
3172 {
3173 struct task_struct *tsk = current;
3174
3175 /*
3176 * If this is a nested plug, don't actually assign it.
3177 */
3178 if (tsk->plug)
3179 return;
3180
3181 INIT_LIST_HEAD(&plug->list);
3182 INIT_LIST_HEAD(&plug->mq_list);
3183 INIT_LIST_HEAD(&plug->cb_list);
3184 /*
3185 * Store ordering should not be needed here, since a potential
3186 * preempt will imply a full memory barrier
3187 */
3188 tsk->plug = plug;
3189 }
3190 EXPORT_SYMBOL(blk_start_plug);
3191
3192 static int plug_rq_cmp(void *priv, struct list_head *a, struct list_head *b)
3193 {
3194 struct request *rqa = container_of(a, struct request, queuelist);
3195 struct request *rqb = container_of(b, struct request, queuelist);
3196
3197 return !(rqa->q < rqb->q ||
3198 (rqa->q == rqb->q && blk_rq_pos(rqa) < blk_rq_pos(rqb)));
3199 }
3200
3201 /*
3202 * If 'from_schedule' is true, then postpone the dispatch of requests
3203 * until a safe kblockd context. We due this to avoid accidental big
3204 * additional stack usage in driver dispatch, in places where the originally
3205 * plugger did not intend it.
3206 */
3207 static void queue_unplugged(struct request_queue *q, unsigned int depth,
3208 bool from_schedule)
3209 __releases(q->queue_lock)
3210 {
3211 trace_block_unplug(q, depth, !from_schedule);
3212
3213 if (from_schedule)
3214 blk_run_queue_async(q);
3215 else
3216 __blk_run_queue(q);
3217 spin_unlock(q->queue_lock);
3218 }
3219
3220 static void flush_plug_callbacks(struct blk_plug *plug, bool from_schedule)
3221 {
3222 LIST_HEAD(callbacks);
3223
3224 while (!list_empty(&plug->cb_list)) {
3225 list_splice_init(&plug->cb_list, &callbacks);
3226
3227 while (!list_empty(&callbacks)) {
3228 struct blk_plug_cb *cb = list_first_entry(&callbacks,
3229 struct blk_plug_cb,
3230 list);
3231 list_del(&cb->list);
3232 cb->callback(cb, from_schedule);
3233 }
3234 }
3235 }
3236
3237 struct blk_plug_cb *blk_check_plugged(blk_plug_cb_fn unplug, void *data,
3238 int size)
3239 {
3240 struct blk_plug *plug = current->plug;
3241 struct blk_plug_cb *cb;
3242
3243 if (!plug)
3244 return NULL;
3245
3246 list_for_each_entry(cb, &plug->cb_list, list)
3247 if (cb->callback == unplug && cb->data == data)
3248 return cb;
3249
3250 /* Not currently on the callback list */
3251 BUG_ON(size < sizeof(*cb));
3252 cb = kzalloc(size, GFP_ATOMIC);
3253 if (cb) {
3254 cb->data = data;
3255 cb->callback = unplug;
3256 list_add(&cb->list, &plug->cb_list);
3257 }
3258 return cb;
3259 }
3260 EXPORT_SYMBOL(blk_check_plugged);
3261
3262 void blk_flush_plug_list(struct blk_plug *plug, bool from_schedule)
3263 {
3264 struct request_queue *q;
3265 unsigned long flags;
3266 struct request *rq;
3267 LIST_HEAD(list);
3268 unsigned int depth;
3269
3270 flush_plug_callbacks(plug, from_schedule);
3271
3272 if (!list_empty(&plug->mq_list))
3273 blk_mq_flush_plug_list(plug, from_schedule);
3274
3275 if (list_empty(&plug->list))
3276 return;
3277
3278 list_splice_init(&plug->list, &list);
3279
3280 list_sort(NULL, &list, plug_rq_cmp);
3281
3282 q = NULL;
3283 depth = 0;
3284
3285 /*
3286 * Save and disable interrupts here, to avoid doing it for every
3287 * queue lock we have to take.
3288 */
3289 local_irq_save(flags);
3290 while (!list_empty(&list)) {
3291 rq = list_entry_rq(list.next);
3292 list_del_init(&rq->queuelist);
3293 BUG_ON(!rq->q);
3294 if (rq->q != q) {
3295 /*
3296 * This drops the queue lock
3297 */
3298 if (q)
3299 queue_unplugged(q, depth, from_schedule);
3300 q = rq->q;
3301 depth = 0;
3302 spin_lock(q->queue_lock);
3303 }
3304
3305 /*
3306 * Short-circuit if @q is dead
3307 */
3308 if (unlikely(blk_queue_dying(q))) {
3309 __blk_end_request_all(rq, -ENODEV);
3310 continue;
3311 }
3312
3313 /*
3314 * rq is already accounted, so use raw insert
3315 */
3316 if (rq->cmd_flags & (REQ_FLUSH | REQ_FUA))
3317 __elv_add_request(q, rq, ELEVATOR_INSERT_FLUSH);
3318 else
3319 __elv_add_request(q, rq, ELEVATOR_INSERT_SORT_MERGE);
3320
3321 depth++;
3322 }
3323
3324 /*
3325 * This drops the queue lock
3326 */
3327 if (q)
3328 queue_unplugged(q, depth, from_schedule);
3329
3330 local_irq_restore(flags);
3331 }
3332
3333 void blk_finish_plug(struct blk_plug *plug)
3334 {
3335 if (plug != current->plug)
3336 return;
3337 blk_flush_plug_list(plug, false);
3338
3339 current->plug = NULL;
3340 }
3341 EXPORT_SYMBOL(blk_finish_plug);
3342
3343 bool blk_poll(struct request_queue *q, blk_qc_t cookie)
3344 {
3345 struct blk_plug *plug;
3346 long state;
3347
3348 if (!q->mq_ops || !q->mq_ops->poll || !blk_qc_t_valid(cookie) ||
3349 !test_bit(QUEUE_FLAG_POLL, &q->queue_flags))
3350 return false;
3351
3352 plug = current->plug;
3353 if (plug)
3354 blk_flush_plug_list(plug, false);
3355
3356 state = current->state;
3357 while (!need_resched()) {
3358 unsigned int queue_num = blk_qc_t_to_queue_num(cookie);
3359 struct blk_mq_hw_ctx *hctx = q->queue_hw_ctx[queue_num];
3360 int ret;
3361
3362 hctx->poll_invoked++;
3363
3364 ret = q->mq_ops->poll(hctx, blk_qc_t_to_tag(cookie));
3365 if (ret > 0) {
3366 hctx->poll_success++;
3367 set_current_state(TASK_RUNNING);
3368 return true;
3369 }
3370
3371 if (signal_pending_state(state, current))
3372 set_current_state(TASK_RUNNING);
3373
3374 if (current->state == TASK_RUNNING)
3375 return true;
3376 if (ret < 0)
3377 break;
3378 cpu_relax();
3379 }
3380
3381 return false;
3382 }
3383
3384 #ifdef CONFIG_PM
3385 /**
3386 * blk_pm_runtime_init - Block layer runtime PM initialization routine
3387 * @q: the queue of the device
3388 * @dev: the device the queue belongs to
3389 *
3390 * Description:
3391 * Initialize runtime-PM-related fields for @q and start auto suspend for
3392 * @dev. Drivers that want to take advantage of request-based runtime PM
3393 * should call this function after @dev has been initialized, and its
3394 * request queue @q has been allocated, and runtime PM for it can not happen
3395 * yet(either due to disabled/forbidden or its usage_count > 0). In most
3396 * cases, driver should call this function before any I/O has taken place.
3397 *
3398 * This function takes care of setting up using auto suspend for the device,
3399 * the autosuspend delay is set to -1 to make runtime suspend impossible
3400 * until an updated value is either set by user or by driver. Drivers do
3401 * not need to touch other autosuspend settings.
3402 *
3403 * The block layer runtime PM is request based, so only works for drivers
3404 * that use request as their IO unit instead of those directly use bio's.
3405 */
3406 void blk_pm_runtime_init(struct request_queue *q, struct device *dev)
3407 {
3408 q->dev = dev;
3409 q->rpm_status = RPM_ACTIVE;
3410 pm_runtime_set_autosuspend_delay(q->dev, -1);
3411 pm_runtime_use_autosuspend(q->dev);
3412 }
3413 EXPORT_SYMBOL(blk_pm_runtime_init);
3414
3415 /**
3416 * blk_pre_runtime_suspend - Pre runtime suspend check
3417 * @q: the queue of the device
3418 *
3419 * Description:
3420 * This function will check if runtime suspend is allowed for the device
3421 * by examining if there are any requests pending in the queue. If there
3422 * are requests pending, the device can not be runtime suspended; otherwise,
3423 * the queue's status will be updated to SUSPENDING and the driver can
3424 * proceed to suspend the device.
3425 *
3426 * For the not allowed case, we mark last busy for the device so that
3427 * runtime PM core will try to autosuspend it some time later.
3428 *
3429 * This function should be called near the start of the device's
3430 * runtime_suspend callback.
3431 *
3432 * Return:
3433 * 0 - OK to runtime suspend the device
3434 * -EBUSY - Device should not be runtime suspended
3435 */
3436 int blk_pre_runtime_suspend(struct request_queue *q)
3437 {
3438 int ret = 0;
3439
3440 if (!q->dev)
3441 return ret;
3442
3443 spin_lock_irq(q->queue_lock);
3444 if (q->nr_pending) {
3445 ret = -EBUSY;
3446 pm_runtime_mark_last_busy(q->dev);
3447 } else {
3448 q->rpm_status = RPM_SUSPENDING;
3449 }
3450 spin_unlock_irq(q->queue_lock);
3451 return ret;
3452 }
3453 EXPORT_SYMBOL(blk_pre_runtime_suspend);
3454
3455 /**
3456 * blk_post_runtime_suspend - Post runtime suspend processing
3457 * @q: the queue of the device
3458 * @err: return value of the device's runtime_suspend function
3459 *
3460 * Description:
3461 * Update the queue's runtime status according to the return value of the
3462 * device's runtime suspend function and mark last busy for the device so
3463 * that PM core will try to auto suspend the device at a later time.
3464 *
3465 * This function should be called near the end of the device's
3466 * runtime_suspend callback.
3467 */
3468 void blk_post_runtime_suspend(struct request_queue *q, int err)
3469 {
3470 if (!q->dev)
3471 return;
3472
3473 spin_lock_irq(q->queue_lock);
3474 if (!err) {
3475 q->rpm_status = RPM_SUSPENDED;
3476 } else {
3477 q->rpm_status = RPM_ACTIVE;
3478 pm_runtime_mark_last_busy(q->dev);
3479 }
3480 spin_unlock_irq(q->queue_lock);
3481 }
3482 EXPORT_SYMBOL(blk_post_runtime_suspend);
3483
3484 /**
3485 * blk_pre_runtime_resume - Pre runtime resume processing
3486 * @q: the queue of the device
3487 *
3488 * Description:
3489 * Update the queue's runtime status to RESUMING in preparation for the
3490 * runtime resume of the device.
3491 *
3492 * This function should be called near the start of the device's
3493 * runtime_resume callback.
3494 */
3495 void blk_pre_runtime_resume(struct request_queue *q)
3496 {
3497 if (!q->dev)
3498 return;
3499
3500 spin_lock_irq(q->queue_lock);
3501 q->rpm_status = RPM_RESUMING;
3502 spin_unlock_irq(q->queue_lock);
3503 }
3504 EXPORT_SYMBOL(blk_pre_runtime_resume);
3505
3506 /**
3507 * blk_post_runtime_resume - Post runtime resume processing
3508 * @q: the queue of the device
3509 * @err: return value of the device's runtime_resume function
3510 *
3511 * Description:
3512 * Update the queue's runtime status according to the return value of the
3513 * device's runtime_resume function. If it is successfully resumed, process
3514 * the requests that are queued into the device's queue when it is resuming
3515 * and then mark last busy and initiate autosuspend for it.
3516 *
3517 * This function should be called near the end of the device's
3518 * runtime_resume callback.
3519 */
3520 void blk_post_runtime_resume(struct request_queue *q, int err)
3521 {
3522 if (!q->dev)
3523 return;
3524
3525 spin_lock_irq(q->queue_lock);
3526 if (!err) {
3527 q->rpm_status = RPM_ACTIVE;
3528 __blk_run_queue(q);
3529 pm_runtime_mark_last_busy(q->dev);
3530 pm_request_autosuspend(q->dev);
3531 } else {
3532 q->rpm_status = RPM_SUSPENDED;
3533 }
3534 spin_unlock_irq(q->queue_lock);
3535 }
3536 EXPORT_SYMBOL(blk_post_runtime_resume);
3537 #endif
3538
3539 int __init blk_dev_init(void)
3540 {
3541 BUILD_BUG_ON(__REQ_NR_BITS > 8 *
3542 FIELD_SIZEOF(struct request, cmd_flags));
3543
3544 /* used for unplugging and affects IO latency/throughput - HIGHPRI */
3545 kblockd_workqueue = alloc_workqueue("kblockd",
3546 WQ_MEM_RECLAIM | WQ_HIGHPRI, 0);
3547 if (!kblockd_workqueue)
3548 panic("Failed to create kblockd\n");
3549
3550 request_cachep = kmem_cache_create("blkdev_requests",
3551 sizeof(struct request), 0, SLAB_PANIC, NULL);
3552
3553 blk_requestq_cachep = kmem_cache_create("blkdev_queue",
3554 sizeof(struct request_queue), 0, SLAB_PANIC, NULL);
3555
3556 return 0;
3557 }