]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blob - block/blk-core.c
block: factor out a blk_try_enter_queue helper
[mirror_ubuntu-jammy-kernel.git] / block / blk-core.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Copyright (C) 1991, 1992 Linus Torvalds
4 * Copyright (C) 1994, Karl Keyte: Added support for disk statistics
5 * Elevator latency, (C) 2000 Andrea Arcangeli <andrea@suse.de> SuSE
6 * Queue request tables / lock, selectable elevator, Jens Axboe <axboe@suse.de>
7 * kernel-doc documentation started by NeilBrown <neilb@cse.unsw.edu.au>
8 * - July2000
9 * bio rewrite, highmem i/o, etc, Jens Axboe <axboe@suse.de> - may 2001
10 */
11
12 /*
13 * This handles all read/write requests to block devices
14 */
15 #include <linux/kernel.h>
16 #include <linux/module.h>
17 #include <linux/bio.h>
18 #include <linux/blkdev.h>
19 #include <linux/blk-mq.h>
20 #include <linux/blk-pm.h>
21 #include <linux/highmem.h>
22 #include <linux/mm.h>
23 #include <linux/pagemap.h>
24 #include <linux/kernel_stat.h>
25 #include <linux/string.h>
26 #include <linux/init.h>
27 #include <linux/completion.h>
28 #include <linux/slab.h>
29 #include <linux/swap.h>
30 #include <linux/writeback.h>
31 #include <linux/task_io_accounting_ops.h>
32 #include <linux/fault-inject.h>
33 #include <linux/list_sort.h>
34 #include <linux/delay.h>
35 #include <linux/ratelimit.h>
36 #include <linux/pm_runtime.h>
37 #include <linux/blk-cgroup.h>
38 #include <linux/t10-pi.h>
39 #include <linux/debugfs.h>
40 #include <linux/bpf.h>
41 #include <linux/psi.h>
42 #include <linux/sched/sysctl.h>
43 #include <linux/blk-crypto.h>
44
45 #define CREATE_TRACE_POINTS
46 #include <trace/events/block.h>
47
48 #include "blk.h"
49 #include "blk-mq.h"
50 #include "blk-mq-sched.h"
51 #include "blk-pm.h"
52 #include "blk-rq-qos.h"
53
54 struct dentry *blk_debugfs_root;
55
56 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_remap);
57 EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_remap);
58 EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_complete);
59 EXPORT_TRACEPOINT_SYMBOL_GPL(block_split);
60 EXPORT_TRACEPOINT_SYMBOL_GPL(block_unplug);
61 EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_insert);
62
63 DEFINE_IDA(blk_queue_ida);
64
65 /*
66 * For queue allocation
67 */
68 struct kmem_cache *blk_requestq_cachep;
69
70 /*
71 * Controlling structure to kblockd
72 */
73 static struct workqueue_struct *kblockd_workqueue;
74
75 /**
76 * blk_queue_flag_set - atomically set a queue flag
77 * @flag: flag to be set
78 * @q: request queue
79 */
80 void blk_queue_flag_set(unsigned int flag, struct request_queue *q)
81 {
82 set_bit(flag, &q->queue_flags);
83 }
84 EXPORT_SYMBOL(blk_queue_flag_set);
85
86 /**
87 * blk_queue_flag_clear - atomically clear a queue flag
88 * @flag: flag to be cleared
89 * @q: request queue
90 */
91 void blk_queue_flag_clear(unsigned int flag, struct request_queue *q)
92 {
93 clear_bit(flag, &q->queue_flags);
94 }
95 EXPORT_SYMBOL(blk_queue_flag_clear);
96
97 /**
98 * blk_queue_flag_test_and_set - atomically test and set a queue flag
99 * @flag: flag to be set
100 * @q: request queue
101 *
102 * Returns the previous value of @flag - 0 if the flag was not set and 1 if
103 * the flag was already set.
104 */
105 bool blk_queue_flag_test_and_set(unsigned int flag, struct request_queue *q)
106 {
107 return test_and_set_bit(flag, &q->queue_flags);
108 }
109 EXPORT_SYMBOL_GPL(blk_queue_flag_test_and_set);
110
111 void blk_rq_init(struct request_queue *q, struct request *rq)
112 {
113 memset(rq, 0, sizeof(*rq));
114
115 INIT_LIST_HEAD(&rq->queuelist);
116 rq->q = q;
117 rq->__sector = (sector_t) -1;
118 INIT_HLIST_NODE(&rq->hash);
119 RB_CLEAR_NODE(&rq->rb_node);
120 rq->tag = BLK_MQ_NO_TAG;
121 rq->internal_tag = BLK_MQ_NO_TAG;
122 rq->start_time_ns = ktime_get_ns();
123 rq->part = NULL;
124 blk_crypto_rq_set_defaults(rq);
125 }
126 EXPORT_SYMBOL(blk_rq_init);
127
128 #define REQ_OP_NAME(name) [REQ_OP_##name] = #name
129 static const char *const blk_op_name[] = {
130 REQ_OP_NAME(READ),
131 REQ_OP_NAME(WRITE),
132 REQ_OP_NAME(FLUSH),
133 REQ_OP_NAME(DISCARD),
134 REQ_OP_NAME(SECURE_ERASE),
135 REQ_OP_NAME(ZONE_RESET),
136 REQ_OP_NAME(ZONE_RESET_ALL),
137 REQ_OP_NAME(ZONE_OPEN),
138 REQ_OP_NAME(ZONE_CLOSE),
139 REQ_OP_NAME(ZONE_FINISH),
140 REQ_OP_NAME(ZONE_APPEND),
141 REQ_OP_NAME(WRITE_SAME),
142 REQ_OP_NAME(WRITE_ZEROES),
143 REQ_OP_NAME(DRV_IN),
144 REQ_OP_NAME(DRV_OUT),
145 };
146 #undef REQ_OP_NAME
147
148 /**
149 * blk_op_str - Return string XXX in the REQ_OP_XXX.
150 * @op: REQ_OP_XXX.
151 *
152 * Description: Centralize block layer function to convert REQ_OP_XXX into
153 * string format. Useful in the debugging and tracing bio or request. For
154 * invalid REQ_OP_XXX it returns string "UNKNOWN".
155 */
156 inline const char *blk_op_str(unsigned int op)
157 {
158 const char *op_str = "UNKNOWN";
159
160 if (op < ARRAY_SIZE(blk_op_name) && blk_op_name[op])
161 op_str = blk_op_name[op];
162
163 return op_str;
164 }
165 EXPORT_SYMBOL_GPL(blk_op_str);
166
167 static const struct {
168 int errno;
169 const char *name;
170 } blk_errors[] = {
171 [BLK_STS_OK] = { 0, "" },
172 [BLK_STS_NOTSUPP] = { -EOPNOTSUPP, "operation not supported" },
173 [BLK_STS_TIMEOUT] = { -ETIMEDOUT, "timeout" },
174 [BLK_STS_NOSPC] = { -ENOSPC, "critical space allocation" },
175 [BLK_STS_TRANSPORT] = { -ENOLINK, "recoverable transport" },
176 [BLK_STS_TARGET] = { -EREMOTEIO, "critical target" },
177 [BLK_STS_NEXUS] = { -EBADE, "critical nexus" },
178 [BLK_STS_MEDIUM] = { -ENODATA, "critical medium" },
179 [BLK_STS_PROTECTION] = { -EILSEQ, "protection" },
180 [BLK_STS_RESOURCE] = { -ENOMEM, "kernel resource" },
181 [BLK_STS_DEV_RESOURCE] = { -EBUSY, "device resource" },
182 [BLK_STS_AGAIN] = { -EAGAIN, "nonblocking retry" },
183
184 /* device mapper special case, should not leak out: */
185 [BLK_STS_DM_REQUEUE] = { -EREMCHG, "dm internal retry" },
186
187 /* zone device specific errors */
188 [BLK_STS_ZONE_OPEN_RESOURCE] = { -ETOOMANYREFS, "open zones exceeded" },
189 [BLK_STS_ZONE_ACTIVE_RESOURCE] = { -EOVERFLOW, "active zones exceeded" },
190
191 /* everything else not covered above: */
192 [BLK_STS_IOERR] = { -EIO, "I/O" },
193 };
194
195 blk_status_t errno_to_blk_status(int errno)
196 {
197 int i;
198
199 for (i = 0; i < ARRAY_SIZE(blk_errors); i++) {
200 if (blk_errors[i].errno == errno)
201 return (__force blk_status_t)i;
202 }
203
204 return BLK_STS_IOERR;
205 }
206 EXPORT_SYMBOL_GPL(errno_to_blk_status);
207
208 int blk_status_to_errno(blk_status_t status)
209 {
210 int idx = (__force int)status;
211
212 if (WARN_ON_ONCE(idx >= ARRAY_SIZE(blk_errors)))
213 return -EIO;
214 return blk_errors[idx].errno;
215 }
216 EXPORT_SYMBOL_GPL(blk_status_to_errno);
217
218 static void print_req_error(struct request *req, blk_status_t status,
219 const char *caller)
220 {
221 int idx = (__force int)status;
222
223 if (WARN_ON_ONCE(idx >= ARRAY_SIZE(blk_errors)))
224 return;
225
226 printk_ratelimited(KERN_ERR
227 "%s: %s error, dev %s, sector %llu op 0x%x:(%s) flags 0x%x "
228 "phys_seg %u prio class %u\n",
229 caller, blk_errors[idx].name,
230 req->rq_disk ? req->rq_disk->disk_name : "?",
231 blk_rq_pos(req), req_op(req), blk_op_str(req_op(req)),
232 req->cmd_flags & ~REQ_OP_MASK,
233 req->nr_phys_segments,
234 IOPRIO_PRIO_CLASS(req->ioprio));
235 }
236
237 static void req_bio_endio(struct request *rq, struct bio *bio,
238 unsigned int nbytes, blk_status_t error)
239 {
240 if (error)
241 bio->bi_status = error;
242
243 if (unlikely(rq->rq_flags & RQF_QUIET))
244 bio_set_flag(bio, BIO_QUIET);
245
246 bio_advance(bio, nbytes);
247
248 if (req_op(rq) == REQ_OP_ZONE_APPEND && error == BLK_STS_OK) {
249 /*
250 * Partial zone append completions cannot be supported as the
251 * BIO fragments may end up not being written sequentially.
252 */
253 if (bio->bi_iter.bi_size)
254 bio->bi_status = BLK_STS_IOERR;
255 else
256 bio->bi_iter.bi_sector = rq->__sector;
257 }
258
259 /* don't actually finish bio if it's part of flush sequence */
260 if (bio->bi_iter.bi_size == 0 && !(rq->rq_flags & RQF_FLUSH_SEQ))
261 bio_endio(bio);
262 }
263
264 void blk_dump_rq_flags(struct request *rq, char *msg)
265 {
266 printk(KERN_INFO "%s: dev %s: flags=%llx\n", msg,
267 rq->rq_disk ? rq->rq_disk->disk_name : "?",
268 (unsigned long long) rq->cmd_flags);
269
270 printk(KERN_INFO " sector %llu, nr/cnr %u/%u\n",
271 (unsigned long long)blk_rq_pos(rq),
272 blk_rq_sectors(rq), blk_rq_cur_sectors(rq));
273 printk(KERN_INFO " bio %p, biotail %p, len %u\n",
274 rq->bio, rq->biotail, blk_rq_bytes(rq));
275 }
276 EXPORT_SYMBOL(blk_dump_rq_flags);
277
278 /**
279 * blk_sync_queue - cancel any pending callbacks on a queue
280 * @q: the queue
281 *
282 * Description:
283 * The block layer may perform asynchronous callback activity
284 * on a queue, such as calling the unplug function after a timeout.
285 * A block device may call blk_sync_queue to ensure that any
286 * such activity is cancelled, thus allowing it to release resources
287 * that the callbacks might use. The caller must already have made sure
288 * that its ->submit_bio will not re-add plugging prior to calling
289 * this function.
290 *
291 * This function does not cancel any asynchronous activity arising
292 * out of elevator or throttling code. That would require elevator_exit()
293 * and blkcg_exit_queue() to be called with queue lock initialized.
294 *
295 */
296 void blk_sync_queue(struct request_queue *q)
297 {
298 del_timer_sync(&q->timeout);
299 cancel_work_sync(&q->timeout_work);
300 }
301 EXPORT_SYMBOL(blk_sync_queue);
302
303 /**
304 * blk_set_pm_only - increment pm_only counter
305 * @q: request queue pointer
306 */
307 void blk_set_pm_only(struct request_queue *q)
308 {
309 atomic_inc(&q->pm_only);
310 }
311 EXPORT_SYMBOL_GPL(blk_set_pm_only);
312
313 void blk_clear_pm_only(struct request_queue *q)
314 {
315 int pm_only;
316
317 pm_only = atomic_dec_return(&q->pm_only);
318 WARN_ON_ONCE(pm_only < 0);
319 if (pm_only == 0)
320 wake_up_all(&q->mq_freeze_wq);
321 }
322 EXPORT_SYMBOL_GPL(blk_clear_pm_only);
323
324 /**
325 * blk_put_queue - decrement the request_queue refcount
326 * @q: the request_queue structure to decrement the refcount for
327 *
328 * Decrements the refcount of the request_queue kobject. When this reaches 0
329 * we'll have blk_release_queue() called.
330 *
331 * Context: Any context, but the last reference must not be dropped from
332 * atomic context.
333 */
334 void blk_put_queue(struct request_queue *q)
335 {
336 kobject_put(&q->kobj);
337 }
338 EXPORT_SYMBOL(blk_put_queue);
339
340 void blk_set_queue_dying(struct request_queue *q)
341 {
342 blk_queue_flag_set(QUEUE_FLAG_DYING, q);
343
344 /*
345 * When queue DYING flag is set, we need to block new req
346 * entering queue, so we call blk_freeze_queue_start() to
347 * prevent I/O from crossing blk_queue_enter().
348 */
349 blk_freeze_queue_start(q);
350
351 if (queue_is_mq(q))
352 blk_mq_wake_waiters(q);
353
354 /* Make blk_queue_enter() reexamine the DYING flag. */
355 wake_up_all(&q->mq_freeze_wq);
356 }
357 EXPORT_SYMBOL_GPL(blk_set_queue_dying);
358
359 /**
360 * blk_cleanup_queue - shutdown a request queue
361 * @q: request queue to shutdown
362 *
363 * Mark @q DYING, drain all pending requests, mark @q DEAD, destroy and
364 * put it. All future requests will be failed immediately with -ENODEV.
365 *
366 * Context: can sleep
367 */
368 void blk_cleanup_queue(struct request_queue *q)
369 {
370 /* cannot be called from atomic context */
371 might_sleep();
372
373 WARN_ON_ONCE(blk_queue_registered(q));
374
375 /* mark @q DYING, no new request or merges will be allowed afterwards */
376 blk_set_queue_dying(q);
377
378 blk_queue_flag_set(QUEUE_FLAG_NOMERGES, q);
379 blk_queue_flag_set(QUEUE_FLAG_NOXMERGES, q);
380
381 /*
382 * Drain all requests queued before DYING marking. Set DEAD flag to
383 * prevent that blk_mq_run_hw_queues() accesses the hardware queues
384 * after draining finished.
385 */
386 blk_freeze_queue(q);
387
388 rq_qos_exit(q);
389
390 blk_queue_flag_set(QUEUE_FLAG_DEAD, q);
391
392 /* for synchronous bio-based driver finish in-flight integrity i/o */
393 blk_flush_integrity();
394
395 blk_sync_queue(q);
396 if (queue_is_mq(q))
397 blk_mq_exit_queue(q);
398
399 /*
400 * In theory, request pool of sched_tags belongs to request queue.
401 * However, the current implementation requires tag_set for freeing
402 * requests, so free the pool now.
403 *
404 * Queue has become frozen, there can't be any in-queue requests, so
405 * it is safe to free requests now.
406 */
407 mutex_lock(&q->sysfs_lock);
408 if (q->elevator)
409 blk_mq_sched_free_requests(q);
410 mutex_unlock(&q->sysfs_lock);
411
412 percpu_ref_exit(&q->q_usage_counter);
413
414 /* @q is and will stay empty, shutdown and put */
415 blk_put_queue(q);
416 }
417 EXPORT_SYMBOL(blk_cleanup_queue);
418
419 static bool blk_try_enter_queue(struct request_queue *q, bool pm)
420 {
421 rcu_read_lock();
422 if (!percpu_ref_tryget_live(&q->q_usage_counter))
423 goto fail;
424
425 /*
426 * The code that increments the pm_only counter must ensure that the
427 * counter is globally visible before the queue is unfrozen.
428 */
429 if (blk_queue_pm_only(q) &&
430 (!pm || queue_rpm_status(q) == RPM_SUSPENDED))
431 goto fail_put;
432
433 rcu_read_unlock();
434 return true;
435
436 fail_put:
437 percpu_ref_put(&q->q_usage_counter);
438 fail:
439 rcu_read_unlock();
440 return false;
441 }
442
443 /**
444 * blk_queue_enter() - try to increase q->q_usage_counter
445 * @q: request queue pointer
446 * @flags: BLK_MQ_REQ_NOWAIT and/or BLK_MQ_REQ_PM
447 */
448 int blk_queue_enter(struct request_queue *q, blk_mq_req_flags_t flags)
449 {
450 const bool pm = flags & BLK_MQ_REQ_PM;
451
452 while (!blk_try_enter_queue(q, pm)) {
453 if (flags & BLK_MQ_REQ_NOWAIT)
454 return -EBUSY;
455
456 /*
457 * read pair of barrier in blk_freeze_queue_start(), we need to
458 * order reading __PERCPU_REF_DEAD flag of .q_usage_counter and
459 * reading .mq_freeze_depth or queue dying flag, otherwise the
460 * following wait may never return if the two reads are
461 * reordered.
462 */
463 smp_rmb();
464 wait_event(q->mq_freeze_wq,
465 (!q->mq_freeze_depth &&
466 blk_pm_resume_queue(pm, q)) ||
467 blk_queue_dying(q));
468 if (blk_queue_dying(q))
469 return -ENODEV;
470 }
471
472 return 0;
473 }
474
475 static inline int bio_queue_enter(struct bio *bio)
476 {
477 struct request_queue *q = bio->bi_bdev->bd_disk->queue;
478 bool nowait = bio->bi_opf & REQ_NOWAIT;
479 int ret;
480
481 ret = blk_queue_enter(q, nowait ? BLK_MQ_REQ_NOWAIT : 0);
482 if (unlikely(ret)) {
483 if (nowait && !blk_queue_dying(q))
484 bio_wouldblock_error(bio);
485 else
486 bio_io_error(bio);
487 }
488
489 return ret;
490 }
491
492 void blk_queue_exit(struct request_queue *q)
493 {
494 percpu_ref_put(&q->q_usage_counter);
495 }
496
497 static void blk_queue_usage_counter_release(struct percpu_ref *ref)
498 {
499 struct request_queue *q =
500 container_of(ref, struct request_queue, q_usage_counter);
501
502 wake_up_all(&q->mq_freeze_wq);
503 }
504
505 static void blk_rq_timed_out_timer(struct timer_list *t)
506 {
507 struct request_queue *q = from_timer(q, t, timeout);
508
509 kblockd_schedule_work(&q->timeout_work);
510 }
511
512 static void blk_timeout_work(struct work_struct *work)
513 {
514 }
515
516 struct request_queue *blk_alloc_queue(int node_id)
517 {
518 struct request_queue *q;
519 int ret;
520
521 q = kmem_cache_alloc_node(blk_requestq_cachep,
522 GFP_KERNEL | __GFP_ZERO, node_id);
523 if (!q)
524 return NULL;
525
526 q->last_merge = NULL;
527
528 q->id = ida_simple_get(&blk_queue_ida, 0, 0, GFP_KERNEL);
529 if (q->id < 0)
530 goto fail_q;
531
532 ret = bioset_init(&q->bio_split, BIO_POOL_SIZE, 0, 0);
533 if (ret)
534 goto fail_id;
535
536 q->stats = blk_alloc_queue_stats();
537 if (!q->stats)
538 goto fail_split;
539
540 q->node = node_id;
541
542 atomic_set(&q->nr_active_requests_shared_sbitmap, 0);
543
544 timer_setup(&q->timeout, blk_rq_timed_out_timer, 0);
545 INIT_WORK(&q->timeout_work, blk_timeout_work);
546 INIT_LIST_HEAD(&q->icq_list);
547 #ifdef CONFIG_BLK_CGROUP
548 INIT_LIST_HEAD(&q->blkg_list);
549 #endif
550
551 kobject_init(&q->kobj, &blk_queue_ktype);
552
553 mutex_init(&q->debugfs_mutex);
554 mutex_init(&q->sysfs_lock);
555 mutex_init(&q->sysfs_dir_lock);
556 spin_lock_init(&q->queue_lock);
557
558 init_waitqueue_head(&q->mq_freeze_wq);
559 mutex_init(&q->mq_freeze_lock);
560
561 /*
562 * Init percpu_ref in atomic mode so that it's faster to shutdown.
563 * See blk_register_queue() for details.
564 */
565 if (percpu_ref_init(&q->q_usage_counter,
566 blk_queue_usage_counter_release,
567 PERCPU_REF_INIT_ATOMIC, GFP_KERNEL))
568 goto fail_stats;
569
570 if (blkcg_init_queue(q))
571 goto fail_ref;
572
573 blk_queue_dma_alignment(q, 511);
574 blk_set_default_limits(&q->limits);
575 q->nr_requests = BLKDEV_MAX_RQ;
576
577 return q;
578
579 fail_ref:
580 percpu_ref_exit(&q->q_usage_counter);
581 fail_stats:
582 blk_free_queue_stats(q->stats);
583 fail_split:
584 bioset_exit(&q->bio_split);
585 fail_id:
586 ida_simple_remove(&blk_queue_ida, q->id);
587 fail_q:
588 kmem_cache_free(blk_requestq_cachep, q);
589 return NULL;
590 }
591
592 /**
593 * blk_get_queue - increment the request_queue refcount
594 * @q: the request_queue structure to increment the refcount for
595 *
596 * Increment the refcount of the request_queue kobject.
597 *
598 * Context: Any context.
599 */
600 bool blk_get_queue(struct request_queue *q)
601 {
602 if (likely(!blk_queue_dying(q))) {
603 __blk_get_queue(q);
604 return true;
605 }
606
607 return false;
608 }
609 EXPORT_SYMBOL(blk_get_queue);
610
611 /**
612 * blk_get_request - allocate a request
613 * @q: request queue to allocate a request for
614 * @op: operation (REQ_OP_*) and REQ_* flags, e.g. REQ_SYNC.
615 * @flags: BLK_MQ_REQ_* flags, e.g. BLK_MQ_REQ_NOWAIT.
616 */
617 struct request *blk_get_request(struct request_queue *q, unsigned int op,
618 blk_mq_req_flags_t flags)
619 {
620 struct request *req;
621
622 WARN_ON_ONCE(op & REQ_NOWAIT);
623 WARN_ON_ONCE(flags & ~(BLK_MQ_REQ_NOWAIT | BLK_MQ_REQ_PM));
624
625 req = blk_mq_alloc_request(q, op, flags);
626 if (!IS_ERR(req) && q->mq_ops->initialize_rq_fn)
627 q->mq_ops->initialize_rq_fn(req);
628
629 return req;
630 }
631 EXPORT_SYMBOL(blk_get_request);
632
633 void blk_put_request(struct request *req)
634 {
635 blk_mq_free_request(req);
636 }
637 EXPORT_SYMBOL(blk_put_request);
638
639 static void handle_bad_sector(struct bio *bio, sector_t maxsector)
640 {
641 char b[BDEVNAME_SIZE];
642
643 pr_info_ratelimited("attempt to access beyond end of device\n"
644 "%s: rw=%d, want=%llu, limit=%llu\n",
645 bio_devname(bio, b), bio->bi_opf,
646 bio_end_sector(bio), maxsector);
647 }
648
649 #ifdef CONFIG_FAIL_MAKE_REQUEST
650
651 static DECLARE_FAULT_ATTR(fail_make_request);
652
653 static int __init setup_fail_make_request(char *str)
654 {
655 return setup_fault_attr(&fail_make_request, str);
656 }
657 __setup("fail_make_request=", setup_fail_make_request);
658
659 static bool should_fail_request(struct block_device *part, unsigned int bytes)
660 {
661 return part->bd_make_it_fail && should_fail(&fail_make_request, bytes);
662 }
663
664 static int __init fail_make_request_debugfs(void)
665 {
666 struct dentry *dir = fault_create_debugfs_attr("fail_make_request",
667 NULL, &fail_make_request);
668
669 return PTR_ERR_OR_ZERO(dir);
670 }
671
672 late_initcall(fail_make_request_debugfs);
673
674 #else /* CONFIG_FAIL_MAKE_REQUEST */
675
676 static inline bool should_fail_request(struct block_device *part,
677 unsigned int bytes)
678 {
679 return false;
680 }
681
682 #endif /* CONFIG_FAIL_MAKE_REQUEST */
683
684 static inline bool bio_check_ro(struct bio *bio)
685 {
686 if (op_is_write(bio_op(bio)) && bdev_read_only(bio->bi_bdev)) {
687 char b[BDEVNAME_SIZE];
688
689 if (op_is_flush(bio->bi_opf) && !bio_sectors(bio))
690 return false;
691
692 WARN_ONCE(1,
693 "Trying to write to read-only block-device %s (partno %d)\n",
694 bio_devname(bio, b), bio->bi_bdev->bd_partno);
695 /* Older lvm-tools actually trigger this */
696 return false;
697 }
698
699 return false;
700 }
701
702 static noinline int should_fail_bio(struct bio *bio)
703 {
704 if (should_fail_request(bdev_whole(bio->bi_bdev), bio->bi_iter.bi_size))
705 return -EIO;
706 return 0;
707 }
708 ALLOW_ERROR_INJECTION(should_fail_bio, ERRNO);
709
710 /*
711 * Check whether this bio extends beyond the end of the device or partition.
712 * This may well happen - the kernel calls bread() without checking the size of
713 * the device, e.g., when mounting a file system.
714 */
715 static inline int bio_check_eod(struct bio *bio)
716 {
717 sector_t maxsector = bdev_nr_sectors(bio->bi_bdev);
718 unsigned int nr_sectors = bio_sectors(bio);
719
720 if (nr_sectors && maxsector &&
721 (nr_sectors > maxsector ||
722 bio->bi_iter.bi_sector > maxsector - nr_sectors)) {
723 handle_bad_sector(bio, maxsector);
724 return -EIO;
725 }
726 return 0;
727 }
728
729 /*
730 * Remap block n of partition p to block n+start(p) of the disk.
731 */
732 static int blk_partition_remap(struct bio *bio)
733 {
734 struct block_device *p = bio->bi_bdev;
735
736 if (unlikely(should_fail_request(p, bio->bi_iter.bi_size)))
737 return -EIO;
738 if (bio_sectors(bio)) {
739 bio->bi_iter.bi_sector += p->bd_start_sect;
740 trace_block_bio_remap(bio, p->bd_dev,
741 bio->bi_iter.bi_sector -
742 p->bd_start_sect);
743 }
744 bio_set_flag(bio, BIO_REMAPPED);
745 return 0;
746 }
747
748 /*
749 * Check write append to a zoned block device.
750 */
751 static inline blk_status_t blk_check_zone_append(struct request_queue *q,
752 struct bio *bio)
753 {
754 sector_t pos = bio->bi_iter.bi_sector;
755 int nr_sectors = bio_sectors(bio);
756
757 /* Only applicable to zoned block devices */
758 if (!blk_queue_is_zoned(q))
759 return BLK_STS_NOTSUPP;
760
761 /* The bio sector must point to the start of a sequential zone */
762 if (pos & (blk_queue_zone_sectors(q) - 1) ||
763 !blk_queue_zone_is_seq(q, pos))
764 return BLK_STS_IOERR;
765
766 /*
767 * Not allowed to cross zone boundaries. Otherwise, the BIO will be
768 * split and could result in non-contiguous sectors being written in
769 * different zones.
770 */
771 if (nr_sectors > q->limits.chunk_sectors)
772 return BLK_STS_IOERR;
773
774 /* Make sure the BIO is small enough and will not get split */
775 if (nr_sectors > q->limits.max_zone_append_sectors)
776 return BLK_STS_IOERR;
777
778 bio->bi_opf |= REQ_NOMERGE;
779
780 return BLK_STS_OK;
781 }
782
783 static noinline_for_stack bool submit_bio_checks(struct bio *bio)
784 {
785 struct block_device *bdev = bio->bi_bdev;
786 struct request_queue *q = bdev->bd_disk->queue;
787 blk_status_t status = BLK_STS_IOERR;
788 struct blk_plug *plug;
789
790 might_sleep();
791
792 plug = blk_mq_plug(q, bio);
793 if (plug && plug->nowait)
794 bio->bi_opf |= REQ_NOWAIT;
795
796 /*
797 * For a REQ_NOWAIT based request, return -EOPNOTSUPP
798 * if queue does not support NOWAIT.
799 */
800 if ((bio->bi_opf & REQ_NOWAIT) && !blk_queue_nowait(q))
801 goto not_supported;
802
803 if (should_fail_bio(bio))
804 goto end_io;
805 if (unlikely(bio_check_ro(bio)))
806 goto end_io;
807 if (!bio_flagged(bio, BIO_REMAPPED)) {
808 if (unlikely(bio_check_eod(bio)))
809 goto end_io;
810 if (bdev->bd_partno && unlikely(blk_partition_remap(bio)))
811 goto end_io;
812 }
813
814 /*
815 * Filter flush bio's early so that bio based drivers without flush
816 * support don't have to worry about them.
817 */
818 if (op_is_flush(bio->bi_opf) &&
819 !test_bit(QUEUE_FLAG_WC, &q->queue_flags)) {
820 bio->bi_opf &= ~(REQ_PREFLUSH | REQ_FUA);
821 if (!bio_sectors(bio)) {
822 status = BLK_STS_OK;
823 goto end_io;
824 }
825 }
826
827 if (!test_bit(QUEUE_FLAG_POLL, &q->queue_flags))
828 bio_clear_hipri(bio);
829
830 switch (bio_op(bio)) {
831 case REQ_OP_DISCARD:
832 if (!blk_queue_discard(q))
833 goto not_supported;
834 break;
835 case REQ_OP_SECURE_ERASE:
836 if (!blk_queue_secure_erase(q))
837 goto not_supported;
838 break;
839 case REQ_OP_WRITE_SAME:
840 if (!q->limits.max_write_same_sectors)
841 goto not_supported;
842 break;
843 case REQ_OP_ZONE_APPEND:
844 status = blk_check_zone_append(q, bio);
845 if (status != BLK_STS_OK)
846 goto end_io;
847 break;
848 case REQ_OP_ZONE_RESET:
849 case REQ_OP_ZONE_OPEN:
850 case REQ_OP_ZONE_CLOSE:
851 case REQ_OP_ZONE_FINISH:
852 if (!blk_queue_is_zoned(q))
853 goto not_supported;
854 break;
855 case REQ_OP_ZONE_RESET_ALL:
856 if (!blk_queue_is_zoned(q) || !blk_queue_zone_resetall(q))
857 goto not_supported;
858 break;
859 case REQ_OP_WRITE_ZEROES:
860 if (!q->limits.max_write_zeroes_sectors)
861 goto not_supported;
862 break;
863 default:
864 break;
865 }
866
867 /*
868 * Various block parts want %current->io_context, so allocate it up
869 * front rather than dealing with lots of pain to allocate it only
870 * where needed. This may fail and the block layer knows how to live
871 * with it.
872 */
873 if (unlikely(!current->io_context))
874 create_task_io_context(current, GFP_ATOMIC, q->node);
875
876 if (blk_throtl_bio(bio)) {
877 blkcg_bio_issue_init(bio);
878 return false;
879 }
880
881 blk_cgroup_bio_start(bio);
882 blkcg_bio_issue_init(bio);
883
884 if (!bio_flagged(bio, BIO_TRACE_COMPLETION)) {
885 trace_block_bio_queue(bio);
886 /* Now that enqueuing has been traced, we need to trace
887 * completion as well.
888 */
889 bio_set_flag(bio, BIO_TRACE_COMPLETION);
890 }
891 return true;
892
893 not_supported:
894 status = BLK_STS_NOTSUPP;
895 end_io:
896 bio->bi_status = status;
897 bio_endio(bio);
898 return false;
899 }
900
901 static blk_qc_t __submit_bio(struct bio *bio)
902 {
903 struct gendisk *disk = bio->bi_bdev->bd_disk;
904 blk_qc_t ret = BLK_QC_T_NONE;
905
906 if (unlikely(bio_queue_enter(bio) != 0))
907 return BLK_QC_T_NONE;
908
909 if (!submit_bio_checks(bio) || !blk_crypto_bio_prep(&bio))
910 goto queue_exit;
911 if (disk->fops->submit_bio) {
912 ret = disk->fops->submit_bio(bio);
913 goto queue_exit;
914 }
915 return blk_mq_submit_bio(bio);
916
917 queue_exit:
918 blk_queue_exit(disk->queue);
919 return ret;
920 }
921
922 /*
923 * The loop in this function may be a bit non-obvious, and so deserves some
924 * explanation:
925 *
926 * - Before entering the loop, bio->bi_next is NULL (as all callers ensure
927 * that), so we have a list with a single bio.
928 * - We pretend that we have just taken it off a longer list, so we assign
929 * bio_list to a pointer to the bio_list_on_stack, thus initialising the
930 * bio_list of new bios to be added. ->submit_bio() may indeed add some more
931 * bios through a recursive call to submit_bio_noacct. If it did, we find a
932 * non-NULL value in bio_list and re-enter the loop from the top.
933 * - In this case we really did just take the bio of the top of the list (no
934 * pretending) and so remove it from bio_list, and call into ->submit_bio()
935 * again.
936 *
937 * bio_list_on_stack[0] contains bios submitted by the current ->submit_bio.
938 * bio_list_on_stack[1] contains bios that were submitted before the current
939 * ->submit_bio_bio, but that haven't been processed yet.
940 */
941 static blk_qc_t __submit_bio_noacct(struct bio *bio)
942 {
943 struct bio_list bio_list_on_stack[2];
944 blk_qc_t ret = BLK_QC_T_NONE;
945
946 BUG_ON(bio->bi_next);
947
948 bio_list_init(&bio_list_on_stack[0]);
949 current->bio_list = bio_list_on_stack;
950
951 do {
952 struct request_queue *q = bio->bi_bdev->bd_disk->queue;
953 struct bio_list lower, same;
954
955 /*
956 * Create a fresh bio_list for all subordinate requests.
957 */
958 bio_list_on_stack[1] = bio_list_on_stack[0];
959 bio_list_init(&bio_list_on_stack[0]);
960
961 ret = __submit_bio(bio);
962
963 /*
964 * Sort new bios into those for a lower level and those for the
965 * same level.
966 */
967 bio_list_init(&lower);
968 bio_list_init(&same);
969 while ((bio = bio_list_pop(&bio_list_on_stack[0])) != NULL)
970 if (q == bio->bi_bdev->bd_disk->queue)
971 bio_list_add(&same, bio);
972 else
973 bio_list_add(&lower, bio);
974
975 /*
976 * Now assemble so we handle the lowest level first.
977 */
978 bio_list_merge(&bio_list_on_stack[0], &lower);
979 bio_list_merge(&bio_list_on_stack[0], &same);
980 bio_list_merge(&bio_list_on_stack[0], &bio_list_on_stack[1]);
981 } while ((bio = bio_list_pop(&bio_list_on_stack[0])));
982
983 current->bio_list = NULL;
984 return ret;
985 }
986
987 static blk_qc_t __submit_bio_noacct_mq(struct bio *bio)
988 {
989 struct bio_list bio_list[2] = { };
990 blk_qc_t ret;
991
992 current->bio_list = bio_list;
993
994 do {
995 ret = __submit_bio(bio);
996 } while ((bio = bio_list_pop(&bio_list[0])));
997
998 current->bio_list = NULL;
999 return ret;
1000 }
1001
1002 /**
1003 * submit_bio_noacct - re-submit a bio to the block device layer for I/O
1004 * @bio: The bio describing the location in memory and on the device.
1005 *
1006 * This is a version of submit_bio() that shall only be used for I/O that is
1007 * resubmitted to lower level drivers by stacking block drivers. All file
1008 * systems and other upper level users of the block layer should use
1009 * submit_bio() instead.
1010 */
1011 blk_qc_t submit_bio_noacct(struct bio *bio)
1012 {
1013 /*
1014 * We only want one ->submit_bio to be active at a time, else stack
1015 * usage with stacked devices could be a problem. Use current->bio_list
1016 * to collect a list of requests submited by a ->submit_bio method while
1017 * it is active, and then process them after it returned.
1018 */
1019 if (current->bio_list) {
1020 bio_list_add(&current->bio_list[0], bio);
1021 return BLK_QC_T_NONE;
1022 }
1023
1024 if (!bio->bi_bdev->bd_disk->fops->submit_bio)
1025 return __submit_bio_noacct_mq(bio);
1026 return __submit_bio_noacct(bio);
1027 }
1028 EXPORT_SYMBOL(submit_bio_noacct);
1029
1030 /**
1031 * submit_bio - submit a bio to the block device layer for I/O
1032 * @bio: The &struct bio which describes the I/O
1033 *
1034 * submit_bio() is used to submit I/O requests to block devices. It is passed a
1035 * fully set up &struct bio that describes the I/O that needs to be done. The
1036 * bio will be send to the device described by the bi_bdev field.
1037 *
1038 * The success/failure status of the request, along with notification of
1039 * completion, is delivered asynchronously through the ->bi_end_io() callback
1040 * in @bio. The bio must NOT be touched by thecaller until ->bi_end_io() has
1041 * been called.
1042 */
1043 blk_qc_t submit_bio(struct bio *bio)
1044 {
1045 if (blkcg_punt_bio_submit(bio))
1046 return BLK_QC_T_NONE;
1047
1048 /*
1049 * If it's a regular read/write or a barrier with data attached,
1050 * go through the normal accounting stuff before submission.
1051 */
1052 if (bio_has_data(bio)) {
1053 unsigned int count;
1054
1055 if (unlikely(bio_op(bio) == REQ_OP_WRITE_SAME))
1056 count = queue_logical_block_size(
1057 bio->bi_bdev->bd_disk->queue) >> 9;
1058 else
1059 count = bio_sectors(bio);
1060
1061 if (op_is_write(bio_op(bio))) {
1062 count_vm_events(PGPGOUT, count);
1063 } else {
1064 task_io_account_read(bio->bi_iter.bi_size);
1065 count_vm_events(PGPGIN, count);
1066 }
1067 }
1068
1069 /*
1070 * If we're reading data that is part of the userspace workingset, count
1071 * submission time as memory stall. When the device is congested, or
1072 * the submitting cgroup IO-throttled, submission can be a significant
1073 * part of overall IO time.
1074 */
1075 if (unlikely(bio_op(bio) == REQ_OP_READ &&
1076 bio_flagged(bio, BIO_WORKINGSET))) {
1077 unsigned long pflags;
1078 blk_qc_t ret;
1079
1080 psi_memstall_enter(&pflags);
1081 ret = submit_bio_noacct(bio);
1082 psi_memstall_leave(&pflags);
1083
1084 return ret;
1085 }
1086
1087 return submit_bio_noacct(bio);
1088 }
1089 EXPORT_SYMBOL(submit_bio);
1090
1091 /**
1092 * blk_cloned_rq_check_limits - Helper function to check a cloned request
1093 * for the new queue limits
1094 * @q: the queue
1095 * @rq: the request being checked
1096 *
1097 * Description:
1098 * @rq may have been made based on weaker limitations of upper-level queues
1099 * in request stacking drivers, and it may violate the limitation of @q.
1100 * Since the block layer and the underlying device driver trust @rq
1101 * after it is inserted to @q, it should be checked against @q before
1102 * the insertion using this generic function.
1103 *
1104 * Request stacking drivers like request-based dm may change the queue
1105 * limits when retrying requests on other queues. Those requests need
1106 * to be checked against the new queue limits again during dispatch.
1107 */
1108 static blk_status_t blk_cloned_rq_check_limits(struct request_queue *q,
1109 struct request *rq)
1110 {
1111 unsigned int max_sectors = blk_queue_get_max_sectors(q, req_op(rq));
1112
1113 if (blk_rq_sectors(rq) > max_sectors) {
1114 /*
1115 * SCSI device does not have a good way to return if
1116 * Write Same/Zero is actually supported. If a device rejects
1117 * a non-read/write command (discard, write same,etc.) the
1118 * low-level device driver will set the relevant queue limit to
1119 * 0 to prevent blk-lib from issuing more of the offending
1120 * operations. Commands queued prior to the queue limit being
1121 * reset need to be completed with BLK_STS_NOTSUPP to avoid I/O
1122 * errors being propagated to upper layers.
1123 */
1124 if (max_sectors == 0)
1125 return BLK_STS_NOTSUPP;
1126
1127 printk(KERN_ERR "%s: over max size limit. (%u > %u)\n",
1128 __func__, blk_rq_sectors(rq), max_sectors);
1129 return BLK_STS_IOERR;
1130 }
1131
1132 /*
1133 * The queue settings related to segment counting may differ from the
1134 * original queue.
1135 */
1136 rq->nr_phys_segments = blk_recalc_rq_segments(rq);
1137 if (rq->nr_phys_segments > queue_max_segments(q)) {
1138 printk(KERN_ERR "%s: over max segments limit. (%hu > %hu)\n",
1139 __func__, rq->nr_phys_segments, queue_max_segments(q));
1140 return BLK_STS_IOERR;
1141 }
1142
1143 return BLK_STS_OK;
1144 }
1145
1146 /**
1147 * blk_insert_cloned_request - Helper for stacking drivers to submit a request
1148 * @q: the queue to submit the request
1149 * @rq: the request being queued
1150 */
1151 blk_status_t blk_insert_cloned_request(struct request_queue *q, struct request *rq)
1152 {
1153 blk_status_t ret;
1154
1155 ret = blk_cloned_rq_check_limits(q, rq);
1156 if (ret != BLK_STS_OK)
1157 return ret;
1158
1159 if (rq->rq_disk &&
1160 should_fail_request(rq->rq_disk->part0, blk_rq_bytes(rq)))
1161 return BLK_STS_IOERR;
1162
1163 if (blk_crypto_insert_cloned_request(rq))
1164 return BLK_STS_IOERR;
1165
1166 if (blk_queue_io_stat(q))
1167 blk_account_io_start(rq);
1168
1169 /*
1170 * Since we have a scheduler attached on the top device,
1171 * bypass a potential scheduler on the bottom device for
1172 * insert.
1173 */
1174 return blk_mq_request_issue_directly(rq, true);
1175 }
1176 EXPORT_SYMBOL_GPL(blk_insert_cloned_request);
1177
1178 /**
1179 * blk_rq_err_bytes - determine number of bytes till the next failure boundary
1180 * @rq: request to examine
1181 *
1182 * Description:
1183 * A request could be merge of IOs which require different failure
1184 * handling. This function determines the number of bytes which
1185 * can be failed from the beginning of the request without
1186 * crossing into area which need to be retried further.
1187 *
1188 * Return:
1189 * The number of bytes to fail.
1190 */
1191 unsigned int blk_rq_err_bytes(const struct request *rq)
1192 {
1193 unsigned int ff = rq->cmd_flags & REQ_FAILFAST_MASK;
1194 unsigned int bytes = 0;
1195 struct bio *bio;
1196
1197 if (!(rq->rq_flags & RQF_MIXED_MERGE))
1198 return blk_rq_bytes(rq);
1199
1200 /*
1201 * Currently the only 'mixing' which can happen is between
1202 * different fastfail types. We can safely fail portions
1203 * which have all the failfast bits that the first one has -
1204 * the ones which are at least as eager to fail as the first
1205 * one.
1206 */
1207 for (bio = rq->bio; bio; bio = bio->bi_next) {
1208 if ((bio->bi_opf & ff) != ff)
1209 break;
1210 bytes += bio->bi_iter.bi_size;
1211 }
1212
1213 /* this could lead to infinite loop */
1214 BUG_ON(blk_rq_bytes(rq) && !bytes);
1215 return bytes;
1216 }
1217 EXPORT_SYMBOL_GPL(blk_rq_err_bytes);
1218
1219 static void update_io_ticks(struct block_device *part, unsigned long now,
1220 bool end)
1221 {
1222 unsigned long stamp;
1223 again:
1224 stamp = READ_ONCE(part->bd_stamp);
1225 if (unlikely(time_after(now, stamp))) {
1226 if (likely(cmpxchg(&part->bd_stamp, stamp, now) == stamp))
1227 __part_stat_add(part, io_ticks, end ? now - stamp : 1);
1228 }
1229 if (part->bd_partno) {
1230 part = bdev_whole(part);
1231 goto again;
1232 }
1233 }
1234
1235 static void blk_account_io_completion(struct request *req, unsigned int bytes)
1236 {
1237 if (req->part && blk_do_io_stat(req)) {
1238 const int sgrp = op_stat_group(req_op(req));
1239
1240 part_stat_lock();
1241 part_stat_add(req->part, sectors[sgrp], bytes >> 9);
1242 part_stat_unlock();
1243 }
1244 }
1245
1246 void blk_account_io_done(struct request *req, u64 now)
1247 {
1248 /*
1249 * Account IO completion. flush_rq isn't accounted as a
1250 * normal IO on queueing nor completion. Accounting the
1251 * containing request is enough.
1252 */
1253 if (req->part && blk_do_io_stat(req) &&
1254 !(req->rq_flags & RQF_FLUSH_SEQ)) {
1255 const int sgrp = op_stat_group(req_op(req));
1256
1257 part_stat_lock();
1258 update_io_ticks(req->part, jiffies, true);
1259 part_stat_inc(req->part, ios[sgrp]);
1260 part_stat_add(req->part, nsecs[sgrp], now - req->start_time_ns);
1261 part_stat_unlock();
1262 }
1263 }
1264
1265 void blk_account_io_start(struct request *rq)
1266 {
1267 if (!blk_do_io_stat(rq))
1268 return;
1269
1270 /* passthrough requests can hold bios that do not have ->bi_bdev set */
1271 if (rq->bio && rq->bio->bi_bdev)
1272 rq->part = rq->bio->bi_bdev;
1273 else
1274 rq->part = rq->rq_disk->part0;
1275
1276 part_stat_lock();
1277 update_io_ticks(rq->part, jiffies, false);
1278 part_stat_unlock();
1279 }
1280
1281 static unsigned long __part_start_io_acct(struct block_device *part,
1282 unsigned int sectors, unsigned int op)
1283 {
1284 const int sgrp = op_stat_group(op);
1285 unsigned long now = READ_ONCE(jiffies);
1286
1287 part_stat_lock();
1288 update_io_ticks(part, now, false);
1289 part_stat_inc(part, ios[sgrp]);
1290 part_stat_add(part, sectors[sgrp], sectors);
1291 part_stat_local_inc(part, in_flight[op_is_write(op)]);
1292 part_stat_unlock();
1293
1294 return now;
1295 }
1296
1297 /**
1298 * bio_start_io_acct - start I/O accounting for bio based drivers
1299 * @bio: bio to start account for
1300 *
1301 * Returns the start time that should be passed back to bio_end_io_acct().
1302 */
1303 unsigned long bio_start_io_acct(struct bio *bio)
1304 {
1305 return __part_start_io_acct(bio->bi_bdev, bio_sectors(bio), bio_op(bio));
1306 }
1307 EXPORT_SYMBOL_GPL(bio_start_io_acct);
1308
1309 unsigned long disk_start_io_acct(struct gendisk *disk, unsigned int sectors,
1310 unsigned int op)
1311 {
1312 return __part_start_io_acct(disk->part0, sectors, op);
1313 }
1314 EXPORT_SYMBOL(disk_start_io_acct);
1315
1316 static void __part_end_io_acct(struct block_device *part, unsigned int op,
1317 unsigned long start_time)
1318 {
1319 const int sgrp = op_stat_group(op);
1320 unsigned long now = READ_ONCE(jiffies);
1321 unsigned long duration = now - start_time;
1322
1323 part_stat_lock();
1324 update_io_ticks(part, now, true);
1325 part_stat_add(part, nsecs[sgrp], jiffies_to_nsecs(duration));
1326 part_stat_local_dec(part, in_flight[op_is_write(op)]);
1327 part_stat_unlock();
1328 }
1329
1330 void bio_end_io_acct_remapped(struct bio *bio, unsigned long start_time,
1331 struct block_device *orig_bdev)
1332 {
1333 __part_end_io_acct(orig_bdev, bio_op(bio), start_time);
1334 }
1335 EXPORT_SYMBOL_GPL(bio_end_io_acct_remapped);
1336
1337 void disk_end_io_acct(struct gendisk *disk, unsigned int op,
1338 unsigned long start_time)
1339 {
1340 __part_end_io_acct(disk->part0, op, start_time);
1341 }
1342 EXPORT_SYMBOL(disk_end_io_acct);
1343
1344 /*
1345 * Steal bios from a request and add them to a bio list.
1346 * The request must not have been partially completed before.
1347 */
1348 void blk_steal_bios(struct bio_list *list, struct request *rq)
1349 {
1350 if (rq->bio) {
1351 if (list->tail)
1352 list->tail->bi_next = rq->bio;
1353 else
1354 list->head = rq->bio;
1355 list->tail = rq->biotail;
1356
1357 rq->bio = NULL;
1358 rq->biotail = NULL;
1359 }
1360
1361 rq->__data_len = 0;
1362 }
1363 EXPORT_SYMBOL_GPL(blk_steal_bios);
1364
1365 /**
1366 * blk_update_request - Complete multiple bytes without completing the request
1367 * @req: the request being processed
1368 * @error: block status code
1369 * @nr_bytes: number of bytes to complete for @req
1370 *
1371 * Description:
1372 * Ends I/O on a number of bytes attached to @req, but doesn't complete
1373 * the request structure even if @req doesn't have leftover.
1374 * If @req has leftover, sets it up for the next range of segments.
1375 *
1376 * Passing the result of blk_rq_bytes() as @nr_bytes guarantees
1377 * %false return from this function.
1378 *
1379 * Note:
1380 * The RQF_SPECIAL_PAYLOAD flag is ignored on purpose in this function
1381 * except in the consistency check at the end of this function.
1382 *
1383 * Return:
1384 * %false - this request doesn't have any more data
1385 * %true - this request has more data
1386 **/
1387 bool blk_update_request(struct request *req, blk_status_t error,
1388 unsigned int nr_bytes)
1389 {
1390 int total_bytes;
1391
1392 trace_block_rq_complete(req, blk_status_to_errno(error), nr_bytes);
1393
1394 if (!req->bio)
1395 return false;
1396
1397 #ifdef CONFIG_BLK_DEV_INTEGRITY
1398 if (blk_integrity_rq(req) && req_op(req) == REQ_OP_READ &&
1399 error == BLK_STS_OK)
1400 req->q->integrity.profile->complete_fn(req, nr_bytes);
1401 #endif
1402
1403 if (unlikely(error && !blk_rq_is_passthrough(req) &&
1404 !(req->rq_flags & RQF_QUIET)))
1405 print_req_error(req, error, __func__);
1406
1407 blk_account_io_completion(req, nr_bytes);
1408
1409 total_bytes = 0;
1410 while (req->bio) {
1411 struct bio *bio = req->bio;
1412 unsigned bio_bytes = min(bio->bi_iter.bi_size, nr_bytes);
1413
1414 if (bio_bytes == bio->bi_iter.bi_size)
1415 req->bio = bio->bi_next;
1416
1417 /* Completion has already been traced */
1418 bio_clear_flag(bio, BIO_TRACE_COMPLETION);
1419 req_bio_endio(req, bio, bio_bytes, error);
1420
1421 total_bytes += bio_bytes;
1422 nr_bytes -= bio_bytes;
1423
1424 if (!nr_bytes)
1425 break;
1426 }
1427
1428 /*
1429 * completely done
1430 */
1431 if (!req->bio) {
1432 /*
1433 * Reset counters so that the request stacking driver
1434 * can find how many bytes remain in the request
1435 * later.
1436 */
1437 req->__data_len = 0;
1438 return false;
1439 }
1440
1441 req->__data_len -= total_bytes;
1442
1443 /* update sector only for requests with clear definition of sector */
1444 if (!blk_rq_is_passthrough(req))
1445 req->__sector += total_bytes >> 9;
1446
1447 /* mixed attributes always follow the first bio */
1448 if (req->rq_flags & RQF_MIXED_MERGE) {
1449 req->cmd_flags &= ~REQ_FAILFAST_MASK;
1450 req->cmd_flags |= req->bio->bi_opf & REQ_FAILFAST_MASK;
1451 }
1452
1453 if (!(req->rq_flags & RQF_SPECIAL_PAYLOAD)) {
1454 /*
1455 * If total number of sectors is less than the first segment
1456 * size, something has gone terribly wrong.
1457 */
1458 if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {
1459 blk_dump_rq_flags(req, "request botched");
1460 req->__data_len = blk_rq_cur_bytes(req);
1461 }
1462
1463 /* recalculate the number of segments */
1464 req->nr_phys_segments = blk_recalc_rq_segments(req);
1465 }
1466
1467 return true;
1468 }
1469 EXPORT_SYMBOL_GPL(blk_update_request);
1470
1471 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE
1472 /**
1473 * rq_flush_dcache_pages - Helper function to flush all pages in a request
1474 * @rq: the request to be flushed
1475 *
1476 * Description:
1477 * Flush all pages in @rq.
1478 */
1479 void rq_flush_dcache_pages(struct request *rq)
1480 {
1481 struct req_iterator iter;
1482 struct bio_vec bvec;
1483
1484 rq_for_each_segment(bvec, rq, iter)
1485 flush_dcache_page(bvec.bv_page);
1486 }
1487 EXPORT_SYMBOL_GPL(rq_flush_dcache_pages);
1488 #endif
1489
1490 /**
1491 * blk_lld_busy - Check if underlying low-level drivers of a device are busy
1492 * @q : the queue of the device being checked
1493 *
1494 * Description:
1495 * Check if underlying low-level drivers of a device are busy.
1496 * If the drivers want to export their busy state, they must set own
1497 * exporting function using blk_queue_lld_busy() first.
1498 *
1499 * Basically, this function is used only by request stacking drivers
1500 * to stop dispatching requests to underlying devices when underlying
1501 * devices are busy. This behavior helps more I/O merging on the queue
1502 * of the request stacking driver and prevents I/O throughput regression
1503 * on burst I/O load.
1504 *
1505 * Return:
1506 * 0 - Not busy (The request stacking driver should dispatch request)
1507 * 1 - Busy (The request stacking driver should stop dispatching request)
1508 */
1509 int blk_lld_busy(struct request_queue *q)
1510 {
1511 if (queue_is_mq(q) && q->mq_ops->busy)
1512 return q->mq_ops->busy(q);
1513
1514 return 0;
1515 }
1516 EXPORT_SYMBOL_GPL(blk_lld_busy);
1517
1518 /**
1519 * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
1520 * @rq: the clone request to be cleaned up
1521 *
1522 * Description:
1523 * Free all bios in @rq for a cloned request.
1524 */
1525 void blk_rq_unprep_clone(struct request *rq)
1526 {
1527 struct bio *bio;
1528
1529 while ((bio = rq->bio) != NULL) {
1530 rq->bio = bio->bi_next;
1531
1532 bio_put(bio);
1533 }
1534 }
1535 EXPORT_SYMBOL_GPL(blk_rq_unprep_clone);
1536
1537 /**
1538 * blk_rq_prep_clone - Helper function to setup clone request
1539 * @rq: the request to be setup
1540 * @rq_src: original request to be cloned
1541 * @bs: bio_set that bios for clone are allocated from
1542 * @gfp_mask: memory allocation mask for bio
1543 * @bio_ctr: setup function to be called for each clone bio.
1544 * Returns %0 for success, non %0 for failure.
1545 * @data: private data to be passed to @bio_ctr
1546 *
1547 * Description:
1548 * Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
1549 * Also, pages which the original bios are pointing to are not copied
1550 * and the cloned bios just point same pages.
1551 * So cloned bios must be completed before original bios, which means
1552 * the caller must complete @rq before @rq_src.
1553 */
1554 int blk_rq_prep_clone(struct request *rq, struct request *rq_src,
1555 struct bio_set *bs, gfp_t gfp_mask,
1556 int (*bio_ctr)(struct bio *, struct bio *, void *),
1557 void *data)
1558 {
1559 struct bio *bio, *bio_src;
1560
1561 if (!bs)
1562 bs = &fs_bio_set;
1563
1564 __rq_for_each_bio(bio_src, rq_src) {
1565 bio = bio_clone_fast(bio_src, gfp_mask, bs);
1566 if (!bio)
1567 goto free_and_out;
1568
1569 if (bio_ctr && bio_ctr(bio, bio_src, data))
1570 goto free_and_out;
1571
1572 if (rq->bio) {
1573 rq->biotail->bi_next = bio;
1574 rq->biotail = bio;
1575 } else {
1576 rq->bio = rq->biotail = bio;
1577 }
1578 bio = NULL;
1579 }
1580
1581 /* Copy attributes of the original request to the clone request. */
1582 rq->__sector = blk_rq_pos(rq_src);
1583 rq->__data_len = blk_rq_bytes(rq_src);
1584 if (rq_src->rq_flags & RQF_SPECIAL_PAYLOAD) {
1585 rq->rq_flags |= RQF_SPECIAL_PAYLOAD;
1586 rq->special_vec = rq_src->special_vec;
1587 }
1588 rq->nr_phys_segments = rq_src->nr_phys_segments;
1589 rq->ioprio = rq_src->ioprio;
1590
1591 if (rq->bio && blk_crypto_rq_bio_prep(rq, rq->bio, gfp_mask) < 0)
1592 goto free_and_out;
1593
1594 return 0;
1595
1596 free_and_out:
1597 if (bio)
1598 bio_put(bio);
1599 blk_rq_unprep_clone(rq);
1600
1601 return -ENOMEM;
1602 }
1603 EXPORT_SYMBOL_GPL(blk_rq_prep_clone);
1604
1605 int kblockd_schedule_work(struct work_struct *work)
1606 {
1607 return queue_work(kblockd_workqueue, work);
1608 }
1609 EXPORT_SYMBOL(kblockd_schedule_work);
1610
1611 int kblockd_mod_delayed_work_on(int cpu, struct delayed_work *dwork,
1612 unsigned long delay)
1613 {
1614 return mod_delayed_work_on(cpu, kblockd_workqueue, dwork, delay);
1615 }
1616 EXPORT_SYMBOL(kblockd_mod_delayed_work_on);
1617
1618 /**
1619 * blk_start_plug - initialize blk_plug and track it inside the task_struct
1620 * @plug: The &struct blk_plug that needs to be initialized
1621 *
1622 * Description:
1623 * blk_start_plug() indicates to the block layer an intent by the caller
1624 * to submit multiple I/O requests in a batch. The block layer may use
1625 * this hint to defer submitting I/Os from the caller until blk_finish_plug()
1626 * is called. However, the block layer may choose to submit requests
1627 * before a call to blk_finish_plug() if the number of queued I/Os
1628 * exceeds %BLK_MAX_REQUEST_COUNT, or if the size of the I/O is larger than
1629 * %BLK_PLUG_FLUSH_SIZE. The queued I/Os may also be submitted early if
1630 * the task schedules (see below).
1631 *
1632 * Tracking blk_plug inside the task_struct will help with auto-flushing the
1633 * pending I/O should the task end up blocking between blk_start_plug() and
1634 * blk_finish_plug(). This is important from a performance perspective, but
1635 * also ensures that we don't deadlock. For instance, if the task is blocking
1636 * for a memory allocation, memory reclaim could end up wanting to free a
1637 * page belonging to that request that is currently residing in our private
1638 * plug. By flushing the pending I/O when the process goes to sleep, we avoid
1639 * this kind of deadlock.
1640 */
1641 void blk_start_plug(struct blk_plug *plug)
1642 {
1643 struct task_struct *tsk = current;
1644
1645 /*
1646 * If this is a nested plug, don't actually assign it.
1647 */
1648 if (tsk->plug)
1649 return;
1650
1651 INIT_LIST_HEAD(&plug->mq_list);
1652 INIT_LIST_HEAD(&plug->cb_list);
1653 plug->rq_count = 0;
1654 plug->multiple_queues = false;
1655 plug->nowait = false;
1656
1657 /*
1658 * Store ordering should not be needed here, since a potential
1659 * preempt will imply a full memory barrier
1660 */
1661 tsk->plug = plug;
1662 }
1663 EXPORT_SYMBOL(blk_start_plug);
1664
1665 static void flush_plug_callbacks(struct blk_plug *plug, bool from_schedule)
1666 {
1667 LIST_HEAD(callbacks);
1668
1669 while (!list_empty(&plug->cb_list)) {
1670 list_splice_init(&plug->cb_list, &callbacks);
1671
1672 while (!list_empty(&callbacks)) {
1673 struct blk_plug_cb *cb = list_first_entry(&callbacks,
1674 struct blk_plug_cb,
1675 list);
1676 list_del(&cb->list);
1677 cb->callback(cb, from_schedule);
1678 }
1679 }
1680 }
1681
1682 struct blk_plug_cb *blk_check_plugged(blk_plug_cb_fn unplug, void *data,
1683 int size)
1684 {
1685 struct blk_plug *plug = current->plug;
1686 struct blk_plug_cb *cb;
1687
1688 if (!plug)
1689 return NULL;
1690
1691 list_for_each_entry(cb, &plug->cb_list, list)
1692 if (cb->callback == unplug && cb->data == data)
1693 return cb;
1694
1695 /* Not currently on the callback list */
1696 BUG_ON(size < sizeof(*cb));
1697 cb = kzalloc(size, GFP_ATOMIC);
1698 if (cb) {
1699 cb->data = data;
1700 cb->callback = unplug;
1701 list_add(&cb->list, &plug->cb_list);
1702 }
1703 return cb;
1704 }
1705 EXPORT_SYMBOL(blk_check_plugged);
1706
1707 void blk_flush_plug_list(struct blk_plug *plug, bool from_schedule)
1708 {
1709 flush_plug_callbacks(plug, from_schedule);
1710
1711 if (!list_empty(&plug->mq_list))
1712 blk_mq_flush_plug_list(plug, from_schedule);
1713 }
1714
1715 /**
1716 * blk_finish_plug - mark the end of a batch of submitted I/O
1717 * @plug: The &struct blk_plug passed to blk_start_plug()
1718 *
1719 * Description:
1720 * Indicate that a batch of I/O submissions is complete. This function
1721 * must be paired with an initial call to blk_start_plug(). The intent
1722 * is to allow the block layer to optimize I/O submission. See the
1723 * documentation for blk_start_plug() for more information.
1724 */
1725 void blk_finish_plug(struct blk_plug *plug)
1726 {
1727 if (plug != current->plug)
1728 return;
1729 blk_flush_plug_list(plug, false);
1730
1731 current->plug = NULL;
1732 }
1733 EXPORT_SYMBOL(blk_finish_plug);
1734
1735 void blk_io_schedule(void)
1736 {
1737 /* Prevent hang_check timer from firing at us during very long I/O */
1738 unsigned long timeout = sysctl_hung_task_timeout_secs * HZ / 2;
1739
1740 if (timeout)
1741 io_schedule_timeout(timeout);
1742 else
1743 io_schedule();
1744 }
1745 EXPORT_SYMBOL_GPL(blk_io_schedule);
1746
1747 int __init blk_dev_init(void)
1748 {
1749 BUILD_BUG_ON(REQ_OP_LAST >= (1 << REQ_OP_BITS));
1750 BUILD_BUG_ON(REQ_OP_BITS + REQ_FLAG_BITS > 8 *
1751 sizeof_field(struct request, cmd_flags));
1752 BUILD_BUG_ON(REQ_OP_BITS + REQ_FLAG_BITS > 8 *
1753 sizeof_field(struct bio, bi_opf));
1754
1755 /* used for unplugging and affects IO latency/throughput - HIGHPRI */
1756 kblockd_workqueue = alloc_workqueue("kblockd",
1757 WQ_MEM_RECLAIM | WQ_HIGHPRI, 0);
1758 if (!kblockd_workqueue)
1759 panic("Failed to create kblockd\n");
1760
1761 blk_requestq_cachep = kmem_cache_create("request_queue",
1762 sizeof(struct request_queue), 0, SLAB_PANIC, NULL);
1763
1764 blk_debugfs_root = debugfs_create_dir("block", NULL);
1765
1766 return 0;
1767 }