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