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