]> git.ipfire.org Git - people/ms/linux.git/blame - block/bio.c
block: factor out a bvec_alloc_gfp helper
[people/ms/linux.git] / block / bio.c
CommitLineData
8c16567d 1// SPDX-License-Identifier: GPL-2.0
1da177e4 2/*
0fe23479 3 * Copyright (C) 2001 Jens Axboe <axboe@kernel.dk>
1da177e4
LT
4 */
5#include <linux/mm.h>
6#include <linux/swap.h>
7#include <linux/bio.h>
8#include <linux/blkdev.h>
a27bb332 9#include <linux/uio.h>
852c788f 10#include <linux/iocontext.h>
1da177e4
LT
11#include <linux/slab.h>
12#include <linux/init.h>
13#include <linux/kernel.h>
630d9c47 14#include <linux/export.h>
1da177e4
LT
15#include <linux/mempool.h>
16#include <linux/workqueue.h>
852c788f 17#include <linux/cgroup.h>
08e18eab 18#include <linux/blk-cgroup.h>
b4c5875d 19#include <linux/highmem.h>
de6a78b6 20#include <linux/sched/sysctl.h>
a892c8d5 21#include <linux/blk-crypto.h>
49d1ec85 22#include <linux/xarray.h>
1da177e4 23
55782138 24#include <trace/events/block.h>
9e234eea 25#include "blk.h"
67b42d0b 26#include "blk-rq-qos.h"
0bfc2455 27
6ac0b715
CH
28struct biovec_slab {
29 int nr_vecs;
30 char *name;
31 struct kmem_cache *slab;
32};
33
1da177e4
LT
34/*
35 * if you change this list, also change bvec_alloc or things will
36 * break badly! cannot be bigger than what you can fit into an
37 * unsigned short
38 */
bd5c4fac 39#define BV(x, n) { .nr_vecs = x, .name = "biovec-"#n }
ed996a52 40static struct biovec_slab bvec_slabs[BVEC_POOL_NR] __read_mostly = {
bd5c4fac 41 BV(1, 1), BV(4, 4), BV(16, 16), BV(64, 64), BV(128, 128), BV(BIO_MAX_PAGES, max),
1da177e4
LT
42};
43#undef BV
44
1da177e4
LT
45/*
46 * fs_bio_set is the bio_set containing bio and iovec memory pools used by
47 * IO code that does not need private memory pools.
48 */
f4f8154a 49struct bio_set fs_bio_set;
3f86a82a 50EXPORT_SYMBOL(fs_bio_set);
1da177e4 51
bb799ca0
JA
52/*
53 * Our slab pool management
54 */
55struct bio_slab {
56 struct kmem_cache *slab;
57 unsigned int slab_ref;
58 unsigned int slab_size;
59 char name[8];
60};
61static DEFINE_MUTEX(bio_slab_lock);
49d1ec85 62static DEFINE_XARRAY(bio_slabs);
bb799ca0 63
49d1ec85 64static struct bio_slab *create_bio_slab(unsigned int size)
bb799ca0 65{
49d1ec85 66 struct bio_slab *bslab = kzalloc(sizeof(*bslab), GFP_KERNEL);
bb799ca0 67
49d1ec85
ML
68 if (!bslab)
69 return NULL;
bb799ca0 70
49d1ec85
ML
71 snprintf(bslab->name, sizeof(bslab->name), "bio-%d", size);
72 bslab->slab = kmem_cache_create(bslab->name, size,
73 ARCH_KMALLOC_MINALIGN, SLAB_HWCACHE_ALIGN, NULL);
74 if (!bslab->slab)
75 goto fail_alloc_slab;
bb799ca0 76
49d1ec85
ML
77 bslab->slab_ref = 1;
78 bslab->slab_size = size;
bb799ca0 79
49d1ec85
ML
80 if (!xa_err(xa_store(&bio_slabs, size, bslab, GFP_KERNEL)))
81 return bslab;
bb799ca0 82
49d1ec85 83 kmem_cache_destroy(bslab->slab);
bb799ca0 84
49d1ec85
ML
85fail_alloc_slab:
86 kfree(bslab);
87 return NULL;
88}
bb799ca0 89
49d1ec85
ML
90static inline unsigned int bs_bio_slab_size(struct bio_set *bs)
91{
9f180e31 92 return bs->front_pad + sizeof(struct bio) + bs->back_pad;
49d1ec85
ML
93}
94
95static struct kmem_cache *bio_find_or_create_slab(struct bio_set *bs)
96{
97 unsigned int size = bs_bio_slab_size(bs);
98 struct bio_slab *bslab;
99
100 mutex_lock(&bio_slab_lock);
101 bslab = xa_load(&bio_slabs, size);
102 if (bslab)
103 bslab->slab_ref++;
104 else
105 bslab = create_bio_slab(size);
bb799ca0 106 mutex_unlock(&bio_slab_lock);
49d1ec85
ML
107
108 if (bslab)
109 return bslab->slab;
110 return NULL;
bb799ca0
JA
111}
112
113static void bio_put_slab(struct bio_set *bs)
114{
115 struct bio_slab *bslab = NULL;
49d1ec85 116 unsigned int slab_size = bs_bio_slab_size(bs);
bb799ca0
JA
117
118 mutex_lock(&bio_slab_lock);
119
49d1ec85 120 bslab = xa_load(&bio_slabs, slab_size);
bb799ca0
JA
121 if (WARN(!bslab, KERN_ERR "bio: unable to find slab!\n"))
122 goto out;
123
49d1ec85
ML
124 WARN_ON_ONCE(bslab->slab != bs->bio_slab);
125
bb799ca0
JA
126 WARN_ON(!bslab->slab_ref);
127
128 if (--bslab->slab_ref)
129 goto out;
130
49d1ec85
ML
131 xa_erase(&bio_slabs, slab_size);
132
bb799ca0 133 kmem_cache_destroy(bslab->slab);
49d1ec85 134 kfree(bslab);
bb799ca0
JA
135
136out:
137 mutex_unlock(&bio_slab_lock);
138}
139
7ba1ba12
MP
140unsigned int bvec_nr_vecs(unsigned short idx)
141{
d6c02a9b 142 return bvec_slabs[--idx].nr_vecs;
7ba1ba12
MP
143}
144
9f060e22 145void bvec_free(mempool_t *pool, struct bio_vec *bv, unsigned int idx)
bb799ca0 146{
ed996a52
CH
147 if (!idx)
148 return;
149 idx--;
150
151 BIO_BUG_ON(idx >= BVEC_POOL_NR);
bb799ca0 152
ed996a52 153 if (idx == BVEC_POOL_MAX) {
9f060e22 154 mempool_free(bv, pool);
ed996a52 155 } else {
bb799ca0
JA
156 struct biovec_slab *bvs = bvec_slabs + idx;
157
158 kmem_cache_free(bvs->slab, bv);
159 }
160}
161
f2c3eb9b
CH
162/*
163 * Make the first allocation restricted and don't dump info on allocation
164 * failures, since we'll fall back to the mempool in case of failure.
165 */
166static inline gfp_t bvec_alloc_gfp(gfp_t gfp)
167{
168 return (gfp & ~(__GFP_DIRECT_RECLAIM | __GFP_IO)) |
169 __GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN;
170}
171
9f060e22
KO
172struct bio_vec *bvec_alloc(gfp_t gfp_mask, int nr, unsigned long *idx,
173 mempool_t *pool)
1da177e4
LT
174{
175 struct bio_vec *bvl;
1da177e4 176
7ff9345f
JA
177 /*
178 * see comment near bvec_array define!
179 */
180 switch (nr) {
181 case 1:
182 *idx = 0;
183 break;
184 case 2 ... 4:
185 *idx = 1;
186 break;
187 case 5 ... 16:
188 *idx = 2;
189 break;
190 case 17 ... 64:
191 *idx = 3;
192 break;
193 case 65 ... 128:
194 *idx = 4;
195 break;
196 case 129 ... BIO_MAX_PAGES:
197 *idx = 5;
198 break;
199 default:
200 return NULL;
201 }
202
203 /*
204 * idx now points to the pool we want to allocate from. only the
205 * 1-vec entry pool is mempool backed.
206 */
ed996a52 207 if (*idx == BVEC_POOL_MAX) {
7ff9345f 208fallback:
9f060e22 209 bvl = mempool_alloc(pool, gfp_mask);
7ff9345f
JA
210 } else {
211 struct biovec_slab *bvs = bvec_slabs + *idx;
1da177e4 212
0a0d96b0 213 /*
d0164adc 214 * Try a slab allocation. If this fails and __GFP_DIRECT_RECLAIM
7ff9345f 215 * is set, retry with the 1-entry mempool
0a0d96b0 216 */
f2c3eb9b 217 bvl = kmem_cache_alloc(bvs->slab, bvec_alloc_gfp(gfp_mask));
d0164adc 218 if (unlikely(!bvl && (gfp_mask & __GFP_DIRECT_RECLAIM))) {
ed996a52 219 *idx = BVEC_POOL_MAX;
7ff9345f
JA
220 goto fallback;
221 }
222 }
223
ed996a52 224 (*idx)++;
1da177e4
LT
225 return bvl;
226}
227
9ae3b3f5 228void bio_uninit(struct bio *bio)
1da177e4 229{
db9819c7
CH
230#ifdef CONFIG_BLK_CGROUP
231 if (bio->bi_blkg) {
232 blkg_put(bio->bi_blkg);
233 bio->bi_blkg = NULL;
234 }
235#endif
ece841ab
JT
236 if (bio_integrity(bio))
237 bio_integrity_free(bio);
a892c8d5
ST
238
239 bio_crypt_free_ctx(bio);
4254bba1 240}
9ae3b3f5 241EXPORT_SYMBOL(bio_uninit);
7ba1ba12 242
4254bba1
KO
243static void bio_free(struct bio *bio)
244{
245 struct bio_set *bs = bio->bi_pool;
246 void *p;
247
9ae3b3f5 248 bio_uninit(bio);
4254bba1
KO
249
250 if (bs) {
8aa6ba2f 251 bvec_free(&bs->bvec_pool, bio->bi_io_vec, BVEC_POOL_IDX(bio));
4254bba1
KO
252
253 /*
254 * If we have front padding, adjust the bio pointer before freeing
255 */
256 p = bio;
bb799ca0
JA
257 p -= bs->front_pad;
258
8aa6ba2f 259 mempool_free(p, &bs->bio_pool);
4254bba1
KO
260 } else {
261 /* Bio was allocated by bio_kmalloc() */
262 kfree(bio);
263 }
3676347a
PO
264}
265
9ae3b3f5
JA
266/*
267 * Users of this function have their own bio allocation. Subsequently,
268 * they must remember to pair any call to bio_init() with bio_uninit()
269 * when IO has completed, or when the bio is released.
270 */
3a83f467
ML
271void bio_init(struct bio *bio, struct bio_vec *table,
272 unsigned short max_vecs)
1da177e4 273{
2b94de55 274 memset(bio, 0, sizeof(*bio));
c4cf5261 275 atomic_set(&bio->__bi_remaining, 1);
dac56212 276 atomic_set(&bio->__bi_cnt, 1);
3a83f467
ML
277
278 bio->bi_io_vec = table;
279 bio->bi_max_vecs = max_vecs;
1da177e4 280}
a112a71d 281EXPORT_SYMBOL(bio_init);
1da177e4 282
f44b48c7
KO
283/**
284 * bio_reset - reinitialize a bio
285 * @bio: bio to reset
286 *
287 * Description:
288 * After calling bio_reset(), @bio will be in the same state as a freshly
289 * allocated bio returned bio bio_alloc_bioset() - the only fields that are
290 * preserved are the ones that are initialized by bio_alloc_bioset(). See
291 * comment in struct bio.
292 */
293void bio_reset(struct bio *bio)
294{
295 unsigned long flags = bio->bi_flags & (~0UL << BIO_RESET_BITS);
296
9ae3b3f5 297 bio_uninit(bio);
f44b48c7
KO
298
299 memset(bio, 0, BIO_RESET_BYTES);
4246a0b6 300 bio->bi_flags = flags;
c4cf5261 301 atomic_set(&bio->__bi_remaining, 1);
f44b48c7
KO
302}
303EXPORT_SYMBOL(bio_reset);
304
38f8baae 305static struct bio *__bio_chain_endio(struct bio *bio)
196d38bc 306{
4246a0b6
CH
307 struct bio *parent = bio->bi_private;
308
4e4cbee9
CH
309 if (!parent->bi_status)
310 parent->bi_status = bio->bi_status;
196d38bc 311 bio_put(bio);
38f8baae
CH
312 return parent;
313}
314
315static void bio_chain_endio(struct bio *bio)
316{
317 bio_endio(__bio_chain_endio(bio));
196d38bc
KO
318}
319
320/**
321 * bio_chain - chain bio completions
1051a902 322 * @bio: the target bio
5b874af6 323 * @parent: the parent bio of @bio
196d38bc
KO
324 *
325 * The caller won't have a bi_end_io called when @bio completes - instead,
326 * @parent's bi_end_io won't be called until both @parent and @bio have
327 * completed; the chained bio will also be freed when it completes.
328 *
329 * The caller must not set bi_private or bi_end_io in @bio.
330 */
331void bio_chain(struct bio *bio, struct bio *parent)
332{
333 BUG_ON(bio->bi_private || bio->bi_end_io);
334
335 bio->bi_private = parent;
336 bio->bi_end_io = bio_chain_endio;
c4cf5261 337 bio_inc_remaining(parent);
196d38bc
KO
338}
339EXPORT_SYMBOL(bio_chain);
340
df2cb6da
KO
341static void bio_alloc_rescue(struct work_struct *work)
342{
343 struct bio_set *bs = container_of(work, struct bio_set, rescue_work);
344 struct bio *bio;
345
346 while (1) {
347 spin_lock(&bs->rescue_lock);
348 bio = bio_list_pop(&bs->rescue_list);
349 spin_unlock(&bs->rescue_lock);
350
351 if (!bio)
352 break;
353
ed00aabd 354 submit_bio_noacct(bio);
df2cb6da
KO
355 }
356}
357
358static void punt_bios_to_rescuer(struct bio_set *bs)
359{
360 struct bio_list punt, nopunt;
361 struct bio *bio;
362
47e0fb46
N
363 if (WARN_ON_ONCE(!bs->rescue_workqueue))
364 return;
df2cb6da
KO
365 /*
366 * In order to guarantee forward progress we must punt only bios that
367 * were allocated from this bio_set; otherwise, if there was a bio on
368 * there for a stacking driver higher up in the stack, processing it
369 * could require allocating bios from this bio_set, and doing that from
370 * our own rescuer would be bad.
371 *
372 * Since bio lists are singly linked, pop them all instead of trying to
373 * remove from the middle of the list:
374 */
375
376 bio_list_init(&punt);
377 bio_list_init(&nopunt);
378
f5fe1b51 379 while ((bio = bio_list_pop(&current->bio_list[0])))
df2cb6da 380 bio_list_add(bio->bi_pool == bs ? &punt : &nopunt, bio);
f5fe1b51 381 current->bio_list[0] = nopunt;
df2cb6da 382
f5fe1b51
N
383 bio_list_init(&nopunt);
384 while ((bio = bio_list_pop(&current->bio_list[1])))
385 bio_list_add(bio->bi_pool == bs ? &punt : &nopunt, bio);
386 current->bio_list[1] = nopunt;
df2cb6da
KO
387
388 spin_lock(&bs->rescue_lock);
389 bio_list_merge(&bs->rescue_list, &punt);
390 spin_unlock(&bs->rescue_lock);
391
392 queue_work(bs->rescue_workqueue, &bs->rescue_work);
393}
394
1da177e4
LT
395/**
396 * bio_alloc_bioset - allocate a bio for I/O
519c8e9f 397 * @gfp_mask: the GFP_* mask given to the slab allocator
1da177e4 398 * @nr_iovecs: number of iovecs to pre-allocate
db18efac 399 * @bs: the bio_set to allocate from.
1da177e4 400 *
3175199a 401 * Allocate a bio from the mempools in @bs.
3f86a82a 402 *
3175199a
CH
403 * If %__GFP_DIRECT_RECLAIM is set then bio_alloc will always be able to
404 * allocate a bio. This is due to the mempool guarantees. To make this work,
405 * callers must never allocate more than 1 bio at a time from the general pool.
406 * Callers that need to allocate more than 1 bio must always submit the
407 * previously allocated bio for IO before attempting to allocate a new one.
408 * Failure to do so can cause deadlocks under memory pressure.
3f86a82a 409 *
3175199a
CH
410 * Note that when running under submit_bio_noacct() (i.e. any block driver),
411 * bios are not submitted until after you return - see the code in
412 * submit_bio_noacct() that converts recursion into iteration, to prevent
413 * stack overflows.
df2cb6da 414 *
3175199a
CH
415 * This would normally mean allocating multiple bios under submit_bio_noacct()
416 * would be susceptible to deadlocks, but we have
417 * deadlock avoidance code that resubmits any blocked bios from a rescuer
418 * thread.
df2cb6da 419 *
3175199a
CH
420 * However, we do not guarantee forward progress for allocations from other
421 * mempools. Doing multiple allocations from the same mempool under
422 * submit_bio_noacct() should be avoided - instead, use bio_set's front_pad
423 * for per bio allocations.
df2cb6da 424 *
3175199a 425 * Returns: Pointer to new bio on success, NULL on failure.
3f86a82a 426 */
7a88fa19
DC
427struct bio *bio_alloc_bioset(gfp_t gfp_mask, unsigned int nr_iovecs,
428 struct bio_set *bs)
1da177e4 429{
df2cb6da 430 gfp_t saved_gfp = gfp_mask;
451a9ebf
TH
431 struct bio *bio;
432 void *p;
433
3175199a
CH
434 /* should not use nobvec bioset for nr_iovecs > 0 */
435 if (WARN_ON_ONCE(!mempool_initialized(&bs->bvec_pool) && nr_iovecs > 0))
436 return NULL;
df2cb6da 437
3175199a
CH
438 /*
439 * submit_bio_noacct() converts recursion to iteration; this means if
440 * we're running beneath it, any bios we allocate and submit will not be
441 * submitted (and thus freed) until after we return.
442 *
443 * This exposes us to a potential deadlock if we allocate multiple bios
444 * from the same bio_set() while running underneath submit_bio_noacct().
445 * If we were to allocate multiple bios (say a stacking block driver
446 * that was splitting bios), we would deadlock if we exhausted the
447 * mempool's reserve.
448 *
449 * We solve this, and guarantee forward progress, with a rescuer
450 * workqueue per bio_set. If we go to allocate and there are bios on
451 * current->bio_list, we first try the allocation without
452 * __GFP_DIRECT_RECLAIM; if that fails, we punt those bios we would be
453 * blocking to the rescuer workqueue before we retry with the original
454 * gfp_flags.
455 */
456 if (current->bio_list &&
457 (!bio_list_empty(&current->bio_list[0]) ||
458 !bio_list_empty(&current->bio_list[1])) &&
459 bs->rescue_workqueue)
460 gfp_mask &= ~__GFP_DIRECT_RECLAIM;
461
462 p = mempool_alloc(&bs->bio_pool, gfp_mask);
463 if (!p && gfp_mask != saved_gfp) {
464 punt_bios_to_rescuer(bs);
465 gfp_mask = saved_gfp;
8aa6ba2f 466 p = mempool_alloc(&bs->bio_pool, gfp_mask);
3f86a82a 467 }
451a9ebf
TH
468 if (unlikely(!p))
469 return NULL;
1da177e4 470
3175199a
CH
471 bio = p + bs->front_pad;
472 if (nr_iovecs > BIO_INLINE_VECS) {
ed996a52 473 unsigned long idx = 0;
3175199a 474 struct bio_vec *bvl = NULL;
ed996a52 475
8aa6ba2f 476 bvl = bvec_alloc(gfp_mask, nr_iovecs, &idx, &bs->bvec_pool);
df2cb6da
KO
477 if (!bvl && gfp_mask != saved_gfp) {
478 punt_bios_to_rescuer(bs);
479 gfp_mask = saved_gfp;
3175199a
CH
480 bvl = bvec_alloc(gfp_mask, nr_iovecs, &idx,
481 &bs->bvec_pool);
df2cb6da
KO
482 }
483
34053979
IM
484 if (unlikely(!bvl))
485 goto err_free;
a38352e0 486
3175199a 487 bio_init(bio, bvl, bvec_nr_vecs(idx));
8358c28a 488 bio->bi_flags |= idx << BVEC_POOL_OFFSET;
3f86a82a 489 } else if (nr_iovecs) {
3175199a
CH
490 bio_init(bio, bio->bi_inline_vecs, BIO_INLINE_VECS);
491 } else {
492 bio_init(bio, NULL, 0);
1da177e4 493 }
3f86a82a
KO
494
495 bio->bi_pool = bs;
1da177e4 496 return bio;
34053979
IM
497
498err_free:
8aa6ba2f 499 mempool_free(p, &bs->bio_pool);
34053979 500 return NULL;
1da177e4 501}
a112a71d 502EXPORT_SYMBOL(bio_alloc_bioset);
1da177e4 503
3175199a
CH
504/**
505 * bio_kmalloc - kmalloc a bio for I/O
506 * @gfp_mask: the GFP_* mask given to the slab allocator
507 * @nr_iovecs: number of iovecs to pre-allocate
508 *
509 * Use kmalloc to allocate and initialize a bio.
510 *
511 * Returns: Pointer to new bio on success, NULL on failure.
512 */
513struct bio *bio_kmalloc(gfp_t gfp_mask, unsigned int nr_iovecs)
514{
515 struct bio *bio;
516
517 if (nr_iovecs > UIO_MAXIOV)
518 return NULL;
519
520 bio = kmalloc(struct_size(bio, bi_inline_vecs, nr_iovecs), gfp_mask);
521 if (unlikely(!bio))
522 return NULL;
523 bio_init(bio, nr_iovecs ? bio->bi_inline_vecs : NULL, nr_iovecs);
524 bio->bi_pool = NULL;
525 return bio;
526}
527EXPORT_SYMBOL(bio_kmalloc);
528
38a72dac 529void zero_fill_bio_iter(struct bio *bio, struct bvec_iter start)
1da177e4
LT
530{
531 unsigned long flags;
7988613b
KO
532 struct bio_vec bv;
533 struct bvec_iter iter;
1da177e4 534
38a72dac 535 __bio_for_each_segment(bv, bio, iter, start) {
7988613b
KO
536 char *data = bvec_kmap_irq(&bv, &flags);
537 memset(data, 0, bv.bv_len);
538 flush_dcache_page(bv.bv_page);
1da177e4
LT
539 bvec_kunmap_irq(data, &flags);
540 }
541}
38a72dac 542EXPORT_SYMBOL(zero_fill_bio_iter);
1da177e4 543
83c9c547
ML
544/**
545 * bio_truncate - truncate the bio to small size of @new_size
546 * @bio: the bio to be truncated
547 * @new_size: new size for truncating the bio
548 *
549 * Description:
550 * Truncate the bio to new size of @new_size. If bio_op(bio) is
551 * REQ_OP_READ, zero the truncated part. This function should only
552 * be used for handling corner cases, such as bio eod.
553 */
85a8ce62
ML
554void bio_truncate(struct bio *bio, unsigned new_size)
555{
556 struct bio_vec bv;
557 struct bvec_iter iter;
558 unsigned int done = 0;
559 bool truncated = false;
560
561 if (new_size >= bio->bi_iter.bi_size)
562 return;
563
83c9c547 564 if (bio_op(bio) != REQ_OP_READ)
85a8ce62
ML
565 goto exit;
566
567 bio_for_each_segment(bv, bio, iter) {
568 if (done + bv.bv_len > new_size) {
569 unsigned offset;
570
571 if (!truncated)
572 offset = new_size - done;
573 else
574 offset = 0;
575 zero_user(bv.bv_page, offset, bv.bv_len - offset);
576 truncated = true;
577 }
578 done += bv.bv_len;
579 }
580
581 exit:
582 /*
583 * Don't touch bvec table here and make it really immutable, since
584 * fs bio user has to retrieve all pages via bio_for_each_segment_all
585 * in its .end_bio() callback.
586 *
587 * It is enough to truncate bio by updating .bi_size since we can make
588 * correct bvec with the updated .bi_size for drivers.
589 */
590 bio->bi_iter.bi_size = new_size;
591}
592
29125ed6
CH
593/**
594 * guard_bio_eod - truncate a BIO to fit the block device
595 * @bio: bio to truncate
596 *
597 * This allows us to do IO even on the odd last sectors of a device, even if the
598 * block size is some multiple of the physical sector size.
599 *
600 * We'll just truncate the bio to the size of the device, and clear the end of
601 * the buffer head manually. Truly out-of-range accesses will turn into actual
602 * I/O errors, this only handles the "we need to be able to do I/O at the final
603 * sector" case.
604 */
605void guard_bio_eod(struct bio *bio)
606{
309dca30 607 sector_t maxsector = bdev_nr_sectors(bio->bi_bdev);
29125ed6
CH
608
609 if (!maxsector)
610 return;
611
612 /*
613 * If the *whole* IO is past the end of the device,
614 * let it through, and the IO layer will turn it into
615 * an EIO.
616 */
617 if (unlikely(bio->bi_iter.bi_sector >= maxsector))
618 return;
619
620 maxsector -= bio->bi_iter.bi_sector;
621 if (likely((bio->bi_iter.bi_size >> 9) <= maxsector))
622 return;
623
624 bio_truncate(bio, maxsector << 9);
625}
626
1da177e4
LT
627/**
628 * bio_put - release a reference to a bio
629 * @bio: bio to release reference to
630 *
631 * Description:
632 * Put a reference to a &struct bio, either one you have gotten with
9b10f6a9 633 * bio_alloc, bio_get or bio_clone_*. The last put of a bio will free it.
1da177e4
LT
634 **/
635void bio_put(struct bio *bio)
636{
dac56212 637 if (!bio_flagged(bio, BIO_REFFED))
4254bba1 638 bio_free(bio);
dac56212
JA
639 else {
640 BIO_BUG_ON(!atomic_read(&bio->__bi_cnt));
641
642 /*
643 * last put frees it
644 */
645 if (atomic_dec_and_test(&bio->__bi_cnt))
646 bio_free(bio);
647 }
1da177e4 648}
a112a71d 649EXPORT_SYMBOL(bio_put);
1da177e4 650
59d276fe
KO
651/**
652 * __bio_clone_fast - clone a bio that shares the original bio's biovec
653 * @bio: destination bio
654 * @bio_src: bio to clone
655 *
656 * Clone a &bio. Caller will own the returned bio, but not
657 * the actual data it points to. Reference count of returned
658 * bio will be one.
659 *
660 * Caller must ensure that @bio_src is not freed before @bio.
661 */
662void __bio_clone_fast(struct bio *bio, struct bio *bio_src)
663{
ed996a52 664 BUG_ON(bio->bi_pool && BVEC_POOL_IDX(bio));
59d276fe
KO
665
666 /*
309dca30 667 * most users will be overriding ->bi_bdev with a new target,
59d276fe
KO
668 * so we don't set nor calculate new physical/hw segment counts here
669 */
309dca30 670 bio->bi_bdev = bio_src->bi_bdev;
b7c44ed9 671 bio_set_flag(bio, BIO_CLONED);
111be883
SL
672 if (bio_flagged(bio_src, BIO_THROTTLED))
673 bio_set_flag(bio, BIO_THROTTLED);
46bbf653
CH
674 if (bio_flagged(bio_src, BIO_REMAPPED))
675 bio_set_flag(bio, BIO_REMAPPED);
1eff9d32 676 bio->bi_opf = bio_src->bi_opf;
ca474b73 677 bio->bi_ioprio = bio_src->bi_ioprio;
cb6934f8 678 bio->bi_write_hint = bio_src->bi_write_hint;
59d276fe
KO
679 bio->bi_iter = bio_src->bi_iter;
680 bio->bi_io_vec = bio_src->bi_io_vec;
20bd723e 681
db6638d7 682 bio_clone_blkg_association(bio, bio_src);
e439bedf 683 blkcg_bio_issue_init(bio);
59d276fe
KO
684}
685EXPORT_SYMBOL(__bio_clone_fast);
686
687/**
688 * bio_clone_fast - clone a bio that shares the original bio's biovec
689 * @bio: bio to clone
690 * @gfp_mask: allocation priority
691 * @bs: bio_set to allocate from
692 *
693 * Like __bio_clone_fast, only also allocates the returned bio
694 */
695struct bio *bio_clone_fast(struct bio *bio, gfp_t gfp_mask, struct bio_set *bs)
696{
697 struct bio *b;
698
699 b = bio_alloc_bioset(gfp_mask, 0, bs);
700 if (!b)
701 return NULL;
702
703 __bio_clone_fast(b, bio);
704
07560151
EB
705 if (bio_crypt_clone(b, bio, gfp_mask) < 0)
706 goto err_put;
a892c8d5 707
07560151
EB
708 if (bio_integrity(bio) &&
709 bio_integrity_clone(b, bio, gfp_mask) < 0)
710 goto err_put;
59d276fe
KO
711
712 return b;
07560151
EB
713
714err_put:
715 bio_put(b);
716 return NULL;
59d276fe
KO
717}
718EXPORT_SYMBOL(bio_clone_fast);
719
5cbd28e3
CH
720const char *bio_devname(struct bio *bio, char *buf)
721{
309dca30 722 return bdevname(bio->bi_bdev, buf);
5cbd28e3
CH
723}
724EXPORT_SYMBOL(bio_devname);
725
5919482e
ML
726static inline bool page_is_mergeable(const struct bio_vec *bv,
727 struct page *page, unsigned int len, unsigned int off,
ff896738 728 bool *same_page)
5919482e 729{
d8166519
MWO
730 size_t bv_end = bv->bv_offset + bv->bv_len;
731 phys_addr_t vec_end_addr = page_to_phys(bv->bv_page) + bv_end - 1;
5919482e
ML
732 phys_addr_t page_addr = page_to_phys(page);
733
734 if (vec_end_addr + 1 != page_addr + off)
735 return false;
736 if (xen_domain() && !xen_biovec_phys_mergeable(bv, page))
737 return false;
52d52d1c 738
ff896738 739 *same_page = ((vec_end_addr & PAGE_MASK) == page_addr);
d8166519
MWO
740 if (*same_page)
741 return true;
742 return (bv->bv_page + bv_end / PAGE_SIZE) == (page + off / PAGE_SIZE);
5919482e
ML
743}
744
e4581105
CH
745/*
746 * Try to merge a page into a segment, while obeying the hardware segment
747 * size limit. This is not for normal read/write bios, but for passthrough
748 * or Zone Append operations that we can't split.
749 */
750static bool bio_try_merge_hw_seg(struct request_queue *q, struct bio *bio,
751 struct page *page, unsigned len,
752 unsigned offset, bool *same_page)
489fbbcb 753{
384209cd 754 struct bio_vec *bv = &bio->bi_io_vec[bio->bi_vcnt - 1];
489fbbcb
ML
755 unsigned long mask = queue_segment_boundary(q);
756 phys_addr_t addr1 = page_to_phys(bv->bv_page) + bv->bv_offset;
757 phys_addr_t addr2 = page_to_phys(page) + offset + len - 1;
758
759 if ((addr1 | mask) != (addr2 | mask))
760 return false;
489fbbcb
ML
761 if (bv->bv_len + len > queue_max_segment_size(q))
762 return false;
384209cd 763 return __bio_try_merge_page(bio, page, len, offset, same_page);
489fbbcb
ML
764}
765
1da177e4 766/**
e4581105
CH
767 * bio_add_hw_page - attempt to add a page to a bio with hw constraints
768 * @q: the target queue
769 * @bio: destination bio
770 * @page: page to add
771 * @len: vec entry length
772 * @offset: vec entry offset
773 * @max_sectors: maximum number of sectors that can be added
774 * @same_page: return if the segment has been merged inside the same page
c66a14d0 775 *
e4581105
CH
776 * Add a page to a bio while respecting the hardware max_sectors, max_segment
777 * and gap limitations.
1da177e4 778 */
e4581105 779int bio_add_hw_page(struct request_queue *q, struct bio *bio,
19047087 780 struct page *page, unsigned int len, unsigned int offset,
e4581105 781 unsigned int max_sectors, bool *same_page)
1da177e4 782{
1da177e4
LT
783 struct bio_vec *bvec;
784
e4581105 785 if (WARN_ON_ONCE(bio_flagged(bio, BIO_CLONED)))
1da177e4
LT
786 return 0;
787
e4581105 788 if (((bio->bi_iter.bi_size + len) >> 9) > max_sectors)
1da177e4
LT
789 return 0;
790
80cfd548 791 if (bio->bi_vcnt > 0) {
e4581105 792 if (bio_try_merge_hw_seg(q, bio, page, len, offset, same_page))
384209cd 793 return len;
320ea869
CH
794
795 /*
796 * If the queue doesn't support SG gaps and adding this segment
797 * would create a gap, disallow it.
798 */
384209cd 799 bvec = &bio->bi_io_vec[bio->bi_vcnt - 1];
320ea869
CH
800 if (bvec_gap_to_prev(q, bvec, offset))
801 return 0;
80cfd548
JA
802 }
803
79d08f89 804 if (bio_full(bio, len))
1da177e4
LT
805 return 0;
806
14ccb66b 807 if (bio->bi_vcnt >= queue_max_segments(q))
489fbbcb
ML
808 return 0;
809
fcbf6a08
ML
810 bvec = &bio->bi_io_vec[bio->bi_vcnt];
811 bvec->bv_page = page;
812 bvec->bv_len = len;
813 bvec->bv_offset = offset;
814 bio->bi_vcnt++;
dcdca753 815 bio->bi_iter.bi_size += len;
1da177e4
LT
816 return len;
817}
19047087 818
e4581105
CH
819/**
820 * bio_add_pc_page - attempt to add page to passthrough bio
821 * @q: the target queue
822 * @bio: destination bio
823 * @page: page to add
824 * @len: vec entry length
825 * @offset: vec entry offset
826 *
827 * Attempt to add a page to the bio_vec maplist. This can fail for a
828 * number of reasons, such as the bio being full or target block device
829 * limitations. The target block device must allow bio's up to PAGE_SIZE,
830 * so it is always possible to add a single page to an empty bio.
831 *
832 * This should only be used by passthrough bios.
833 */
19047087
ML
834int bio_add_pc_page(struct request_queue *q, struct bio *bio,
835 struct page *page, unsigned int len, unsigned int offset)
836{
d1916c86 837 bool same_page = false;
e4581105
CH
838 return bio_add_hw_page(q, bio, page, len, offset,
839 queue_max_hw_sectors(q), &same_page);
19047087 840}
a112a71d 841EXPORT_SYMBOL(bio_add_pc_page);
6e68af66 842
1da177e4 843/**
0aa69fd3
CH
844 * __bio_try_merge_page - try appending data to an existing bvec.
845 * @bio: destination bio
551879a4 846 * @page: start page to add
0aa69fd3 847 * @len: length of the data to add
551879a4 848 * @off: offset of the data relative to @page
ff896738 849 * @same_page: return if the segment has been merged inside the same page
1da177e4 850 *
0aa69fd3 851 * Try to add the data at @page + @off to the last bvec of @bio. This is a
3cf14889 852 * useful optimisation for file systems with a block size smaller than the
0aa69fd3
CH
853 * page size.
854 *
551879a4
ML
855 * Warn if (@len, @off) crosses pages in case that @same_page is true.
856 *
0aa69fd3 857 * Return %true on success or %false on failure.
1da177e4 858 */
0aa69fd3 859bool __bio_try_merge_page(struct bio *bio, struct page *page,
ff896738 860 unsigned int len, unsigned int off, bool *same_page)
1da177e4 861{
c66a14d0 862 if (WARN_ON_ONCE(bio_flagged(bio, BIO_CLONED)))
0aa69fd3 863 return false;
762380ad 864
cc90bc68 865 if (bio->bi_vcnt > 0) {
0aa69fd3 866 struct bio_vec *bv = &bio->bi_io_vec[bio->bi_vcnt - 1];
5919482e
ML
867
868 if (page_is_mergeable(bv, page, len, off, same_page)) {
2cd896a5
RH
869 if (bio->bi_iter.bi_size > UINT_MAX - len) {
870 *same_page = false;
cc90bc68 871 return false;
2cd896a5 872 }
5919482e
ML
873 bv->bv_len += len;
874 bio->bi_iter.bi_size += len;
875 return true;
876 }
c66a14d0 877 }
0aa69fd3
CH
878 return false;
879}
880EXPORT_SYMBOL_GPL(__bio_try_merge_page);
c66a14d0 881
0aa69fd3 882/**
551879a4 883 * __bio_add_page - add page(s) to a bio in a new segment
0aa69fd3 884 * @bio: destination bio
551879a4
ML
885 * @page: start page to add
886 * @len: length of the data to add, may cross pages
887 * @off: offset of the data relative to @page, may cross pages
0aa69fd3
CH
888 *
889 * Add the data at @page + @off to @bio as a new bvec. The caller must ensure
890 * that @bio has space for another bvec.
891 */
892void __bio_add_page(struct bio *bio, struct page *page,
893 unsigned int len, unsigned int off)
894{
895 struct bio_vec *bv = &bio->bi_io_vec[bio->bi_vcnt];
c66a14d0 896
0aa69fd3 897 WARN_ON_ONCE(bio_flagged(bio, BIO_CLONED));
79d08f89 898 WARN_ON_ONCE(bio_full(bio, len));
0aa69fd3
CH
899
900 bv->bv_page = page;
901 bv->bv_offset = off;
902 bv->bv_len = len;
c66a14d0 903
c66a14d0 904 bio->bi_iter.bi_size += len;
0aa69fd3 905 bio->bi_vcnt++;
b8e24a93
JW
906
907 if (!bio_flagged(bio, BIO_WORKINGSET) && unlikely(PageWorkingset(page)))
908 bio_set_flag(bio, BIO_WORKINGSET);
0aa69fd3
CH
909}
910EXPORT_SYMBOL_GPL(__bio_add_page);
911
912/**
551879a4 913 * bio_add_page - attempt to add page(s) to bio
0aa69fd3 914 * @bio: destination bio
551879a4
ML
915 * @page: start page to add
916 * @len: vec entry length, may cross pages
917 * @offset: vec entry offset relative to @page, may cross pages
0aa69fd3 918 *
551879a4 919 * Attempt to add page(s) to the bio_vec maplist. This will only fail
0aa69fd3
CH
920 * if either bio->bi_vcnt == bio->bi_max_vecs or it's a cloned bio.
921 */
922int bio_add_page(struct bio *bio, struct page *page,
923 unsigned int len, unsigned int offset)
924{
ff896738
CH
925 bool same_page = false;
926
927 if (!__bio_try_merge_page(bio, page, len, offset, &same_page)) {
79d08f89 928 if (bio_full(bio, len))
0aa69fd3
CH
929 return 0;
930 __bio_add_page(bio, page, len, offset);
931 }
c66a14d0 932 return len;
1da177e4 933}
a112a71d 934EXPORT_SYMBOL(bio_add_page);
1da177e4 935
d241a95f 936void bio_release_pages(struct bio *bio, bool mark_dirty)
7321ecbf
CH
937{
938 struct bvec_iter_all iter_all;
939 struct bio_vec *bvec;
7321ecbf 940
b2d0d991
CH
941 if (bio_flagged(bio, BIO_NO_PAGE_REF))
942 return;
943
d241a95f
CH
944 bio_for_each_segment_all(bvec, bio, iter_all) {
945 if (mark_dirty && !PageCompound(bvec->bv_page))
946 set_page_dirty_lock(bvec->bv_page);
7321ecbf 947 put_page(bvec->bv_page);
d241a95f 948 }
7321ecbf 949}
29b2a3aa 950EXPORT_SYMBOL_GPL(bio_release_pages);
7321ecbf 951
c42bca92 952static int bio_iov_bvec_set(struct bio *bio, struct iov_iter *iter)
6d0c48ae 953{
c42bca92
PB
954 WARN_ON_ONCE(BVEC_POOL_IDX(bio) != 0);
955
956 bio->bi_vcnt = iter->nr_segs;
957 bio->bi_max_vecs = iter->nr_segs;
958 bio->bi_io_vec = (struct bio_vec *)iter->bvec;
959 bio->bi_iter.bi_bvec_done = iter->iov_offset;
960 bio->bi_iter.bi_size = iter->count;
961
962 iov_iter_advance(iter, iter->count);
a10584c3 963 return 0;
6d0c48ae
JA
964}
965
576ed913
CH
966#define PAGE_PTRS_PER_BVEC (sizeof(struct bio_vec) / sizeof(struct page *))
967
2cefe4db 968/**
17d51b10 969 * __bio_iov_iter_get_pages - pin user or kernel pages and add them to a bio
2cefe4db
KO
970 * @bio: bio to add pages to
971 * @iter: iov iterator describing the region to be mapped
972 *
17d51b10 973 * Pins pages from *iter and appends them to @bio's bvec array. The
2cefe4db 974 * pages will have to be released using put_page() when done.
17d51b10 975 * For multi-segment *iter, this function only adds pages from the
3cf14889 976 * next non-empty segment of the iov iterator.
2cefe4db 977 */
17d51b10 978static int __bio_iov_iter_get_pages(struct bio *bio, struct iov_iter *iter)
2cefe4db 979{
576ed913
CH
980 unsigned short nr_pages = bio->bi_max_vecs - bio->bi_vcnt;
981 unsigned short entries_left = bio->bi_max_vecs - bio->bi_vcnt;
2cefe4db
KO
982 struct bio_vec *bv = bio->bi_io_vec + bio->bi_vcnt;
983 struct page **pages = (struct page **)bv;
45691804 984 bool same_page = false;
576ed913
CH
985 ssize_t size, left;
986 unsigned len, i;
b403ea24 987 size_t offset;
576ed913
CH
988
989 /*
990 * Move page array up in the allocated memory for the bio vecs as far as
991 * possible so that we can start filling biovecs from the beginning
992 * without overwriting the temporary page array.
993 */
994 BUILD_BUG_ON(PAGE_PTRS_PER_BVEC < 2);
995 pages += entries_left * (PAGE_PTRS_PER_BVEC - 1);
2cefe4db
KO
996
997 size = iov_iter_get_pages(iter, pages, LONG_MAX, nr_pages, &offset);
998 if (unlikely(size <= 0))
999 return size ? size : -EFAULT;
2cefe4db 1000
576ed913
CH
1001 for (left = size, i = 0; left > 0; left -= len, i++) {
1002 struct page *page = pages[i];
2cefe4db 1003
576ed913 1004 len = min_t(size_t, PAGE_SIZE - offset, left);
45691804
CH
1005
1006 if (__bio_try_merge_page(bio, page, len, offset, &same_page)) {
1007 if (same_page)
1008 put_page(page);
1009 } else {
79d08f89 1010 if (WARN_ON_ONCE(bio_full(bio, len)))
45691804
CH
1011 return -EINVAL;
1012 __bio_add_page(bio, page, len, offset);
1013 }
576ed913 1014 offset = 0;
2cefe4db
KO
1015 }
1016
2cefe4db
KO
1017 iov_iter_advance(iter, size);
1018 return 0;
1019}
17d51b10 1020
0512a75b
KB
1021static int __bio_iov_append_get_pages(struct bio *bio, struct iov_iter *iter)
1022{
1023 unsigned short nr_pages = bio->bi_max_vecs - bio->bi_vcnt;
1024 unsigned short entries_left = bio->bi_max_vecs - bio->bi_vcnt;
309dca30 1025 struct request_queue *q = bio->bi_bdev->bd_disk->queue;
0512a75b
KB
1026 unsigned int max_append_sectors = queue_max_zone_append_sectors(q);
1027 struct bio_vec *bv = bio->bi_io_vec + bio->bi_vcnt;
1028 struct page **pages = (struct page **)bv;
1029 ssize_t size, left;
1030 unsigned len, i;
1031 size_t offset;
4977d121 1032 int ret = 0;
0512a75b
KB
1033
1034 if (WARN_ON_ONCE(!max_append_sectors))
1035 return 0;
1036
1037 /*
1038 * Move page array up in the allocated memory for the bio vecs as far as
1039 * possible so that we can start filling biovecs from the beginning
1040 * without overwriting the temporary page array.
1041 */
1042 BUILD_BUG_ON(PAGE_PTRS_PER_BVEC < 2);
1043 pages += entries_left * (PAGE_PTRS_PER_BVEC - 1);
1044
1045 size = iov_iter_get_pages(iter, pages, LONG_MAX, nr_pages, &offset);
1046 if (unlikely(size <= 0))
1047 return size ? size : -EFAULT;
1048
1049 for (left = size, i = 0; left > 0; left -= len, i++) {
1050 struct page *page = pages[i];
1051 bool same_page = false;
1052
1053 len = min_t(size_t, PAGE_SIZE - offset, left);
1054 if (bio_add_hw_page(q, bio, page, len, offset,
4977d121
NA
1055 max_append_sectors, &same_page) != len) {
1056 ret = -EINVAL;
1057 break;
1058 }
0512a75b
KB
1059 if (same_page)
1060 put_page(page);
1061 offset = 0;
1062 }
1063
4977d121
NA
1064 iov_iter_advance(iter, size - left);
1065 return ret;
0512a75b
KB
1066}
1067
17d51b10 1068/**
6d0c48ae 1069 * bio_iov_iter_get_pages - add user or kernel pages to a bio
17d51b10 1070 * @bio: bio to add pages to
6d0c48ae
JA
1071 * @iter: iov iterator describing the region to be added
1072 *
1073 * This takes either an iterator pointing to user memory, or one pointing to
1074 * kernel pages (BVEC iterator). If we're adding user pages, we pin them and
1075 * map them into the kernel. On IO completion, the caller should put those
c42bca92
PB
1076 * pages. For bvec based iterators bio_iov_iter_get_pages() uses the provided
1077 * bvecs rather than copying them. Hence anyone issuing kiocb based IO needs
1078 * to ensure the bvecs and pages stay referenced until the submitted I/O is
1079 * completed by a call to ->ki_complete() or returns with an error other than
1080 * -EIOCBQUEUED. The caller needs to check if the bio is flagged BIO_NO_PAGE_REF
1081 * on IO completion. If it isn't, then pages should be released.
17d51b10 1082 *
17d51b10 1083 * The function tries, but does not guarantee, to pin as many pages as
5cd3ddc1 1084 * fit into the bio, or are requested in @iter, whatever is smaller. If
6d0c48ae
JA
1085 * MM encounters an error pinning the requested pages, it stops. Error
1086 * is returned only if 0 pages could be pinned.
0cf41e5e
PB
1087 *
1088 * It's intended for direct IO, so doesn't do PSI tracking, the caller is
1089 * responsible for setting BIO_WORKINGSET if necessary.
17d51b10
MW
1090 */
1091int bio_iov_iter_get_pages(struct bio *bio, struct iov_iter *iter)
1092{
c42bca92 1093 int ret = 0;
17d51b10 1094
c42bca92
PB
1095 if (iov_iter_is_bvec(iter)) {
1096 if (WARN_ON_ONCE(bio_op(bio) == REQ_OP_ZONE_APPEND))
1097 return -EINVAL;
1098 bio_iov_bvec_set(bio, iter);
1099 bio_set_flag(bio, BIO_NO_PAGE_REF);
1100 return 0;
1101 } else {
1102 do {
1103 if (bio_op(bio) == REQ_OP_ZONE_APPEND)
1104 ret = __bio_iov_append_get_pages(bio, iter);
0512a75b
KB
1105 else
1106 ret = __bio_iov_iter_get_pages(bio, iter);
c42bca92
PB
1107 } while (!ret && iov_iter_count(iter) && !bio_full(bio, 0));
1108 }
0cf41e5e
PB
1109
1110 /* don't account direct I/O as memory stall */
1111 bio_clear_flag(bio, BIO_WORKINGSET);
14eacf12 1112 return bio->bi_vcnt ? 0 : ret;
17d51b10 1113}
29b2a3aa 1114EXPORT_SYMBOL_GPL(bio_iov_iter_get_pages);
2cefe4db 1115
4246a0b6 1116static void submit_bio_wait_endio(struct bio *bio)
9e882242 1117{
65e53aab 1118 complete(bio->bi_private);
9e882242
KO
1119}
1120
1121/**
1122 * submit_bio_wait - submit a bio, and wait until it completes
9e882242
KO
1123 * @bio: The &struct bio which describes the I/O
1124 *
1125 * Simple wrapper around submit_bio(). Returns 0 on success, or the error from
1126 * bio_endio() on failure.
3d289d68
JK
1127 *
1128 * WARNING: Unlike to how submit_bio() is usually used, this function does not
1129 * result in bio reference to be consumed. The caller must drop the reference
1130 * on his own.
9e882242 1131 */
4e49ea4a 1132int submit_bio_wait(struct bio *bio)
9e882242 1133{
309dca30
CH
1134 DECLARE_COMPLETION_ONSTACK_MAP(done,
1135 bio->bi_bdev->bd_disk->lockdep_map);
de6a78b6 1136 unsigned long hang_check;
9e882242 1137
65e53aab 1138 bio->bi_private = &done;
9e882242 1139 bio->bi_end_io = submit_bio_wait_endio;
1eff9d32 1140 bio->bi_opf |= REQ_SYNC;
4e49ea4a 1141 submit_bio(bio);
de6a78b6
ML
1142
1143 /* Prevent hang_check timer from firing at us during very long I/O */
1144 hang_check = sysctl_hung_task_timeout_secs;
1145 if (hang_check)
1146 while (!wait_for_completion_io_timeout(&done,
1147 hang_check * (HZ/2)))
1148 ;
1149 else
1150 wait_for_completion_io(&done);
9e882242 1151
65e53aab 1152 return blk_status_to_errno(bio->bi_status);
9e882242
KO
1153}
1154EXPORT_SYMBOL(submit_bio_wait);
1155
054bdf64
KO
1156/**
1157 * bio_advance - increment/complete a bio by some number of bytes
1158 * @bio: bio to advance
1159 * @bytes: number of bytes to complete
1160 *
1161 * This updates bi_sector, bi_size and bi_idx; if the number of bytes to
1162 * complete doesn't align with a bvec boundary, then bv_len and bv_offset will
1163 * be updated on the last bvec as well.
1164 *
1165 * @bio will then represent the remaining, uncompleted portion of the io.
1166 */
1167void bio_advance(struct bio *bio, unsigned bytes)
1168{
1169 if (bio_integrity(bio))
1170 bio_integrity_advance(bio, bytes);
1171
a892c8d5 1172 bio_crypt_advance(bio, bytes);
4550dd6c 1173 bio_advance_iter(bio, &bio->bi_iter, bytes);
054bdf64
KO
1174}
1175EXPORT_SYMBOL(bio_advance);
1176
45db54d5
KO
1177void bio_copy_data_iter(struct bio *dst, struct bvec_iter *dst_iter,
1178 struct bio *src, struct bvec_iter *src_iter)
16ac3d63 1179{
1cb9dda4 1180 struct bio_vec src_bv, dst_bv;
16ac3d63 1181 void *src_p, *dst_p;
1cb9dda4 1182 unsigned bytes;
16ac3d63 1183
45db54d5
KO
1184 while (src_iter->bi_size && dst_iter->bi_size) {
1185 src_bv = bio_iter_iovec(src, *src_iter);
1186 dst_bv = bio_iter_iovec(dst, *dst_iter);
1cb9dda4
KO
1187
1188 bytes = min(src_bv.bv_len, dst_bv.bv_len);
16ac3d63 1189
1cb9dda4
KO
1190 src_p = kmap_atomic(src_bv.bv_page);
1191 dst_p = kmap_atomic(dst_bv.bv_page);
16ac3d63 1192
1cb9dda4
KO
1193 memcpy(dst_p + dst_bv.bv_offset,
1194 src_p + src_bv.bv_offset,
16ac3d63
KO
1195 bytes);
1196
1197 kunmap_atomic(dst_p);
1198 kunmap_atomic(src_p);
1199
6e6e811d
KO
1200 flush_dcache_page(dst_bv.bv_page);
1201
22b56c29
PB
1202 bio_advance_iter_single(src, src_iter, bytes);
1203 bio_advance_iter_single(dst, dst_iter, bytes);
16ac3d63
KO
1204 }
1205}
38a72dac
KO
1206EXPORT_SYMBOL(bio_copy_data_iter);
1207
1208/**
45db54d5
KO
1209 * bio_copy_data - copy contents of data buffers from one bio to another
1210 * @src: source bio
1211 * @dst: destination bio
38a72dac
KO
1212 *
1213 * Stops when it reaches the end of either @src or @dst - that is, copies
1214 * min(src->bi_size, dst->bi_size) bytes (or the equivalent for lists of bios).
1215 */
1216void bio_copy_data(struct bio *dst, struct bio *src)
1217{
45db54d5
KO
1218 struct bvec_iter src_iter = src->bi_iter;
1219 struct bvec_iter dst_iter = dst->bi_iter;
1220
1221 bio_copy_data_iter(dst, &dst_iter, src, &src_iter);
38a72dac 1222}
16ac3d63
KO
1223EXPORT_SYMBOL(bio_copy_data);
1224
45db54d5
KO
1225/**
1226 * bio_list_copy_data - copy contents of data buffers from one chain of bios to
1227 * another
1228 * @src: source bio list
1229 * @dst: destination bio list
1230 *
1231 * Stops when it reaches the end of either the @src list or @dst list - that is,
1232 * copies min(src->bi_size, dst->bi_size) bytes (or the equivalent for lists of
1233 * bios).
1234 */
1235void bio_list_copy_data(struct bio *dst, struct bio *src)
1236{
1237 struct bvec_iter src_iter = src->bi_iter;
1238 struct bvec_iter dst_iter = dst->bi_iter;
1239
1240 while (1) {
1241 if (!src_iter.bi_size) {
1242 src = src->bi_next;
1243 if (!src)
1244 break;
1245
1246 src_iter = src->bi_iter;
1247 }
1248
1249 if (!dst_iter.bi_size) {
1250 dst = dst->bi_next;
1251 if (!dst)
1252 break;
1253
1254 dst_iter = dst->bi_iter;
1255 }
1256
1257 bio_copy_data_iter(dst, &dst_iter, src, &src_iter);
1258 }
1259}
1260EXPORT_SYMBOL(bio_list_copy_data);
1261
491221f8 1262void bio_free_pages(struct bio *bio)
1dfa0f68
CH
1263{
1264 struct bio_vec *bvec;
6dc4f100 1265 struct bvec_iter_all iter_all;
1dfa0f68 1266
2b070cfe 1267 bio_for_each_segment_all(bvec, bio, iter_all)
1dfa0f68
CH
1268 __free_page(bvec->bv_page);
1269}
491221f8 1270EXPORT_SYMBOL(bio_free_pages);
1dfa0f68 1271
1da177e4
LT
1272/*
1273 * bio_set_pages_dirty() and bio_check_pages_dirty() are support functions
1274 * for performing direct-IO in BIOs.
1275 *
1276 * The problem is that we cannot run set_page_dirty() from interrupt context
1277 * because the required locks are not interrupt-safe. So what we can do is to
1278 * mark the pages dirty _before_ performing IO. And in interrupt context,
1279 * check that the pages are still dirty. If so, fine. If not, redirty them
1280 * in process context.
1281 *
1282 * We special-case compound pages here: normally this means reads into hugetlb
1283 * pages. The logic in here doesn't really work right for compound pages
1284 * because the VM does not uniformly chase down the head page in all cases.
1285 * But dirtiness of compound pages is pretty meaningless anyway: the VM doesn't
1286 * handle them at all. So we skip compound pages here at an early stage.
1287 *
1288 * Note that this code is very hard to test under normal circumstances because
1289 * direct-io pins the pages with get_user_pages(). This makes
1290 * is_page_cache_freeable return false, and the VM will not clean the pages.
0d5c3eba 1291 * But other code (eg, flusher threads) could clean the pages if they are mapped
1da177e4
LT
1292 * pagecache.
1293 *
1294 * Simply disabling the call to bio_set_pages_dirty() is a good way to test the
1295 * deferred bio dirtying paths.
1296 */
1297
1298/*
1299 * bio_set_pages_dirty() will mark all the bio's pages as dirty.
1300 */
1301void bio_set_pages_dirty(struct bio *bio)
1302{
cb34e057 1303 struct bio_vec *bvec;
6dc4f100 1304 struct bvec_iter_all iter_all;
1da177e4 1305
2b070cfe 1306 bio_for_each_segment_all(bvec, bio, iter_all) {
3bb50983
CH
1307 if (!PageCompound(bvec->bv_page))
1308 set_page_dirty_lock(bvec->bv_page);
1da177e4
LT
1309 }
1310}
1311
1da177e4
LT
1312/*
1313 * bio_check_pages_dirty() will check that all the BIO's pages are still dirty.
1314 * If they are, then fine. If, however, some pages are clean then they must
1315 * have been written out during the direct-IO read. So we take another ref on
24d5493f 1316 * the BIO and re-dirty the pages in process context.
1da177e4
LT
1317 *
1318 * It is expected that bio_check_pages_dirty() will wholly own the BIO from
ea1754a0
KS
1319 * here on. It will run one put_page() against each page and will run one
1320 * bio_put() against the BIO.
1da177e4
LT
1321 */
1322
65f27f38 1323static void bio_dirty_fn(struct work_struct *work);
1da177e4 1324
65f27f38 1325static DECLARE_WORK(bio_dirty_work, bio_dirty_fn);
1da177e4
LT
1326static DEFINE_SPINLOCK(bio_dirty_lock);
1327static struct bio *bio_dirty_list;
1328
1329/*
1330 * This runs in process context
1331 */
65f27f38 1332static void bio_dirty_fn(struct work_struct *work)
1da177e4 1333{
24d5493f 1334 struct bio *bio, *next;
1da177e4 1335
24d5493f
CH
1336 spin_lock_irq(&bio_dirty_lock);
1337 next = bio_dirty_list;
1da177e4 1338 bio_dirty_list = NULL;
24d5493f 1339 spin_unlock_irq(&bio_dirty_lock);
1da177e4 1340
24d5493f
CH
1341 while ((bio = next) != NULL) {
1342 next = bio->bi_private;
1da177e4 1343
d241a95f 1344 bio_release_pages(bio, true);
1da177e4 1345 bio_put(bio);
1da177e4
LT
1346 }
1347}
1348
1349void bio_check_pages_dirty(struct bio *bio)
1350{
cb34e057 1351 struct bio_vec *bvec;
24d5493f 1352 unsigned long flags;
6dc4f100 1353 struct bvec_iter_all iter_all;
1da177e4 1354
2b070cfe 1355 bio_for_each_segment_all(bvec, bio, iter_all) {
24d5493f
CH
1356 if (!PageDirty(bvec->bv_page) && !PageCompound(bvec->bv_page))
1357 goto defer;
1da177e4
LT
1358 }
1359
d241a95f 1360 bio_release_pages(bio, false);
24d5493f
CH
1361 bio_put(bio);
1362 return;
1363defer:
1364 spin_lock_irqsave(&bio_dirty_lock, flags);
1365 bio->bi_private = bio_dirty_list;
1366 bio_dirty_list = bio;
1367 spin_unlock_irqrestore(&bio_dirty_lock, flags);
1368 schedule_work(&bio_dirty_work);
1da177e4
LT
1369}
1370
c4cf5261
JA
1371static inline bool bio_remaining_done(struct bio *bio)
1372{
1373 /*
1374 * If we're not chaining, then ->__bi_remaining is always 1 and
1375 * we always end io on the first invocation.
1376 */
1377 if (!bio_flagged(bio, BIO_CHAIN))
1378 return true;
1379
1380 BUG_ON(atomic_read(&bio->__bi_remaining) <= 0);
1381
326e1dbb 1382 if (atomic_dec_and_test(&bio->__bi_remaining)) {
b7c44ed9 1383 bio_clear_flag(bio, BIO_CHAIN);
c4cf5261 1384 return true;
326e1dbb 1385 }
c4cf5261
JA
1386
1387 return false;
1388}
1389
1da177e4
LT
1390/**
1391 * bio_endio - end I/O on a bio
1392 * @bio: bio
1da177e4
LT
1393 *
1394 * Description:
4246a0b6
CH
1395 * bio_endio() will end I/O on the whole bio. bio_endio() is the preferred
1396 * way to end I/O on a bio. No one should call bi_end_io() directly on a
1397 * bio unless they own it and thus know that it has an end_io function.
fbbaf700
N
1398 *
1399 * bio_endio() can be called several times on a bio that has been chained
1400 * using bio_chain(). The ->bi_end_io() function will only be called the
1401 * last time. At this point the BLK_TA_COMPLETE tracing event will be
1402 * generated if BIO_TRACE_COMPLETION is set.
1da177e4 1403 **/
4246a0b6 1404void bio_endio(struct bio *bio)
1da177e4 1405{
ba8c6967 1406again:
2b885517 1407 if (!bio_remaining_done(bio))
ba8c6967 1408 return;
7c20f116
CH
1409 if (!bio_integrity_endio(bio))
1410 return;
1da177e4 1411
309dca30
CH
1412 if (bio->bi_bdev)
1413 rq_qos_done_bio(bio->bi_bdev->bd_disk->queue, bio);
67b42d0b 1414
ba8c6967
CH
1415 /*
1416 * Need to have a real endio function for chained bios, otherwise
1417 * various corner cases will break (like stacking block devices that
1418 * save/restore bi_end_io) - however, we want to avoid unbounded
1419 * recursion and blowing the stack. Tail call optimization would
1420 * handle this, but compiling with frame pointers also disables
1421 * gcc's sibling call optimization.
1422 */
1423 if (bio->bi_end_io == bio_chain_endio) {
1424 bio = __bio_chain_endio(bio);
1425 goto again;
196d38bc 1426 }
ba8c6967 1427
309dca30
CH
1428 if (bio->bi_bdev && bio_flagged(bio, BIO_TRACE_COMPLETION)) {
1429 trace_block_bio_complete(bio->bi_bdev->bd_disk->queue, bio);
fbbaf700
N
1430 bio_clear_flag(bio, BIO_TRACE_COMPLETION);
1431 }
1432
9e234eea 1433 blk_throtl_bio_endio(bio);
b222dd2f
SL
1434 /* release cgroup info */
1435 bio_uninit(bio);
ba8c6967
CH
1436 if (bio->bi_end_io)
1437 bio->bi_end_io(bio);
1da177e4 1438}
a112a71d 1439EXPORT_SYMBOL(bio_endio);
1da177e4 1440
20d0189b
KO
1441/**
1442 * bio_split - split a bio
1443 * @bio: bio to split
1444 * @sectors: number of sectors to split from the front of @bio
1445 * @gfp: gfp mask
1446 * @bs: bio set to allocate from
1447 *
1448 * Allocates and returns a new bio which represents @sectors from the start of
1449 * @bio, and updates @bio to represent the remaining sectors.
1450 *
f3f5da62 1451 * Unless this is a discard request the newly allocated bio will point
dad77584
BVA
1452 * to @bio's bi_io_vec. It is the caller's responsibility to ensure that
1453 * neither @bio nor @bs are freed before the split bio.
20d0189b
KO
1454 */
1455struct bio *bio_split(struct bio *bio, int sectors,
1456 gfp_t gfp, struct bio_set *bs)
1457{
f341a4d3 1458 struct bio *split;
20d0189b
KO
1459
1460 BUG_ON(sectors <= 0);
1461 BUG_ON(sectors >= bio_sectors(bio));
1462
0512a75b
KB
1463 /* Zone append commands cannot be split */
1464 if (WARN_ON_ONCE(bio_op(bio) == REQ_OP_ZONE_APPEND))
1465 return NULL;
1466
f9d03f96 1467 split = bio_clone_fast(bio, gfp, bs);
20d0189b
KO
1468 if (!split)
1469 return NULL;
1470
1471 split->bi_iter.bi_size = sectors << 9;
1472
1473 if (bio_integrity(split))
fbd08e76 1474 bio_integrity_trim(split);
20d0189b
KO
1475
1476 bio_advance(bio, split->bi_iter.bi_size);
1477
fbbaf700 1478 if (bio_flagged(bio, BIO_TRACE_COMPLETION))
20d59023 1479 bio_set_flag(split, BIO_TRACE_COMPLETION);
fbbaf700 1480
20d0189b
KO
1481 return split;
1482}
1483EXPORT_SYMBOL(bio_split);
1484
6678d83f
KO
1485/**
1486 * bio_trim - trim a bio
1487 * @bio: bio to trim
1488 * @offset: number of sectors to trim from the front of @bio
1489 * @size: size we want to trim @bio to, in sectors
1490 */
1491void bio_trim(struct bio *bio, int offset, int size)
1492{
1493 /* 'bio' is a cloned bio which we need to trim to match
1494 * the given offset and size.
6678d83f 1495 */
6678d83f
KO
1496
1497 size <<= 9;
4f024f37 1498 if (offset == 0 && size == bio->bi_iter.bi_size)
6678d83f
KO
1499 return;
1500
6678d83f 1501 bio_advance(bio, offset << 9);
4f024f37 1502 bio->bi_iter.bi_size = size;
376a78ab
DM
1503
1504 if (bio_integrity(bio))
fbd08e76 1505 bio_integrity_trim(bio);
376a78ab 1506
6678d83f
KO
1507}
1508EXPORT_SYMBOL_GPL(bio_trim);
1509
1da177e4
LT
1510/*
1511 * create memory pools for biovec's in a bio_set.
1512 * use the global biovec slabs created for general use.
1513 */
8aa6ba2f 1514int biovec_init_pool(mempool_t *pool, int pool_entries)
1da177e4 1515{
ed996a52 1516 struct biovec_slab *bp = bvec_slabs + BVEC_POOL_MAX;
1da177e4 1517
8aa6ba2f 1518 return mempool_init_slab_pool(pool, pool_entries, bp->slab);
1da177e4
LT
1519}
1520
917a38c7
KO
1521/*
1522 * bioset_exit - exit a bioset initialized with bioset_init()
1523 *
1524 * May be called on a zeroed but uninitialized bioset (i.e. allocated with
1525 * kzalloc()).
1526 */
1527void bioset_exit(struct bio_set *bs)
1da177e4 1528{
df2cb6da
KO
1529 if (bs->rescue_workqueue)
1530 destroy_workqueue(bs->rescue_workqueue);
917a38c7 1531 bs->rescue_workqueue = NULL;
df2cb6da 1532
8aa6ba2f
KO
1533 mempool_exit(&bs->bio_pool);
1534 mempool_exit(&bs->bvec_pool);
9f060e22 1535
7878cba9 1536 bioset_integrity_free(bs);
917a38c7
KO
1537 if (bs->bio_slab)
1538 bio_put_slab(bs);
1539 bs->bio_slab = NULL;
1540}
1541EXPORT_SYMBOL(bioset_exit);
1da177e4 1542
917a38c7
KO
1543/**
1544 * bioset_init - Initialize a bio_set
dad08527 1545 * @bs: pool to initialize
917a38c7
KO
1546 * @pool_size: Number of bio and bio_vecs to cache in the mempool
1547 * @front_pad: Number of bytes to allocate in front of the returned bio
1548 * @flags: Flags to modify behavior, currently %BIOSET_NEED_BVECS
1549 * and %BIOSET_NEED_RESCUER
1550 *
dad08527
KO
1551 * Description:
1552 * Set up a bio_set to be used with @bio_alloc_bioset. Allows the caller
1553 * to ask for a number of bytes to be allocated in front of the bio.
1554 * Front pad allocation is useful for embedding the bio inside
1555 * another structure, to avoid allocating extra data to go with the bio.
1556 * Note that the bio must be embedded at the END of that structure always,
1557 * or things will break badly.
1558 * If %BIOSET_NEED_BVECS is set in @flags, a separate pool will be allocated
1559 * for allocating iovecs. This pool is not needed e.g. for bio_clone_fast().
1560 * If %BIOSET_NEED_RESCUER is set, a workqueue is created which can be used to
1561 * dispatch queued requests when the mempool runs out of space.
1562 *
917a38c7
KO
1563 */
1564int bioset_init(struct bio_set *bs,
1565 unsigned int pool_size,
1566 unsigned int front_pad,
1567 int flags)
1568{
917a38c7 1569 bs->front_pad = front_pad;
9f180e31
ML
1570 if (flags & BIOSET_NEED_BVECS)
1571 bs->back_pad = BIO_INLINE_VECS * sizeof(struct bio_vec);
1572 else
1573 bs->back_pad = 0;
917a38c7
KO
1574
1575 spin_lock_init(&bs->rescue_lock);
1576 bio_list_init(&bs->rescue_list);
1577 INIT_WORK(&bs->rescue_work, bio_alloc_rescue);
1578
49d1ec85 1579 bs->bio_slab = bio_find_or_create_slab(bs);
917a38c7
KO
1580 if (!bs->bio_slab)
1581 return -ENOMEM;
1582
1583 if (mempool_init_slab_pool(&bs->bio_pool, pool_size, bs->bio_slab))
1584 goto bad;
1585
1586 if ((flags & BIOSET_NEED_BVECS) &&
1587 biovec_init_pool(&bs->bvec_pool, pool_size))
1588 goto bad;
1589
1590 if (!(flags & BIOSET_NEED_RESCUER))
1591 return 0;
1592
1593 bs->rescue_workqueue = alloc_workqueue("bioset", WQ_MEM_RECLAIM, 0);
1594 if (!bs->rescue_workqueue)
1595 goto bad;
1596
1597 return 0;
1598bad:
1599 bioset_exit(bs);
1600 return -ENOMEM;
1601}
1602EXPORT_SYMBOL(bioset_init);
1603
28e89fd9
JA
1604/*
1605 * Initialize and setup a new bio_set, based on the settings from
1606 * another bio_set.
1607 */
1608int bioset_init_from_src(struct bio_set *bs, struct bio_set *src)
1609{
1610 int flags;
1611
1612 flags = 0;
1613 if (src->bvec_pool.min_nr)
1614 flags |= BIOSET_NEED_BVECS;
1615 if (src->rescue_workqueue)
1616 flags |= BIOSET_NEED_RESCUER;
1617
1618 return bioset_init(bs, src->bio_pool.min_nr, src->front_pad, flags);
1619}
1620EXPORT_SYMBOL(bioset_init_from_src);
1621
1da177e4
LT
1622static void __init biovec_init_slabs(void)
1623{
1624 int i;
1625
ed996a52 1626 for (i = 0; i < BVEC_POOL_NR; i++) {
1da177e4
LT
1627 int size;
1628 struct biovec_slab *bvs = bvec_slabs + i;
1629
a7fcd37c
JA
1630 if (bvs->nr_vecs <= BIO_INLINE_VECS) {
1631 bvs->slab = NULL;
1632 continue;
1633 }
a7fcd37c 1634
1da177e4
LT
1635 size = bvs->nr_vecs * sizeof(struct bio_vec);
1636 bvs->slab = kmem_cache_create(bvs->name, size, 0,
20c2df83 1637 SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
1da177e4
LT
1638 }
1639}
1640
1641static int __init init_bio(void)
1642{
2b24e6f6
JT
1643 BUILD_BUG_ON(BIO_FLAG_LAST > BVEC_POOL_OFFSET);
1644
7878cba9 1645 bio_integrity_init();
1da177e4
LT
1646 biovec_init_slabs();
1647
f4f8154a 1648 if (bioset_init(&fs_bio_set, BIO_POOL_SIZE, 0, BIOSET_NEED_BVECS))
1da177e4
LT
1649 panic("bio: can't allocate bios\n");
1650
f4f8154a 1651 if (bioset_integrity_create(&fs_bio_set, BIO_POOL_SIZE))
a91a2785
MP
1652 panic("bio: can't create integrity pool\n");
1653
1da177e4
LT
1654 return 0;
1655}
1da177e4 1656subsys_initcall(init_bio);