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