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