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