xref: /linux/block/bio.c (revision d0fc310b4dfd334023b90d2423818044190c0f68)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2001 Jens Axboe <axboe@kernel.dk>
4  */
5 #include <linux/mm.h>
6 #include <linux/swap.h>
7 #include <linux/bio-integrity.h>
8 #include <linux/blkdev.h>
9 #include <linux/uio.h>
10 #include <linux/iocontext.h>
11 #include <linux/slab.h>
12 #include <linux/init.h>
13 #include <linux/kernel.h>
14 #include <linux/export.h>
15 #include <linux/mempool.h>
16 #include <linux/workqueue.h>
17 #include <linux/cgroup.h>
18 #include <linux/highmem.h>
19 #include <linux/blk-crypto.h>
20 #include <linux/xarray.h>
21 #include <linux/kmemleak.h>
22 
23 #include <trace/events/block.h>
24 #include "blk.h"
25 #include "blk-rq-qos.h"
26 #include "blk-cgroup.h"
27 
28 #define ALLOC_CACHE_THRESHOLD	16
29 #define ALLOC_CACHE_MAX		256
30 
31 struct bio_alloc_cache {
32 	struct bio		*free_list;
33 	struct bio		*free_list_irq;
34 	unsigned int		nr;
35 	unsigned int		nr_irq;
36 };
37 
38 #define BIO_INLINE_VECS 4
39 
40 static struct biovec_slab {
41 	int nr_vecs;
42 	char *name;
43 	struct kmem_cache *slab;
44 } bvec_slabs[] __read_mostly = {
45 	{ .nr_vecs = 16, .name = "biovec-16" },
46 	{ .nr_vecs = 64, .name = "biovec-64" },
47 	{ .nr_vecs = 128, .name = "biovec-128" },
48 	{ .nr_vecs = BIO_MAX_VECS, .name = "biovec-max" },
49 };
50 
biovec_slab(unsigned short nr_vecs)51 static struct biovec_slab *biovec_slab(unsigned short nr_vecs)
52 {
53 	switch (nr_vecs) {
54 	/* smaller bios use inline vecs */
55 	case 5 ... 16:
56 		return &bvec_slabs[0];
57 	case 17 ... 64:
58 		return &bvec_slabs[1];
59 	case 65 ... 128:
60 		return &bvec_slabs[2];
61 	case 129 ... BIO_MAX_VECS:
62 		return &bvec_slabs[3];
63 	default:
64 		BUG();
65 		return NULL;
66 	}
67 }
68 
69 /*
70  * fs_bio_set is the bio_set containing bio and iovec memory pools used by
71  * IO code that does not need private memory pools.
72  */
73 struct bio_set fs_bio_set;
74 EXPORT_SYMBOL(fs_bio_set);
75 
76 /*
77  * Our slab pool management
78  */
79 struct bio_slab {
80 	struct kmem_cache *slab;
81 	unsigned int slab_ref;
82 	unsigned int slab_size;
83 	char name[12];
84 };
85 static DEFINE_MUTEX(bio_slab_lock);
86 static DEFINE_XARRAY(bio_slabs);
87 
create_bio_slab(unsigned int size)88 static struct bio_slab *create_bio_slab(unsigned int size)
89 {
90 	struct bio_slab *bslab = kzalloc_obj(*bslab);
91 
92 	if (!bslab)
93 		return NULL;
94 
95 	snprintf(bslab->name, sizeof(bslab->name), "bio-%d", size);
96 	bslab->slab = kmem_cache_create(bslab->name, size,
97 			ARCH_KMALLOC_MINALIGN,
98 			SLAB_HWCACHE_ALIGN | SLAB_TYPESAFE_BY_RCU, NULL);
99 	if (!bslab->slab)
100 		goto fail_alloc_slab;
101 
102 	bslab->slab_ref = 1;
103 	bslab->slab_size = size;
104 
105 	if (!xa_err(xa_store(&bio_slabs, size, bslab, GFP_KERNEL)))
106 		return bslab;
107 
108 	kmem_cache_destroy(bslab->slab);
109 
110 fail_alloc_slab:
111 	kfree(bslab);
112 	return NULL;
113 }
114 
bs_bio_slab_size(struct bio_set * bs)115 static inline unsigned int bs_bio_slab_size(struct bio_set *bs)
116 {
117 	return bs->front_pad + sizeof(struct bio) + bs->back_pad;
118 }
119 
bio_slab_addr(struct bio * bio)120 static inline void *bio_slab_addr(struct bio *bio)
121 {
122 	return (void *)bio - bio->bi_pool->front_pad;
123 }
124 
bio_find_or_create_slab(struct bio_set * bs)125 static struct kmem_cache *bio_find_or_create_slab(struct bio_set *bs)
126 {
127 	unsigned int size = bs_bio_slab_size(bs);
128 	struct bio_slab *bslab;
129 
130 	mutex_lock(&bio_slab_lock);
131 	bslab = xa_load(&bio_slabs, size);
132 	if (bslab)
133 		bslab->slab_ref++;
134 	else
135 		bslab = create_bio_slab(size);
136 	mutex_unlock(&bio_slab_lock);
137 
138 	if (bslab)
139 		return bslab->slab;
140 	return NULL;
141 }
142 
bio_put_slab(struct bio_set * bs)143 static void bio_put_slab(struct bio_set *bs)
144 {
145 	struct bio_slab *bslab = NULL;
146 	unsigned int slab_size = bs_bio_slab_size(bs);
147 
148 	mutex_lock(&bio_slab_lock);
149 
150 	bslab = xa_load(&bio_slabs, slab_size);
151 	if (WARN(!bslab, KERN_ERR "bio: unable to find slab!\n"))
152 		goto out;
153 
154 	WARN_ON_ONCE(bslab->slab != bs->bio_slab);
155 
156 	WARN_ON(!bslab->slab_ref);
157 
158 	if (--bslab->slab_ref)
159 		goto out;
160 
161 	xa_erase(&bio_slabs, slab_size);
162 
163 	kmem_cache_destroy(bslab->slab);
164 	kfree(bslab);
165 
166 out:
167 	mutex_unlock(&bio_slab_lock);
168 }
169 
170 /*
171  * Make the first allocation restricted and don't dump info on allocation
172  * failures, since we'll fall back to the mempool in case of failure.
173  */
try_alloc_gfp(gfp_t gfp)174 static inline gfp_t try_alloc_gfp(gfp_t gfp)
175 {
176 	return (gfp & ~(__GFP_DIRECT_RECLAIM | __GFP_IO)) |
177 		__GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN;
178 }
179 
bio_uninit(struct bio * bio)180 void bio_uninit(struct bio *bio)
181 {
182 #ifdef CONFIG_BLK_CGROUP
183 	if (bio->bi_blkg) {
184 		blkg_put(bio->bi_blkg);
185 		bio->bi_blkg = NULL;
186 	}
187 #endif
188 	if (bio_integrity(bio))
189 		bio_integrity_free(bio);
190 
191 	bio_crypt_free_ctx(bio);
192 }
193 EXPORT_SYMBOL(bio_uninit);
194 
bio_free(struct bio * bio)195 static void bio_free(struct bio *bio)
196 {
197 	struct bio_set *bs = bio->bi_pool;
198 	void *p = bio;
199 
200 	WARN_ON_ONCE(!bs);
201 	WARN_ON_ONCE(bio->bi_max_vecs > BIO_MAX_VECS);
202 
203 	bio_uninit(bio);
204 	if (bio->bi_max_vecs == BIO_MAX_VECS)
205 		mempool_free(bio->bi_io_vec, &bs->bvec_pool);
206 	else if (bio->bi_max_vecs > BIO_INLINE_VECS)
207 		kmem_cache_free(biovec_slab(bio->bi_max_vecs)->slab,
208 				bio->bi_io_vec);
209 	mempool_free(p - bs->front_pad, &bs->bio_pool);
210 }
211 
212 /*
213  * Users of this function have their own bio allocation. Subsequently,
214  * they must remember to pair any call to bio_init() with bio_uninit()
215  * when IO has completed, or when the bio is released.
216  */
bio_init(struct bio * bio,struct block_device * bdev,struct bio_vec * table,unsigned short max_vecs,blk_opf_t opf)217 void bio_init(struct bio *bio, struct block_device *bdev, struct bio_vec *table,
218 	      unsigned short max_vecs, blk_opf_t opf)
219 {
220 	bio->bi_next = NULL;
221 	bio->bi_bdev = bdev;
222 	bio->bi_opf = opf;
223 	bio->bi_flags = 0;
224 	bio->bi_ioprio = 0;
225 	bio->bi_write_hint = 0;
226 	bio->bi_write_stream = 0;
227 	bio->bi_status = 0;
228 	bio->bi_bvec_gap_bit = 0;
229 	bio->bi_iter.bi_sector = 0;
230 	bio->bi_iter.bi_size = 0;
231 	bio->bi_iter.bi_idx = 0;
232 	bio->bi_iter.bi_offset = 0;
233 	bio->bi_end_io = NULL;
234 	bio->bi_private = NULL;
235 #ifdef CONFIG_BLK_CGROUP
236 	bio->bi_blkg = NULL;
237 	bio->issue_time_ns = 0;
238 	if (bdev)
239 		bio_associate_blkg(bio);
240 #ifdef CONFIG_BLK_CGROUP_IOCOST
241 	bio->bi_iocost_cost = 0;
242 #endif
243 #endif
244 #ifdef CONFIG_BLK_INLINE_ENCRYPTION
245 	bio->bi_crypt_context = NULL;
246 #endif
247 #ifdef CONFIG_BLK_DEV_INTEGRITY
248 	bio->bi_integrity = NULL;
249 #endif
250 	bio->bi_vcnt = 0;
251 
252 	atomic_set(&bio->__bi_remaining, 1);
253 	atomic_set(&bio->__bi_cnt, 1);
254 	bio->bi_cookie = BLK_QC_T_NONE;
255 
256 	bio->bi_max_vecs = max_vecs;
257 	bio->bi_io_vec = table;
258 	bio->bi_pool = NULL;
259 }
260 EXPORT_SYMBOL(bio_init);
261 
262 /**
263  * bio_reset - reinitialize a bio
264  * @bio:	bio to reset
265  * @bdev:	block device to use the bio for
266  * @opf:	operation and flags for bio
267  *
268  * Description:
269  *   After calling bio_reset(), @bio will be in the same state as a freshly
270  *   allocated bio returned bio bio_alloc_bioset() - the only fields that are
271  *   preserved are the ones that are initialized by bio_alloc_bioset(). See
272  *   comment in struct bio.
273  */
bio_reset(struct bio * bio,struct block_device * bdev,blk_opf_t opf)274 void bio_reset(struct bio *bio, struct block_device *bdev, blk_opf_t opf)
275 {
276 	struct bio_vec          *bv = bio->bi_io_vec;
277 
278 	bio_uninit(bio);
279 	memset(bio, 0, BIO_RESET_BYTES);
280 	atomic_set(&bio->__bi_remaining, 1);
281 	bio->bi_io_vec = bv;
282 	bio->bi_bdev = bdev;
283 	if (bio->bi_bdev)
284 		bio_associate_blkg(bio);
285 	bio->bi_opf = opf;
286 }
287 EXPORT_SYMBOL(bio_reset);
288 
289 /**
290  * bio_reuse - reuse a bio with the payload left intact
291  * @bio:	bio to reuse
292  * @opf:	operation and flags for the next I/O
293  *
294  * Allow reusing an existing bio for another operation with all set up
295  * fields including the payload, device and end_io handler left intact.
296  *
297  * Typically used when @bio is first used to read data which is then written
298  * to another location without modification.  @bio must not be in-flight and
299  * owned by the caller.  Can't be used for cloned bios.
300  *
301  * Note: Can't be used when @bio has integrity or blk-crypto contexts for now.
302  * Feel free to add that support when you need it, though.
303  */
bio_reuse(struct bio * bio,blk_opf_t opf)304 void bio_reuse(struct bio *bio, blk_opf_t opf)
305 {
306 	unsigned short vcnt = bio->bi_vcnt, i;
307 	bio_end_io_t *end_io = bio->bi_end_io;
308 	void *private = bio->bi_private;
309 
310 	WARN_ON_ONCE(bio_flagged(bio, BIO_CLONED));
311 	WARN_ON_ONCE(bio_integrity(bio));
312 	WARN_ON_ONCE(bio_has_crypt_ctx(bio));
313 
314 	bio_reset(bio, bio->bi_bdev, opf);
315 	for (i = 0; i < vcnt; i++)
316 		bio->bi_iter.bi_size += bio->bi_io_vec[i].bv_len;
317 	bio->bi_vcnt = vcnt;
318 	bio->bi_private = private;
319 	bio->bi_end_io = end_io;
320 }
321 EXPORT_SYMBOL_GPL(bio_reuse);
322 
__bio_chain_endio(struct bio * bio)323 static struct bio *__bio_chain_endio(struct bio *bio)
324 {
325 	struct bio *parent = bio->bi_private;
326 
327 	if (bio->bi_status && !parent->bi_status)
328 		parent->bi_status = bio->bi_status;
329 	bio_put(bio);
330 	return parent;
331 }
332 
333 /*
334  * This function should only be used as a flag and must never be called.
335  * If execution reaches here, it indicates a serious programming error.
336  */
bio_chain_endio(struct bio * bio)337 static void bio_chain_endio(struct bio *bio)
338 {
339 	BUG();
340 }
341 
342 /**
343  * bio_chain - chain bio completions
344  * @bio: the target bio
345  * @parent: the parent bio of @bio
346  *
347  * The caller won't have a bi_end_io called when @bio completes - instead,
348  * @parent's bi_end_io won't be called until both @parent and @bio have
349  * completed; the chained bio will also be freed when it completes.
350  *
351  * The caller must not set bi_private or bi_end_io in @bio.
352  */
bio_chain(struct bio * bio,struct bio * parent)353 void bio_chain(struct bio *bio, struct bio *parent)
354 {
355 	BUG_ON(bio->bi_private || bio->bi_end_io);
356 
357 	bio->bi_private = parent;
358 	bio->bi_end_io	= bio_chain_endio;
359 	bio_inc_remaining(parent);
360 }
361 EXPORT_SYMBOL(bio_chain);
362 
363 /**
364  * bio_chain_and_submit - submit a bio after chaining it to another one
365  * @prev: bio to chain and submit
366  * @new: bio to chain to
367  *
368  * If @prev is non-NULL, chain it to @new and submit it.
369  *
370  * Return: @new.
371  */
bio_chain_and_submit(struct bio * prev,struct bio * new)372 struct bio *bio_chain_and_submit(struct bio *prev, struct bio *new)
373 {
374 	if (prev) {
375 		bio_chain(prev, new);
376 		submit_bio(prev);
377 	}
378 	return new;
379 }
380 
blk_next_bio(struct bio * bio,struct block_device * bdev,unsigned int nr_pages,blk_opf_t opf,gfp_t gfp)381 struct bio *blk_next_bio(struct bio *bio, struct block_device *bdev,
382 		unsigned int nr_pages, blk_opf_t opf, gfp_t gfp)
383 {
384 	return bio_chain_and_submit(bio, bio_alloc(bdev, nr_pages, opf, gfp));
385 }
386 EXPORT_SYMBOL_GPL(blk_next_bio);
387 
bio_alloc_rescue(struct work_struct * work)388 static void bio_alloc_rescue(struct work_struct *work)
389 {
390 	struct bio_set *bs = container_of(work, struct bio_set, rescue_work);
391 	struct bio *bio;
392 
393 	while (1) {
394 		spin_lock(&bs->rescue_lock);
395 		bio = bio_list_pop(&bs->rescue_list);
396 		spin_unlock(&bs->rescue_lock);
397 
398 		if (!bio)
399 			break;
400 
401 		submit_bio_noacct(bio);
402 	}
403 }
404 
405 /*
406  * submit_bio_noacct() converts recursion to iteration; this means if we're
407  * running beneath it, any bios we allocate and submit will not be submitted
408  * (and thus freed) until after we return.
409  *
410  * This exposes us to a potential deadlock if we allocate multiple bios from the
411  * same bio_set while running underneath submit_bio_noacct().  If we were to
412  * allocate multiple bios (say a stacking block driver that was splitting bios),
413  * we would deadlock if we exhausted the mempool's reserve.
414  *
415  * We solve this, and guarantee forward progress by punting the bios on
416  * current->bio_list to a per bio_set rescuer workqueue before blocking to wait
417  * for elements being returned to the mempool.
418  */
punt_bios_to_rescuer(struct bio_set * bs)419 static void punt_bios_to_rescuer(struct bio_set *bs)
420 {
421 	struct bio_list punt, nopunt;
422 	struct bio *bio;
423 
424 	if (!current->bio_list || !bs->rescue_workqueue)
425 		return;
426 	if (bio_list_empty(&current->bio_list[0]) &&
427 	    bio_list_empty(&current->bio_list[1]))
428 		return;
429 
430 	/*
431 	 * In order to guarantee forward progress we must punt only bios that
432 	 * were allocated from this bio_set; otherwise, if there was a bio on
433 	 * there for a stacking driver higher up in the stack, processing it
434 	 * could require allocating bios from this bio_set, and doing that from
435 	 * our own rescuer would be bad.
436 	 *
437 	 * Since bio lists are singly linked, pop them all instead of trying to
438 	 * remove from the middle of the list:
439 	 */
440 
441 	bio_list_init(&punt);
442 	bio_list_init(&nopunt);
443 
444 	while ((bio = bio_list_pop(&current->bio_list[0])))
445 		bio_list_add(bio->bi_pool == bs ? &punt : &nopunt, bio);
446 	current->bio_list[0] = nopunt;
447 
448 	bio_list_init(&nopunt);
449 	while ((bio = bio_list_pop(&current->bio_list[1])))
450 		bio_list_add(bio->bi_pool == bs ? &punt : &nopunt, bio);
451 	current->bio_list[1] = nopunt;
452 
453 	spin_lock(&bs->rescue_lock);
454 	bio_list_merge(&bs->rescue_list, &punt);
455 	spin_unlock(&bs->rescue_lock);
456 
457 	queue_work(bs->rescue_workqueue, &bs->rescue_work);
458 }
459 
bio_alloc_irq_cache_splice(struct bio_alloc_cache * cache)460 static void bio_alloc_irq_cache_splice(struct bio_alloc_cache *cache)
461 {
462 	unsigned long flags;
463 
464 	/* cache->free_list must be empty */
465 	if (WARN_ON_ONCE(cache->free_list))
466 		return;
467 
468 	local_irq_save(flags);
469 	cache->free_list = cache->free_list_irq;
470 	cache->free_list_irq = NULL;
471 	cache->nr += cache->nr_irq;
472 	cache->nr_irq = 0;
473 	local_irq_restore(flags);
474 }
475 
bio_alloc_percpu_cache(struct bio_set * bs)476 static struct bio *bio_alloc_percpu_cache(struct bio_set *bs)
477 {
478 	struct bio_alloc_cache *cache;
479 	struct bio *bio;
480 
481 	cache = per_cpu_ptr(bs->cache, get_cpu());
482 	if (!cache->free_list) {
483 		if (READ_ONCE(cache->nr_irq) >= ALLOC_CACHE_THRESHOLD)
484 			bio_alloc_irq_cache_splice(cache);
485 		if (!cache->free_list) {
486 			put_cpu();
487 			return NULL;
488 		}
489 	}
490 	bio = cache->free_list;
491 	cache->free_list = bio->bi_next;
492 	cache->nr--;
493 	put_cpu();
494 	bio->bi_pool = bs;
495 
496 	kmemleak_alloc(bio_slab_addr(bio),
497 		       kmem_cache_size(bs->bio_slab), 1, GFP_NOIO);
498 	return bio;
499 }
500 
501 /**
502  * bio_alloc_bioset - allocate a bio for I/O
503  * @bdev:	block device to allocate the bio for (can be %NULL)
504  * @nr_vecs:	number of bvecs to pre-allocate
505  * @opf:	operation and flags for bio
506  * @gfp:	the GFP_* mask given to the slab allocator
507  * @bs:		the bio_set to allocate from.
508  *
509  * Allocate a bio from the mempools in @bs.
510  *
511  * If %__GFP_DIRECT_RECLAIM is set then bio_alloc will always be able to
512  * allocate a bio.  This is due to the mempool guarantees.  To make this work,
513  * callers must never allocate more than 1 bio at a time from the general pool.
514  * Callers that need to allocate more than 1 bio must always submit the
515  * previously allocated bio for IO before attempting to allocate a new one.
516  * Failure to do so can cause deadlocks under memory pressure.
517  *
518  * Note that when running under submit_bio_noacct() (i.e. any block driver),
519  * bios are not submitted until after you return - see the code in
520  * submit_bio_noacct() that converts recursion into iteration, to prevent
521  * stack overflows.
522  *
523  * This would normally mean allocating multiple bios under submit_bio_noacct()
524  * would be susceptible to deadlocks, but we have
525  * deadlock avoidance code that resubmits any blocked bios from a rescuer
526  * thread.
527  *
528  * However, we do not guarantee forward progress for allocations from other
529  * mempools. Doing multiple allocations from the same mempool under
530  * submit_bio_noacct() should be avoided - instead, use bio_set's front_pad
531  * for per bio allocations.
532  *
533  * Returns: Pointer to new bio on success, NULL on failure.
534  */
bio_alloc_bioset(struct block_device * bdev,unsigned short nr_vecs,blk_opf_t opf,gfp_t gfp,struct bio_set * bs)535 struct bio *bio_alloc_bioset(struct block_device *bdev, unsigned short nr_vecs,
536 			     blk_opf_t opf, gfp_t gfp, struct bio_set *bs)
537 {
538 	struct bio_vec *bvecs = NULL;
539 	struct bio *bio = NULL;
540 	gfp_t saved_gfp = gfp;
541 	void *p;
542 
543 	/* should not use nobvec bioset for nr_vecs > 0 */
544 	if (WARN_ON_ONCE(!mempool_initialized(&bs->bvec_pool) && nr_vecs > 0))
545 		return NULL;
546 
547 	if (saved_gfp & __GFP_DIRECT_RECLAIM)
548 		gfp = try_alloc_gfp(gfp);
549 	if (bs->cache && nr_vecs <= BIO_INLINE_VECS) {
550 		/*
551 		 * Set REQ_ALLOC_CACHE even if no cached bio is available to
552 		 * return the allocated bio to the percpu cache when done.
553 		 */
554 		opf |= REQ_ALLOC_CACHE;
555 		bio = bio_alloc_percpu_cache(bs);
556 	} else {
557 		opf &= ~REQ_ALLOC_CACHE;
558 	}
559 
560 	/*
561 	 * For a bioset without a percpu cache, or when the percpu cache was
562 	 * empty, try a slab allocation with optimistic GFP_ flags before
563 	 * falling back to the mempool.
564 	 */
565 	if (!bio) {
566 		p = kmem_cache_alloc(bs->bio_slab, gfp);
567 		if (p)
568 			bio = p + bs->front_pad;
569 	}
570 
571 	if (bio && nr_vecs > BIO_INLINE_VECS) {
572 		struct biovec_slab *bvs = biovec_slab(nr_vecs);
573 
574 		/*
575 		 * Upgrade nr_vecs to take full advantage of the allocation.
576 		 * We also rely on this in bio_free().
577 		 */
578 		nr_vecs = bvs->nr_vecs;
579 		bvecs = kmem_cache_alloc(bvs->slab, gfp);
580 		if (unlikely(!bvecs)) {
581 			kmem_cache_free(bs->bio_slab, p);
582 			bio = NULL;
583 		}
584 	}
585 
586 	if (unlikely(!bio)) {
587 		/*
588 		 * Give up if we are not allow to sleep as non-blocking mempool
589 		 * allocations just go back to the slab allocation.
590 		 */
591 		if (!(saved_gfp & __GFP_DIRECT_RECLAIM))
592 			return NULL;
593 
594 		punt_bios_to_rescuer(bs);
595 
596 		/*
597 		 * Don't rob the mempools by returning to the per-CPU cache if
598 		 * we're tight on memory.
599 		 */
600 		opf &= ~REQ_ALLOC_CACHE;
601 
602 		p = mempool_alloc(&bs->bio_pool, saved_gfp);
603 		bio = p + bs->front_pad;
604 		if (nr_vecs > BIO_INLINE_VECS) {
605 			nr_vecs = BIO_MAX_VECS;
606 			bvecs = mempool_alloc(&bs->bvec_pool, saved_gfp);
607 		}
608 	}
609 
610 	if (nr_vecs && nr_vecs <= BIO_INLINE_VECS)
611 		bio_init_inline(bio, bdev, nr_vecs, opf);
612 	else
613 		bio_init(bio, bdev, bvecs, nr_vecs, opf);
614 	bio->bi_pool = bs;
615 	return bio;
616 }
617 EXPORT_SYMBOL(bio_alloc_bioset);
618 
619 /**
620  * bio_kmalloc - kmalloc a bio
621  * @nr_vecs:	number of bio_vecs to allocate
622  * @gfp_mask:   the GFP_* mask given to the slab allocator
623  *
624  * Use kmalloc to allocate a bio (including bvecs).  The bio must be initialized
625  * using bio_init() before use.  To free a bio returned from this function use
626  * kfree() after calling bio_uninit().  A bio returned from this function can
627  * be reused by calling bio_uninit() before calling bio_init() again.
628  *
629  * Note that unlike bio_alloc() or bio_alloc_bioset() allocations from this
630  * function are not backed by a mempool can fail.  Do not use this function
631  * for allocations in the file system I/O path.
632  *
633  * Returns: Pointer to new bio on success, NULL on failure.
634  */
bio_kmalloc(unsigned short nr_vecs,gfp_t gfp_mask)635 struct bio *bio_kmalloc(unsigned short nr_vecs, gfp_t gfp_mask)
636 {
637 	struct bio *bio;
638 
639 	if (nr_vecs > BIO_MAX_INLINE_VECS)
640 		return NULL;
641 	return kmalloc(sizeof(*bio) + nr_vecs * sizeof(struct bio_vec),
642 			gfp_mask);
643 }
644 EXPORT_SYMBOL(bio_kmalloc);
645 
zero_fill_bio(struct bio * bio)646 void zero_fill_bio(struct bio *bio)
647 {
648 	struct bio_vec bv;
649 	struct bvec_iter iter;
650 
651 	bio_for_each_segment(bv, bio, iter)
652 		memzero_bvec(&bv);
653 }
654 EXPORT_SYMBOL(zero_fill_bio);
655 
656 /**
657  * bio_truncate - truncate the bio to small size of @new_size
658  * @bio:	the bio to be truncated
659  * @new_size:	new size for truncating the bio
660  *
661  * Description:
662  *   Truncate the bio to new size of @new_size. If bio_op(bio) is
663  *   REQ_OP_READ, zero the truncated part. This function should only
664  *   be used for handling corner cases, such as bio eod.
665  */
bio_truncate(struct bio * bio,unsigned new_size)666 static void bio_truncate(struct bio *bio, unsigned new_size)
667 {
668 	struct bio_vec bv;
669 	struct bvec_iter iter;
670 	unsigned int done = 0;
671 	bool truncated = false;
672 
673 	if (new_size >= bio->bi_iter.bi_size)
674 		return;
675 
676 	if (bio_op(bio) != REQ_OP_READ)
677 		goto exit;
678 
679 	bio_for_each_segment(bv, bio, iter) {
680 		if (done + bv.bv_len > new_size) {
681 			size_t offset;
682 
683 			if (!truncated)
684 				offset = new_size - done;
685 			else
686 				offset = 0;
687 			memzero_page(bv.bv_page, bv.bv_offset + offset,
688 				  bv.bv_len - offset);
689 			truncated = true;
690 		}
691 		done += bv.bv_len;
692 	}
693 
694  exit:
695 	/*
696 	 * Don't touch bvec table here and make it really immutable, since
697 	 * fs bio user has to retrieve all pages via bio_for_each_segment_all
698 	 * in its .end_bio() callback.
699 	 *
700 	 * It is enough to truncate bio by updating .bi_size since we can make
701 	 * correct bvec with the updated .bi_size for drivers.
702 	 */
703 	bio->bi_iter.bi_size = new_size;
704 }
705 
706 /**
707  * guard_bio_eod - truncate a BIO to fit the block device
708  * @bio:	bio to truncate
709  *
710  * This allows us to do IO even on the odd last sectors of a device, even if the
711  * block size is some multiple of the physical sector size.
712  *
713  * We'll just truncate the bio to the size of the device, and clear the end of
714  * the buffer head manually.  Truly out-of-range accesses will turn into actual
715  * I/O errors, this only handles the "we need to be able to do I/O at the final
716  * sector" case.
717  */
guard_bio_eod(struct bio * bio)718 void guard_bio_eod(struct bio *bio)
719 {
720 	sector_t maxsector = bdev_nr_sectors(bio->bi_bdev);
721 
722 	if (!maxsector)
723 		return;
724 
725 	/*
726 	 * If the *whole* IO is past the end of the device,
727 	 * let it through, and the IO layer will turn it into
728 	 * an EIO.
729 	 */
730 	if (unlikely(bio->bi_iter.bi_sector >= maxsector))
731 		return;
732 
733 	maxsector -= bio->bi_iter.bi_sector;
734 	if (likely((bio->bi_iter.bi_size >> 9) <= maxsector))
735 		return;
736 
737 	bio_truncate(bio, maxsector << 9);
738 }
739 
__bio_alloc_cache_prune(struct bio_alloc_cache * cache,unsigned int nr)740 static int __bio_alloc_cache_prune(struct bio_alloc_cache *cache,
741 				   unsigned int nr)
742 {
743 	unsigned int i = 0;
744 	struct bio *bio;
745 
746 	while ((bio = cache->free_list) != NULL) {
747 		cache->free_list = bio->bi_next;
748 		cache->nr--;
749 		kmemleak_alloc(bio_slab_addr(bio),
750 			       kmem_cache_size(bio->bi_pool->bio_slab),
751 			       1, GFP_KERNEL);
752 		bio_free(bio);
753 		if (++i == nr)
754 			break;
755 	}
756 	return i;
757 }
758 
bio_alloc_cache_prune(struct bio_alloc_cache * cache,unsigned int nr)759 static void bio_alloc_cache_prune(struct bio_alloc_cache *cache,
760 				  unsigned int nr)
761 {
762 	nr -= __bio_alloc_cache_prune(cache, nr);
763 	if (!READ_ONCE(cache->free_list)) {
764 		bio_alloc_irq_cache_splice(cache);
765 		__bio_alloc_cache_prune(cache, nr);
766 	}
767 }
768 
bio_cpu_dead(unsigned int cpu,struct hlist_node * node)769 static int bio_cpu_dead(unsigned int cpu, struct hlist_node *node)
770 {
771 	struct bio_set *bs;
772 
773 	bs = hlist_entry_safe(node, struct bio_set, cpuhp_dead);
774 	if (bs->cache) {
775 		struct bio_alloc_cache *cache = per_cpu_ptr(bs->cache, cpu);
776 
777 		bio_alloc_cache_prune(cache, -1U);
778 	}
779 	return 0;
780 }
781 
bio_alloc_cache_destroy(struct bio_set * bs)782 static void bio_alloc_cache_destroy(struct bio_set *bs)
783 {
784 	int cpu;
785 
786 	if (!bs->cache)
787 		return;
788 
789 	cpuhp_state_remove_instance_nocalls(CPUHP_BIO_DEAD, &bs->cpuhp_dead);
790 	for_each_possible_cpu(cpu) {
791 		struct bio_alloc_cache *cache;
792 
793 		cache = per_cpu_ptr(bs->cache, cpu);
794 		bio_alloc_cache_prune(cache, -1U);
795 	}
796 	free_percpu(bs->cache);
797 	bs->cache = NULL;
798 }
799 
bio_put_percpu_cache(struct bio * bio)800 static inline void bio_put_percpu_cache(struct bio *bio)
801 {
802 	struct bio_alloc_cache *cache;
803 
804 	cache = per_cpu_ptr(bio->bi_pool->cache, get_cpu());
805 	if (READ_ONCE(cache->nr_irq) + cache->nr > ALLOC_CACHE_MAX)
806 		goto out_free;
807 
808 	if (in_task()) {
809 		bio_uninit(bio);
810 		bio->bi_next = cache->free_list;
811 		/* Not necessary but helps not to iopoll already freed bios */
812 		bio->bi_bdev = NULL;
813 		cache->free_list = bio;
814 		cache->nr++;
815 		kmemleak_free(bio_slab_addr(bio));
816 	} else if (in_hardirq()) {
817 		lockdep_assert_irqs_disabled();
818 
819 		bio_uninit(bio);
820 		bio->bi_next = cache->free_list_irq;
821 		cache->free_list_irq = bio;
822 		cache->nr_irq++;
823 		kmemleak_free(bio_slab_addr(bio));
824 	} else {
825 		goto out_free;
826 	}
827 	put_cpu();
828 	return;
829 out_free:
830 	put_cpu();
831 	bio_free(bio);
832 }
833 
834 /**
835  * bio_put - release a reference to a bio
836  * @bio:   bio to release reference to
837  *
838  * Description:
839  *   Put a reference to a &struct bio, either one you have gotten with
840  *   bio_alloc, bio_get or bio_clone_*. The last put of a bio will free it.
841  **/
bio_put(struct bio * bio)842 void bio_put(struct bio *bio)
843 {
844 	if (unlikely(bio_flagged(bio, BIO_REFFED))) {
845 		BUG_ON(!atomic_read(&bio->__bi_cnt));
846 		if (!atomic_dec_and_test(&bio->__bi_cnt))
847 			return;
848 	}
849 	if (bio->bi_opf & REQ_ALLOC_CACHE)
850 		bio_put_percpu_cache(bio);
851 	else
852 		bio_free(bio);
853 }
854 EXPORT_SYMBOL(bio_put);
855 
__bio_clone(struct bio * bio,struct bio * bio_src,gfp_t gfp)856 static int __bio_clone(struct bio *bio, struct bio *bio_src, gfp_t gfp)
857 {
858 	bio_set_flag(bio, BIO_CLONED);
859 	bio->bi_ioprio = bio_src->bi_ioprio;
860 	bio->bi_write_hint = bio_src->bi_write_hint;
861 	bio->bi_write_stream = bio_src->bi_write_stream;
862 	bio->bi_bvec_gap_bit = bio_src->bi_bvec_gap_bit;
863 	bio->bi_iter = bio_src->bi_iter;
864 	bio->bi_io_vec = bio_src->bi_io_vec;
865 
866 	if (bio->bi_bdev) {
867 		if (bio->bi_bdev == bio_src->bi_bdev &&
868 		    bio_flagged(bio_src, BIO_REMAPPED))
869 			bio_set_flag(bio, BIO_REMAPPED);
870 		bio_clone_blkg_association(bio, bio_src);
871 	}
872 
873 	if (bio_crypt_clone(bio, bio_src, gfp) < 0)
874 		return -ENOMEM;
875 	if (bio_integrity(bio_src) &&
876 	    bio_integrity_clone(bio, bio_src, gfp) < 0)
877 		return -ENOMEM;
878 	return 0;
879 }
880 
881 /**
882  * bio_alloc_clone - clone a bio that shares the original bio's biovec
883  * @bdev: block_device to clone onto
884  * @bio_src: bio to clone from
885  * @gfp: allocation priority
886  * @bs: bio_set to allocate from
887  *
888  * Allocate a new bio that is a clone of @bio_src. This reuses the bio_vecs
889  * pointed to by @bio_src->bi_io_vec, and clones the iterator pointing to
890  * the current position in it.  The caller owns the returned bio, but not
891  * the bio_vecs, and must ensure the bio is freed before the memory
892  * pointed to by @bio_Src->bi_io_vecs.
893  */
bio_alloc_clone(struct block_device * bdev,struct bio * bio_src,gfp_t gfp,struct bio_set * bs)894 struct bio *bio_alloc_clone(struct block_device *bdev, struct bio *bio_src,
895 		gfp_t gfp, struct bio_set *bs)
896 {
897 	struct bio *bio;
898 
899 	bio = bio_alloc_bioset(bdev, 0, bio_src->bi_opf, gfp, bs);
900 	if (!bio)
901 		return NULL;
902 
903 	if (__bio_clone(bio, bio_src, gfp) < 0) {
904 		bio_put(bio);
905 		return NULL;
906 	}
907 	return bio;
908 }
909 EXPORT_SYMBOL(bio_alloc_clone);
910 
911 /**
912  * bio_init_clone - clone a bio that shares the original bio's biovec
913  * @bdev: block_device to clone onto
914  * @bio: bio to clone into
915  * @bio_src: bio to clone from
916  * @gfp: allocation priority
917  *
918  * Initialize a new bio in caller provided memory that is a clone of @bio_src.
919  * The same bio_vecs reuse and bio lifetime rules as bio_alloc_clone() apply.
920  */
bio_init_clone(struct block_device * bdev,struct bio * bio,struct bio * bio_src,gfp_t gfp)921 int bio_init_clone(struct block_device *bdev, struct bio *bio,
922 		struct bio *bio_src, gfp_t gfp)
923 {
924 	int ret;
925 
926 	bio_init(bio, bdev, NULL, 0, bio_src->bi_opf);
927 	ret = __bio_clone(bio, bio_src, gfp);
928 	if (ret)
929 		bio_uninit(bio);
930 	return ret;
931 }
932 EXPORT_SYMBOL(bio_init_clone);
933 
934 /**
935  * bio_full - check if the bio is full
936  * @bio:	bio to check
937  * @len:	length of one segment to be added
938  *
939  * Return true if @bio is full and one segment with @len bytes can't be
940  * added to the bio, otherwise return false
941  */
bio_full(struct bio * bio,unsigned len)942 static inline bool bio_full(struct bio *bio, unsigned len)
943 {
944 	if (bio->bi_vcnt >= bio->bi_max_vecs)
945 		return true;
946 	if (bio->bi_iter.bi_size > BIO_MAX_SIZE - len)
947 		return true;
948 	return false;
949 }
950 
bvec_try_merge_page(struct bio_vec * bv,struct page * page,unsigned int len,unsigned int off)951 static bool bvec_try_merge_page(struct bio_vec *bv, struct page *page,
952 		unsigned int len, unsigned int off)
953 {
954 	size_t bv_end = bv->bv_offset + bv->bv_len;
955 	phys_addr_t vec_end_addr = page_to_phys(bv->bv_page) + bv_end - 1;
956 	phys_addr_t page_addr = page_to_phys(page);
957 
958 	if (vec_end_addr + 1 != page_addr + off)
959 		return false;
960 	if (xen_domain() && !xen_biovec_phys_mergeable(bv, page))
961 		return false;
962 
963 	if ((vec_end_addr & PAGE_MASK) != ((page_addr + off) & PAGE_MASK)) {
964 		if (IS_ENABLED(CONFIG_KMSAN))
965 			return false;
966 		if (bv->bv_page + bv_end / PAGE_SIZE != page + off / PAGE_SIZE)
967 			return false;
968 	}
969 
970 	bv->bv_len += len;
971 	return true;
972 }
973 
974 /*
975  * Try to merge a page into a segment, while obeying the hardware segment
976  * size limit.
977  *
978  * This is kept around for the integrity metadata, which is still tries
979  * to build the initial bio to the hardware limit and doesn't have proper
980  * helpers to split.  Hopefully this will go away soon.
981  */
bvec_try_merge_hw_page(struct request_queue * q,struct bio_vec * bv,struct page * page,unsigned len,unsigned offset)982 bool bvec_try_merge_hw_page(struct request_queue *q, struct bio_vec *bv,
983 		struct page *page, unsigned len, unsigned offset)
984 {
985 	unsigned long mask = queue_segment_boundary(q);
986 	phys_addr_t addr1 = bvec_phys(bv);
987 	phys_addr_t addr2 = page_to_phys(page) + offset + len - 1;
988 
989 	if ((addr1 | mask) != (addr2 | mask))
990 		return false;
991 	if (len > queue_max_segment_size(q) - bv->bv_len)
992 		return false;
993 	return bvec_try_merge_page(bv, page, len, offset);
994 }
995 
996 /**
997  * __bio_add_page - add page(s) to a bio in a new segment
998  * @bio: destination bio
999  * @page: start page to add
1000  * @len: length of the data to add, may cross pages
1001  * @off: offset of the data relative to @page, may cross pages
1002  *
1003  * Add the data at @page + @off to @bio as a new bvec.  The caller must ensure
1004  * that @bio has space for another bvec.
1005  */
__bio_add_page(struct bio * bio,struct page * page,unsigned int len,unsigned int off)1006 void __bio_add_page(struct bio *bio, struct page *page,
1007 		unsigned int len, unsigned int off)
1008 {
1009 	WARN_ON_ONCE(bio_flagged(bio, BIO_CLONED));
1010 	WARN_ON_ONCE(bio_full(bio, len));
1011 
1012 	if (is_pci_p2pdma_page(page))
1013 		bio->bi_opf |= REQ_NOMERGE;
1014 
1015 	bvec_set_page(&bio->bi_io_vec[bio->bi_vcnt], page, len, off);
1016 	bio->bi_iter.bi_size += len;
1017 	bio->bi_vcnt++;
1018 }
1019 EXPORT_SYMBOL_GPL(__bio_add_page);
1020 
1021 /**
1022  * bio_add_virt_nofail - add data in the direct kernel mapping to a bio
1023  * @bio: destination bio
1024  * @vaddr: data to add
1025  * @len: length of the data to add, may cross pages
1026  *
1027  * Add the data at @vaddr to @bio.  The caller must have ensure a segment
1028  * is available for the added data.  No merging into an existing segment
1029  * will be performed.
1030  */
bio_add_virt_nofail(struct bio * bio,void * vaddr,unsigned len)1031 void bio_add_virt_nofail(struct bio *bio, void *vaddr, unsigned len)
1032 {
1033 	__bio_add_page(bio, virt_to_page(vaddr), len, offset_in_page(vaddr));
1034 }
1035 EXPORT_SYMBOL_GPL(bio_add_virt_nofail);
1036 
1037 /**
1038  *	bio_add_page	-	attempt to add page(s) to bio
1039  *	@bio: destination bio
1040  *	@page: start page to add
1041  *	@len: vec entry length, may cross pages
1042  *	@offset: vec entry offset relative to @page, may cross pages
1043  *
1044  *	Attempt to add page(s) to the bio_vec maplist. This will only fail
1045  *	if either bio->bi_vcnt == bio->bi_max_vecs or it's a cloned bio.
1046  */
bio_add_page(struct bio * bio,struct page * page,unsigned int len,unsigned int offset)1047 int bio_add_page(struct bio *bio, struct page *page,
1048 		 unsigned int len, unsigned int offset)
1049 {
1050 	if (WARN_ON_ONCE(bio_flagged(bio, BIO_CLONED)))
1051 		return 0;
1052 	if (WARN_ON_ONCE(len == 0))
1053 		return 0;
1054 	if (bio->bi_iter.bi_size > BIO_MAX_SIZE - len)
1055 		return 0;
1056 
1057 	if (bio->bi_vcnt > 0) {
1058 		struct bio_vec *bv = &bio->bi_io_vec[bio->bi_vcnt - 1];
1059 
1060 		if (!zone_device_pages_compatible(bv->bv_page, page))
1061 			return 0;
1062 		if (zone_device_pages_have_same_pgmap(bv->bv_page, page) &&
1063 		    bvec_try_merge_page(bv, page, len, offset)) {
1064 			bio->bi_iter.bi_size += len;
1065 			return len;
1066 		}
1067 	}
1068 
1069 	if (bio->bi_vcnt >= bio->bi_max_vecs)
1070 		return 0;
1071 	__bio_add_page(bio, page, len, offset);
1072 	return len;
1073 }
1074 EXPORT_SYMBOL(bio_add_page);
1075 
bio_add_folio_nofail(struct bio * bio,struct folio * folio,size_t len,size_t off)1076 void bio_add_folio_nofail(struct bio *bio, struct folio *folio, size_t len,
1077 			  size_t off)
1078 {
1079 	unsigned long nr = off / PAGE_SIZE;
1080 
1081 	WARN_ON_ONCE(len > BIO_MAX_SIZE);
1082 	__bio_add_page(bio, folio_page(folio, nr), len, off % PAGE_SIZE);
1083 }
1084 EXPORT_SYMBOL_GPL(bio_add_folio_nofail);
1085 
1086 /**
1087  * bio_add_folio - Attempt to add part of a folio to a bio.
1088  * @bio: BIO to add to.
1089  * @folio: Folio to add.
1090  * @len: How many bytes from the folio to add.
1091  * @off: First byte in this folio to add.
1092  *
1093  * Filesystems that use folios can call this function instead of calling
1094  * bio_add_page() for each page in the folio.  If @off is bigger than
1095  * PAGE_SIZE, this function can create a bio_vec that starts in a page
1096  * after the bv_page.  BIOs do not support folios that are 4GiB or larger.
1097  *
1098  * Return: Whether the addition was successful.
1099  */
bio_add_folio(struct bio * bio,struct folio * folio,size_t len,size_t off)1100 bool bio_add_folio(struct bio *bio, struct folio *folio, size_t len,
1101 		   size_t off)
1102 {
1103 	unsigned long nr = off / PAGE_SIZE;
1104 
1105 	if (len > BIO_MAX_SIZE)
1106 		return false;
1107 	return bio_add_page(bio, folio_page(folio, nr), len, off % PAGE_SIZE) > 0;
1108 }
1109 EXPORT_SYMBOL(bio_add_folio);
1110 
1111 /**
1112  * bio_add_vmalloc_chunk - add a vmalloc chunk to a bio
1113  * @bio: destination bio
1114  * @vaddr: vmalloc address to add
1115  * @len: total length in bytes of the data to add
1116  *
1117  * Add data starting at @vaddr to @bio and return how many bytes were added.
1118  * This may be less than the amount originally asked.  Returns 0 if no data
1119  * could be added to @bio.
1120  *
1121  * This helper calls flush_kernel_vmap_range() for the range added.  For reads
1122  * the caller still needs to manually call invalidate_kernel_vmap_range() in
1123  * the completion handler.
1124  */
bio_add_vmalloc_chunk(struct bio * bio,void * vaddr,unsigned len)1125 unsigned int bio_add_vmalloc_chunk(struct bio *bio, void *vaddr, unsigned len)
1126 {
1127 	unsigned int offset = offset_in_page(vaddr);
1128 
1129 	len = min(len, PAGE_SIZE - offset);
1130 	if (bio_add_page(bio, vmalloc_to_page(vaddr), len, offset) < len)
1131 		return 0;
1132 	if (op_is_write(bio_op(bio)))
1133 		flush_kernel_vmap_range(vaddr, len);
1134 	return len;
1135 }
1136 EXPORT_SYMBOL_GPL(bio_add_vmalloc_chunk);
1137 
1138 /**
1139  * bio_add_vmalloc - add a vmalloc region to a bio
1140  * @bio: destination bio
1141  * @vaddr: vmalloc address to add
1142  * @len: total length in bytes of the data to add
1143  *
1144  * Add data starting at @vaddr to @bio.  Return %true on success or %false if
1145  * @bio does not have enough space for the payload.
1146  *
1147  * This helper calls flush_kernel_vmap_range() for the range added.  For reads
1148  * the caller still needs to manually call invalidate_kernel_vmap_range() in
1149  * the completion handler.
1150  */
bio_add_vmalloc(struct bio * bio,void * vaddr,unsigned int len)1151 bool bio_add_vmalloc(struct bio *bio, void *vaddr, unsigned int len)
1152 {
1153 	do {
1154 		unsigned int added = bio_add_vmalloc_chunk(bio, vaddr, len);
1155 
1156 		if (!added)
1157 			return false;
1158 		vaddr += added;
1159 		len -= added;
1160 	} while (len);
1161 
1162 	return true;
1163 }
1164 EXPORT_SYMBOL_GPL(bio_add_vmalloc);
1165 
__bio_release_pages(struct bio * bio,bool mark_dirty)1166 void __bio_release_pages(struct bio *bio, bool mark_dirty)
1167 {
1168 	struct folio_iter fi;
1169 
1170 	bio_for_each_folio_all(fi, bio) {
1171 		size_t nr_pages;
1172 
1173 		if (mark_dirty) {
1174 			folio_lock(fi.folio);
1175 			folio_mark_dirty(fi.folio);
1176 			folio_unlock(fi.folio);
1177 		}
1178 		nr_pages = (fi.offset + fi.length - 1) / PAGE_SIZE -
1179 			   fi.offset / PAGE_SIZE + 1;
1180 		unpin_user_folio(fi.folio, nr_pages);
1181 	}
1182 }
1183 EXPORT_SYMBOL_GPL(__bio_release_pages);
1184 
bio_iov_iter_set(struct bio * bio,const struct iov_iter * iter)1185 bool bio_iov_iter_set(struct bio *bio, const struct iov_iter *iter)
1186 {
1187 	if (!iov_iter_is_bvec(iter))
1188 		return false;
1189 
1190 	WARN_ON_ONCE(bio->bi_max_vecs);
1191 
1192 	bio->bi_io_vec = (struct bio_vec *)iter->bvec;
1193 	bio->bi_iter.bi_idx = 0;
1194 	bio->bi_iter.bi_offset = iter->iov_offset;
1195 	bio->bi_iter.bi_size = iov_iter_count(iter);
1196 	bio_set_flag(bio, BIO_CLONED);
1197 	return true;
1198 }
1199 
1200 /*
1201  * Aligns the bio size to the len_align_mask, releasing excessive bio vecs that
1202  * __bio_iov_iter_get_pages may have inserted, and reverts the trimmed length
1203  * for the next iteration.
1204  */
bio_iov_iter_align_down(struct bio * bio,struct iov_iter * iter,struct bio_vec * bv,unsigned len_align_mask)1205 static int bio_iov_iter_align_down(struct bio *bio, struct iov_iter *iter,
1206 				   struct bio_vec *bv, unsigned len_align_mask)
1207 {
1208 	size_t nbytes = bio->bi_iter.bi_size & len_align_mask;
1209 
1210 	if (!nbytes)
1211 		return 0;
1212 
1213 	iov_iter_revert(iter, nbytes);
1214 	bio->bi_iter.bi_size -= nbytes;
1215 	while (nbytes >= bv->bv_len) {
1216 		if (bio_flagged(bio, BIO_PAGE_PINNED))
1217 			unpin_user_page(bv->bv_page);
1218 
1219 		if (!--bio->bi_vcnt)
1220 			return -EFAULT;
1221 		nbytes -= bv->bv_len;
1222 		bv--;
1223 	}
1224 	bv->bv_len -= nbytes;
1225 	return 0;
1226 }
1227 
1228 #ifdef CONFIG_DEBUG_KERNEL
bio_iov_bvec_aligned(const struct bio * bio,unsigned mem_align_mask)1229 static inline bool bio_iov_bvec_aligned(const struct bio *bio,
1230 					unsigned mem_align_mask)
1231 {
1232 	struct bvec_iter iter;
1233 	struct bio_vec bv;
1234 
1235 	/*
1236 	 * Correct callers never break the alignment requirements, so this
1237 	 * exhaustive check is only paid for in debug builds.
1238 	 */
1239 	for_each_mp_bvec(bv, bio->bi_io_vec, iter, bio->bi_iter)
1240 		if ((bv.bv_offset | bv.bv_len) & mem_align_mask)
1241 			return false;
1242 	return true;
1243 }
1244 #else
bio_iov_bvec_aligned(const struct bio * bio,unsigned mem_align_mask)1245 static inline bool bio_iov_bvec_aligned(const struct bio *bio,
1246 					unsigned mem_align_mask)
1247 {
1248 	/*
1249 	 * We forward the bio_vec as-is, so ITER_BVEC callers must provide
1250 	 * segments already aligned to the device's DMA alignment. The only
1251 	 * unchecked user-controllable offset that reaches here is an io_uring
1252 	 * registered buffer where just the first segment can be unaligned
1253 	 * (the rest is virtually contiguous), so checking only that one is
1254 	 * sufficient to know if the entire vector is valid.
1255 	 */
1256 	return !(mp_bvec_iter_offset(bio->bi_io_vec, bio->bi_iter) &
1257 							mem_align_mask);
1258 }
1259 #endif
1260 
1261 /**
1262  * bio_iov_iter_get_pages - add user or kernel pages to a bio
1263  * @bio: bio to add pages to
1264  * @iter: iov iterator describing the region to be added
1265  * @mem_align_mask: the mask the source address and length must be aligned to,
1266  *	0 for no requirement
1267  * @len_align_mask: the mask to align the total size to, 0 for any length
1268  *
1269  * This takes either an iterator pointing to user memory, or one pointing to
1270  * kernel pages (BVEC iterator). If we're adding user pages, we pin them and
1271  * map them into the kernel. On IO completion, the caller should put those
1272  * pages. For bvec based iterators bio_iov_iter_get_pages() uses the provided
1273  * bvecs rather than copying them. Hence anyone issuing kiocb based IO needs
1274  * to ensure the bvecs and pages stay referenced until the submitted I/O is
1275  * completed by a call to ->ki_complete() or returns with an error other than
1276  * -EIOCBQUEUED. The caller needs to check if the bio is flagged BIO_NO_PAGE_REF
1277  * on IO completion. If it isn't, then pages should be released.
1278  *
1279  * The function tries, but does not guarantee, to pin as many pages as
1280  * fit into the bio, or are requested in @iter, whatever is smaller. If
1281  * MM encounters an error pinning the requested pages, it stops. Error
1282  * is returned only if 0 pages could be pinned.
1283  */
bio_iov_iter_get_pages(struct bio * bio,struct iov_iter * iter,unsigned mem_align_mask,unsigned len_align_mask)1284 int bio_iov_iter_get_pages(struct bio *bio, struct iov_iter *iter,
1285 			   unsigned mem_align_mask, unsigned len_align_mask)
1286 {
1287 	iov_iter_extraction_t flags = 0;
1288 
1289 	if (WARN_ON_ONCE(bio_flagged(bio, BIO_CLONED)))
1290 		return -EIO;
1291 
1292 	if (bio_iov_iter_set(bio, iter)) {
1293 		if (iov_iter_is_bvec(iter) &&
1294 		    !bio_iov_bvec_aligned(bio, mem_align_mask))
1295 			return -EINVAL;
1296 
1297 		iov_iter_advance(iter, bio->bi_iter.bi_size);
1298 		return 0;
1299 	}
1300 
1301 	if (iov_iter_extract_will_pin(iter))
1302 		bio_set_flag(bio, BIO_PAGE_PINNED);
1303 	if (bio->bi_bdev && blk_queue_pci_p2pdma(bio->bi_bdev->bd_disk->queue))
1304 		flags |= ITER_ALLOW_P2PDMA;
1305 
1306 	do {
1307 		ssize_t ret;
1308 
1309 		ret = iov_iter_extract_bvecs(iter, bio->bi_io_vec,
1310 				BIO_MAX_SIZE - bio->bi_iter.bi_size,
1311 				&bio->bi_vcnt, bio->bi_max_vecs,
1312 				mem_align_mask, flags);
1313 		if (ret <= 0) {
1314 			/*
1315 			 * A misaligned vector fails the whole I/O.  Release any
1316 			 * pages pinned by earlier iterations before returning
1317 			 * since this bio won't be submitted to release them.
1318 			 */
1319 			if (ret == -EINVAL) {
1320 				bio_release_pages(bio, false);
1321 				bio_clear_flag(bio, BIO_PAGE_PINNED);
1322 				bio->bi_vcnt = 0;
1323 			}
1324 			if (!bio->bi_vcnt)
1325 				return ret;
1326 			break;
1327 		}
1328 		bio->bi_iter.bi_size += ret;
1329 	} while (iov_iter_count(iter) && !bio_full(bio, 0));
1330 
1331 	if (is_pci_p2pdma_page(bio->bi_io_vec->bv_page))
1332 		bio->bi_opf |= REQ_NOMERGE;
1333 	return bio_iov_iter_align_down(bio, iter,
1334 			&bio->bi_io_vec[bio->bi_vcnt - 1], len_align_mask);
1335 }
1336 
folio_alloc_greedy(gfp_t gfp,size_t * size,size_t minsize)1337 static struct folio *folio_alloc_greedy(gfp_t gfp, size_t *size,
1338 		size_t minsize)
1339 {
1340 	struct folio *folio;
1341 
1342 	while (*size > minsize) {
1343 		folio = folio_alloc(gfp | __GFP_NORETRY | __GFP_NOWARN,
1344 				    get_order(*size));
1345 		if (folio)
1346 			return folio;
1347 		*size = rounddown_pow_of_two(*size - 1);
1348 	}
1349 
1350 	return folio_alloc(gfp, get_order(*size));
1351 }
1352 
bio_free_folios(struct bio * bio)1353 static void bio_free_folios(struct bio *bio)
1354 {
1355 	struct bio_vec *bv;
1356 	int i;
1357 
1358 	bio_for_each_bvec_all(bv, bio, i) {
1359 		struct folio *folio = bvec_folio(bv);
1360 
1361 		if (!is_zero_folio(folio) && !is_huge_zero_folio(folio))
1362 			folio_put(folio);
1363 	}
1364 }
1365 
bio_iov_iter_bounce_write(struct bio * bio,struct iov_iter * iter,size_t maxlen,size_t minsize)1366 static int bio_iov_iter_bounce_write(struct bio *bio, struct iov_iter *iter,
1367 		size_t maxlen, size_t minsize)
1368 {
1369 	size_t total_len = min(maxlen, iov_iter_count(iter));
1370 
1371 	if (WARN_ON_ONCE(bio_flagged(bio, BIO_CLONED)))
1372 		return -EINVAL;
1373 	if (WARN_ON_ONCE(bio->bi_iter.bi_size))
1374 		return -EINVAL;
1375 	if (WARN_ON_ONCE(bio->bi_vcnt >= bio->bi_max_vecs))
1376 		return -EINVAL;
1377 
1378 	do {
1379 		size_t this_len = min(total_len, SZ_1M);
1380 		size_t copied;
1381 		struct folio *folio;
1382 
1383 		if (this_len > minsize * 2)
1384 			this_len = rounddown_pow_of_two(this_len);
1385 
1386 		if (bio->bi_iter.bi_size > BIO_MAX_SIZE - this_len)
1387 			break;
1388 
1389 		folio = folio_alloc_greedy(GFP_KERNEL, &this_len, minsize);
1390 		if (!folio)
1391 			break;
1392 		bio_add_folio_nofail(bio, folio, this_len, 0);
1393 
1394 		if (iter->nofault)
1395 			copied = copy_folio_from_iter_atomic(folio, 0, this_len,
1396 							     iter);
1397 		else
1398 			copied = copy_folio_from_iter(folio, 0, this_len, iter);
1399 		if (copied < this_len) {
1400 			/*
1401 			 * Need to revert the iov iter for all bytes we have
1402 			 * copied.
1403 			 *
1404 			 * However the bio size differs from the real copied
1405 			 * bytes as @this_len is queued but only advanced
1406 			 * less than that.
1407 			 * Need to compensate that for the revert.
1408 			 */
1409 			iov_iter_revert(iter, bio->bi_iter.bi_size - this_len +
1410 					copied);
1411 			bio_free_folios(bio);
1412 			return -EFAULT;
1413 		}
1414 		total_len -= this_len;
1415 	} while (total_len && bio->bi_vcnt < bio->bi_max_vecs);
1416 
1417 	if (!bio->bi_iter.bi_size)
1418 		return -ENOMEM;
1419 	return bio_iov_iter_align_down(bio, iter,
1420 			&bio->bi_io_vec[bio->bi_vcnt - 1], minsize - 1);
1421 }
1422 
bio_iov_iter_bounce_read(struct bio * bio,struct iov_iter * iter,size_t maxlen,size_t minsize)1423 static int bio_iov_iter_bounce_read(struct bio *bio, struct iov_iter *iter,
1424 		size_t maxlen, size_t minsize)
1425 {
1426 	size_t len = min3(iov_iter_count(iter), maxlen, SZ_1M);
1427 	struct folio *folio;
1428 	ssize_t ret;
1429 
1430 	folio = folio_alloc_greedy(GFP_KERNEL, &len, minsize);
1431 	if (!folio)
1432 		return -ENOMEM;
1433 
1434 	do {
1435 		ret = iov_iter_extract_bvecs(iter, bio->bi_io_vec + 1, len,
1436 				&bio->bi_vcnt, bio->bi_max_vecs - 1, 0, 0);
1437 		if (ret <= 0) {
1438 			if (!bio->bi_vcnt)
1439 				goto out_folio_put;
1440 			break;
1441 		}
1442 		len -= ret;
1443 		bio->bi_iter.bi_size += ret;
1444 	} while (len && bio->bi_vcnt < bio->bi_max_vecs - 1);
1445 
1446 	/*
1447 	 * Set the folio directly here.  The above loop has already calculated
1448 	 * the correct bi_size, and we use bi_vcnt for the user buffers.  That
1449 	 * is safe as bi_vcnt is only used by the submitter and not the actual
1450 	 * I/O path.
1451 	 */
1452 	bvec_set_folio(&bio->bi_io_vec[0], folio, bio->bi_iter.bi_size, 0);
1453 	if (iov_iter_extract_will_pin(iter))
1454 		bio_set_flag(bio, BIO_PAGE_PINNED);
1455 
1456 	/* The first vec stores the bounce buffer, so do not subtract 1 here. */
1457 	ret = bio_iov_iter_align_down(bio, iter,
1458 			&bio->bi_io_vec[bio->bi_vcnt], minsize - 1);
1459 	if (ret)
1460 		goto out_folio_put;
1461 
1462 	/* Update the bounc buffer bv_len to the aligned down size. */
1463 	bio->bi_io_vec[0].bv_len = bio->bi_iter.bi_size;
1464 	return 0;
1465 
1466 out_folio_put:
1467 	folio_put(folio);
1468 	return ret;
1469 }
1470 
1471 /**
1472  * bio_iov_iter_bounce - bounce buffer data from an iter into a bio
1473  * @bio:	bio to send
1474  * @iter:	iter to read from / write into
1475  * @maxlen:	maximum size to bounce
1476  * @minsize:	minimum folio allocation size
1477  *
1478  * Helper for direct I/O implementations that need to bounce buffer because
1479  * we need to checksum the data or perform other operations that require
1480  * consistency.  Allocates folios to back the bounce buffer, and for writes
1481  * copies the data into it.  Needs to be paired with bio_iov_iter_unbounce()
1482  * called on completion.
1483  */
bio_iov_iter_bounce(struct bio * bio,struct iov_iter * iter,size_t maxlen,size_t minsize)1484 int bio_iov_iter_bounce(struct bio *bio, struct iov_iter *iter, size_t maxlen,
1485 			size_t minsize)
1486 {
1487 	if (op_is_write(bio_op(bio)))
1488 		return bio_iov_iter_bounce_write(bio, iter, maxlen, minsize);
1489 	return bio_iov_iter_bounce_read(bio, iter, maxlen, minsize);
1490 }
1491 
bvec_unpin(struct bio_vec * bv,bool mark_dirty)1492 static void bvec_unpin(struct bio_vec *bv, bool mark_dirty)
1493 {
1494 	struct folio *folio = bvec_folio(bv);
1495 	size_t nr_pages = (bv->bv_offset + bv->bv_len - 1) / PAGE_SIZE -
1496 			bv->bv_offset / PAGE_SIZE + 1;
1497 
1498 	if (mark_dirty)
1499 		folio_mark_dirty_lock(folio);
1500 	unpin_user_folio(folio, nr_pages);
1501 }
1502 
bio_iov_iter_unbounce_read(struct bio * bio,bool is_error,bool mark_dirty)1503 static void bio_iov_iter_unbounce_read(struct bio *bio, bool is_error,
1504 		bool mark_dirty)
1505 {
1506 	unsigned int len = bio->bi_io_vec[0].bv_len;
1507 
1508 	if (likely(!is_error)) {
1509 		void *buf = bvec_virt(&bio->bi_io_vec[0]);
1510 		struct iov_iter to;
1511 
1512 		iov_iter_bvec(&to, ITER_DEST, bio->bi_io_vec + 1, bio->bi_vcnt,
1513 				len);
1514 		/* copying to pinned pages should always work */
1515 		WARN_ON_ONCE(copy_to_iter(buf, len, &to) != len);
1516 	} else {
1517 		/* No need to mark folios dirty if never copied to them */
1518 		mark_dirty = false;
1519 	}
1520 
1521 	if (bio_flagged(bio, BIO_PAGE_PINNED)) {
1522 		int i;
1523 
1524 		for (i = 0; i < bio->bi_vcnt; i++)
1525 			bvec_unpin(&bio->bi_io_vec[1 + i], mark_dirty);
1526 	}
1527 
1528 	folio_put(bvec_folio(&bio->bi_io_vec[0]));
1529 }
1530 
1531 /**
1532  * bio_iov_iter_unbounce - finish a bounce buffer operation
1533  * @bio:	completed bio
1534  * @is_error:	%true if an I/O error occurred and data should not be copied
1535  * @mark_dirty:	If %true, folios will be marked dirty.
1536  *
1537  * Helper for direct I/O implementations that need to bounce buffer because
1538  * we need to checksum the data or perform other operations that require
1539  * consistency.  Called to complete a bio set up by bio_iov_iter_bounce().
1540  * Copies data back for reads, and marks the original folios dirty if
1541  * requested and then frees the bounce buffer.
1542  */
bio_iov_iter_unbounce(struct bio * bio,bool is_error,bool mark_dirty)1543 void bio_iov_iter_unbounce(struct bio *bio, bool is_error, bool mark_dirty)
1544 {
1545 	if (op_is_write(bio_op(bio)))
1546 		bio_free_folios(bio);
1547 	else
1548 		bio_iov_iter_unbounce_read(bio, is_error, mark_dirty);
1549 }
1550 
bio_wait_end_io(struct bio * bio)1551 static void bio_wait_end_io(struct bio *bio)
1552 {
1553 	complete(bio->bi_private);
1554 }
1555 
1556 /**
1557  * bio_await - call a function on a bio, and wait until it completes
1558  * @bio:	the bio which describes the I/O
1559  * @submit:	function called to submit the bio
1560  * @priv:	private data passed to @submit
1561  *
1562  * Wait for the bio as well as any bio chained off it after executing the
1563  * passed in callback @submit.  The wait for the bio is set up before calling
1564  * @submit to ensure that the completion is captured.  If @submit is %NULL,
1565  * submit_bio() is used instead to submit the bio.
1566  *
1567  * Note: this overrides the bi_private and bi_end_io fields in the bio.
1568  */
bio_await(struct bio * bio,void * priv,void (* submit)(struct bio * bio,void * priv))1569 void bio_await(struct bio *bio, void *priv,
1570 	       void (*submit)(struct bio *bio, void *priv))
1571 {
1572 	DECLARE_COMPLETION_ONSTACK_MAP(done,
1573 			bio->bi_bdev->bd_disk->lockdep_map);
1574 
1575 	bio->bi_private = &done;
1576 	bio->bi_end_io = bio_wait_end_io;
1577 	bio->bi_opf |= REQ_SYNC;
1578 	if (submit)
1579 		submit(bio, priv);
1580 	else
1581 		submit_bio(bio);
1582 	blk_wait_io(&done);
1583 }
1584 EXPORT_SYMBOL_GPL(bio_await);
1585 
1586 /**
1587  * submit_bio_wait - submit a bio, and wait until it completes
1588  * @bio: The &struct bio which describes the I/O
1589  *
1590  * Simple wrapper around submit_bio(). Returns 0 on success, or the error from
1591  * bio_endio() on failure.
1592  *
1593  * WARNING: Unlike to how submit_bio() is usually used, this function does not
1594  * result in bio reference to be consumed. The caller must drop the reference
1595  * on his own.
1596  */
submit_bio_wait(struct bio * bio)1597 int submit_bio_wait(struct bio *bio)
1598 {
1599 	bio_await(bio, NULL, NULL);
1600 	return blk_status_to_errno(bio->bi_status);
1601 }
1602 EXPORT_SYMBOL(submit_bio_wait);
1603 
bio_endio_cb(struct bio * bio,void * priv)1604 static void bio_endio_cb(struct bio *bio, void *priv)
1605 {
1606 	bio_endio(bio);
1607 }
1608 
1609 /*
1610  * Submit @bio synchronously, or call bio_endio on it if the current process
1611  * is being killed.
1612  */
bio_submit_or_kill(struct bio * bio,unsigned int flags)1613 int bio_submit_or_kill(struct bio *bio, unsigned int flags)
1614 {
1615 	if ((flags & BLKDEV_ZERO_KILLABLE) && fatal_signal_pending(current)) {
1616 		bio_await(bio, NULL, bio_endio_cb);
1617 		return -EINTR;
1618 	}
1619 
1620 	return submit_bio_wait(bio);
1621 }
1622 
1623 /**
1624  * bdev_rw_virt - synchronously read into / write from kernel mapping
1625  * @bdev:	block device to access
1626  * @sector:	sector to access
1627  * @data:	data to read/write
1628  * @len:	length in byte to read/write
1629  * @op:		operation (e.g. REQ_OP_READ/REQ_OP_WRITE)
1630  *
1631  * Performs synchronous I/O to @bdev for @data/@len.  @data must be in
1632  * the kernel direct mapping and not a vmalloc address.
1633  */
bdev_rw_virt(struct block_device * bdev,sector_t sector,void * data,size_t len,enum req_op op)1634 int bdev_rw_virt(struct block_device *bdev, sector_t sector, void *data,
1635 		size_t len, enum req_op op)
1636 {
1637 	struct bio_vec bv;
1638 	struct bio bio;
1639 	int error;
1640 
1641 	if (WARN_ON_ONCE(is_vmalloc_addr(data)))
1642 		return -EIO;
1643 
1644 	bio_init(&bio, bdev, &bv, 1, op);
1645 	bio.bi_iter.bi_sector = sector;
1646 	bio_add_virt_nofail(&bio, data, len);
1647 	error = submit_bio_wait(&bio);
1648 	bio_uninit(&bio);
1649 	return error;
1650 }
1651 EXPORT_SYMBOL_GPL(bdev_rw_virt);
1652 
__bio_advance(struct bio * bio,unsigned bytes)1653 void __bio_advance(struct bio *bio, unsigned bytes)
1654 {
1655 	if (bio_integrity(bio))
1656 		bio_integrity_advance(bio, bytes);
1657 
1658 	bio_crypt_advance(bio, bytes);
1659 	bio_advance_iter(bio, &bio->bi_iter, bytes);
1660 }
1661 EXPORT_SYMBOL(__bio_advance);
1662 
1663 
1664 /**
1665  * bio_copy_data - copy contents of data buffers from one bio to another
1666  * @src: source bio
1667  * @dst: destination bio
1668  *
1669  * Stops when it reaches the end of either @src or @dst - that is, copies
1670  * min(src->bi_size, dst->bi_size) bytes (or the equivalent for lists of bios).
1671  */
bio_copy_data(struct bio * dst,struct bio * src)1672 void bio_copy_data(struct bio *dst, struct bio *src)
1673 {
1674 	struct bvec_iter src_iter = src->bi_iter;
1675 	struct bvec_iter dst_iter = dst->bi_iter;
1676 
1677 	while (src_iter.bi_size && dst_iter.bi_size) {
1678 		struct bio_vec src_bv = bio_iter_iovec(src, src_iter);
1679 		struct bio_vec dst_bv = bio_iter_iovec(dst, dst_iter);
1680 		unsigned int bytes = min(src_bv.bv_len, dst_bv.bv_len);
1681 		void *src_buf = bvec_kmap_local(&src_bv);
1682 		void *dst_buf = bvec_kmap_local(&dst_bv);
1683 
1684 		memcpy(dst_buf, src_buf, bytes);
1685 
1686 		kunmap_local(dst_buf);
1687 		kunmap_local(src_buf);
1688 
1689 		bio_advance_iter_single(src, &src_iter, bytes);
1690 		bio_advance_iter_single(dst, &dst_iter, bytes);
1691 	}
1692 }
1693 EXPORT_SYMBOL(bio_copy_data);
1694 
bio_free_pages(struct bio * bio)1695 void bio_free_pages(struct bio *bio)
1696 {
1697 	struct bio_vec *bvec;
1698 	struct bvec_iter_all iter_all;
1699 
1700 	bio_for_each_segment_all(bvec, bio, iter_all)
1701 		__free_page(bvec->bv_page);
1702 }
1703 EXPORT_SYMBOL(bio_free_pages);
1704 
1705 /*
1706  * bio_set_pages_dirty() and bio_check_pages_dirty() are support functions
1707  * for performing direct-IO in BIOs.
1708  *
1709  * The problem is that we cannot run folio_mark_dirty() from interrupt context
1710  * because the required locks are not interrupt-safe.  So what we can do is to
1711  * mark the pages dirty _before_ performing IO.  And in interrupt context,
1712  * check that the pages are still dirty.   If so, fine.  If not, redirty them
1713  * in process context.
1714  *
1715  * Note that this code is very hard to test under normal circumstances because
1716  * direct-io pins the pages with get_user_pages().  This makes
1717  * is_page_cache_freeable return false, and the VM will not clean the pages.
1718  * But other code (eg, flusher threads) could clean the pages if they are mapped
1719  * pagecache.
1720  *
1721  * Simply disabling the call to bio_set_pages_dirty() is a good way to test the
1722  * deferred bio dirtying paths.
1723  */
1724 
1725 /*
1726  * bio_set_pages_dirty() will mark all the bio's pages as dirty.
1727  */
bio_set_pages_dirty(struct bio * bio)1728 void bio_set_pages_dirty(struct bio *bio)
1729 {
1730 	struct folio_iter fi;
1731 
1732 	bio_for_each_folio_all(fi, bio) {
1733 		folio_lock(fi.folio);
1734 		folio_mark_dirty(fi.folio);
1735 		folio_unlock(fi.folio);
1736 	}
1737 }
1738 
1739 /*
1740  * bio_check_pages_dirty() will check that all the BIO's pages are still dirty.
1741  * If they are, then fine.  If, however, some pages are clean then they must
1742  * have been written out during the direct-IO read.  So we take another ref on
1743  * the BIO and re-dirty the pages in process context.
1744  *
1745  * It is expected that bio_check_pages_dirty() will wholly own the BIO from
1746  * here on.  It will unpin each page and will run one bio_put() against the
1747  * BIO.
1748  */
1749 
1750 static void bio_dirty_fn(struct work_struct *work);
1751 
1752 static DECLARE_WORK(bio_dirty_work, bio_dirty_fn);
1753 static DEFINE_SPINLOCK(bio_dirty_lock);
1754 static struct bio *bio_dirty_list;
1755 
1756 /*
1757  * This runs in process context
1758  */
bio_dirty_fn(struct work_struct * work)1759 static void bio_dirty_fn(struct work_struct *work)
1760 {
1761 	struct bio *bio, *next;
1762 
1763 	spin_lock_irq(&bio_dirty_lock);
1764 	next = bio_dirty_list;
1765 	bio_dirty_list = NULL;
1766 	spin_unlock_irq(&bio_dirty_lock);
1767 
1768 	while ((bio = next) != NULL) {
1769 		next = bio->bi_private;
1770 
1771 		bio_release_pages(bio, true);
1772 		bio_put(bio);
1773 	}
1774 }
1775 
bio_check_pages_dirty(struct bio * bio)1776 void bio_check_pages_dirty(struct bio *bio)
1777 {
1778 	struct folio_iter fi;
1779 	unsigned long flags;
1780 
1781 	bio_for_each_folio_all(fi, bio) {
1782 		if (!folio_test_dirty(fi.folio))
1783 			goto defer;
1784 	}
1785 
1786 	bio_release_pages(bio, false);
1787 	bio_put(bio);
1788 	return;
1789 defer:
1790 	spin_lock_irqsave(&bio_dirty_lock, flags);
1791 	bio->bi_private = bio_dirty_list;
1792 	bio_dirty_list = bio;
1793 	spin_unlock_irqrestore(&bio_dirty_lock, flags);
1794 	schedule_work(&bio_dirty_work);
1795 }
1796 
1797 /*
1798  * Infrastructure for deferring bio completions to task-context via a per-CPU
1799  * workqueue. Triggered either by the BIO_COMPLETE_IN_TASK bio flag (static
1800  * decision at submit time) or by calling bio_complete_in_task() from
1801  * bi_end_io() (dynamic decision at completion time).
1802  */
1803 
1804 struct bio_complete_batch {
1805 	struct bio_list list;
1806 	struct work_struct work;
1807 	int cpu;
1808 };
1809 
1810 static DEFINE_PER_CPU(struct bio_complete_batch, bio_complete_batch);
1811 static struct workqueue_struct *bio_complete_wq;
1812 
bio_complete_work_fn(struct work_struct * w)1813 static void bio_complete_work_fn(struct work_struct *w)
1814 {
1815 	struct bio_complete_batch *batch =
1816 		container_of(w, struct bio_complete_batch, work);
1817 
1818 	while (1) {
1819 		struct bio_list list;
1820 		struct bio *bio;
1821 
1822 		local_irq_disable();
1823 		list = batch->list;
1824 		bio_list_init(&batch->list);
1825 		local_irq_enable();
1826 
1827 		if (bio_list_empty(&list))
1828 			break;
1829 
1830 		while ((bio = bio_list_pop(&list)))
1831 			bio->bi_end_io(bio);
1832 	}
1833 }
1834 
__bio_complete_in_task(struct bio * bio)1835 void __bio_complete_in_task(struct bio *bio)
1836 {
1837 	struct bio_complete_batch *batch;
1838 	unsigned long flags;
1839 	bool was_empty;
1840 
1841 	local_irq_save(flags);
1842 	batch = this_cpu_ptr(&bio_complete_batch);
1843 	was_empty = bio_list_empty(&batch->list);
1844 	bio_list_add(&batch->list, bio);
1845 	local_irq_restore(flags);
1846 
1847 	if (was_empty)
1848 		queue_work_on(batch->cpu, bio_complete_wq, &batch->work);
1849 }
1850 EXPORT_SYMBOL_GPL(__bio_complete_in_task);
1851 
bio_remaining_done(struct bio * bio)1852 static inline bool bio_remaining_done(struct bio *bio)
1853 {
1854 	/*
1855 	 * If we're not chaining, then ->__bi_remaining is always 1 and
1856 	 * we always end io on the first invocation.
1857 	 */
1858 	if (!bio_flagged(bio, BIO_CHAIN))
1859 		return true;
1860 
1861 	BUG_ON(atomic_read(&bio->__bi_remaining) <= 0);
1862 
1863 	if (atomic_dec_and_test(&bio->__bi_remaining)) {
1864 		bio_clear_flag(bio, BIO_CHAIN);
1865 		return true;
1866 	}
1867 
1868 	return false;
1869 }
1870 
1871 /**
1872  * bio_endio - end I/O on a bio
1873  * @bio:	bio
1874  *
1875  * Description:
1876  *   bio_endio() will end I/O on the whole bio. bio_endio() is the preferred
1877  *   way to end I/O on a bio. No one should call bi_end_io() directly on a
1878  *   bio unless they own it and thus know that it has an end_io function.
1879  *
1880  *   bio_endio() can be called several times on a bio that has been chained
1881  *   using bio_chain().  The ->bi_end_io() function will only be called the
1882  *   last time.
1883  **/
bio_endio(struct bio * bio)1884 void bio_endio(struct bio *bio)
1885 {
1886 again:
1887 	if (!bio_remaining_done(bio))
1888 		return;
1889 	if (!bio_integrity_endio(bio))
1890 		return;
1891 
1892 	blk_zone_bio_endio(bio);
1893 
1894 	rq_qos_done_bio(bio);
1895 
1896 	if (bio->bi_bdev && bio_flagged(bio, BIO_TRACE_COMPLETION)) {
1897 		trace_block_bio_complete(bdev_get_queue(bio->bi_bdev), bio);
1898 		bio_clear_flag(bio, BIO_TRACE_COMPLETION);
1899 	}
1900 
1901 	/*
1902 	 * Need to have a real endio function for chained bios, otherwise
1903 	 * various corner cases will break (like stacking block devices that
1904 	 * save/restore bi_end_io) - however, we want to avoid unbounded
1905 	 * recursion and blowing the stack. Tail call optimization would
1906 	 * handle this, but compiling with frame pointers also disables
1907 	 * gcc's sibling call optimization.
1908 	 */
1909 	if (bio->bi_end_io == bio_chain_endio) {
1910 		bio = __bio_chain_endio(bio);
1911 		goto again;
1912 	}
1913 
1914 #ifdef CONFIG_BLK_CGROUP
1915 	/*
1916 	 * Release cgroup info.  We shouldn't have to do this here, but quite
1917 	 * a few callers of bio_init fail to call bio_uninit, so we cover up
1918 	 * for that here at least for now.
1919 	 */
1920 	if (bio->bi_blkg) {
1921 		blkg_put(bio->bi_blkg);
1922 		bio->bi_blkg = NULL;
1923 	}
1924 #endif
1925 
1926 	if (bio_flagged(bio, BIO_COMPLETE_IN_TASK) && bio_in_atomic())
1927 		__bio_complete_in_task(bio);
1928 	else if (bio->bi_end_io)
1929 		bio->bi_end_io(bio);
1930 }
1931 EXPORT_SYMBOL(bio_endio);
1932 
1933 /**
1934  * bio_split - split a bio
1935  * @bio:	bio to split
1936  * @sectors:	number of sectors to split from the front of @bio
1937  * @gfp:	gfp mask
1938  * @bs:		bio set to allocate from
1939  *
1940  * Allocates and returns a new bio which represents @sectors from the start of
1941  * @bio, and updates @bio to represent the remaining sectors.
1942  *
1943  * Unless this is a discard request the newly allocated bio will point
1944  * to @bio's bi_io_vec. It is the caller's responsibility to ensure that
1945  * neither @bio nor @bs are freed before the split bio.
1946  */
bio_split(struct bio * bio,int sectors,gfp_t gfp,struct bio_set * bs)1947 struct bio *bio_split(struct bio *bio, int sectors,
1948 		      gfp_t gfp, struct bio_set *bs)
1949 {
1950 	struct bio *split;
1951 
1952 	if (WARN_ON_ONCE(sectors <= 0))
1953 		return ERR_PTR(-EINVAL);
1954 	if (WARN_ON_ONCE(sectors >= bio_sectors(bio)))
1955 		return ERR_PTR(-EINVAL);
1956 
1957 	/* Zone append commands cannot be split */
1958 	if (WARN_ON_ONCE(bio_op(bio) == REQ_OP_ZONE_APPEND))
1959 		return ERR_PTR(-EINVAL);
1960 
1961 	/* atomic writes cannot be split */
1962 	if (bio->bi_opf & REQ_ATOMIC)
1963 		return ERR_PTR(-EINVAL);
1964 
1965 	split = bio_alloc_clone(bio->bi_bdev, bio, gfp, bs);
1966 	if (!split)
1967 		return ERR_PTR(-ENOMEM);
1968 
1969 	split->bi_iter.bi_size = sectors << 9;
1970 
1971 	if (bio_integrity(split))
1972 		bio_integrity_trim(split);
1973 
1974 	bio_advance(bio, split->bi_iter.bi_size);
1975 
1976 	/*
1977 	 * The gap bit is set when splitting to limits and only applies to the
1978 	 * front bio that was split off. The remaining bio will calcualte its
1979 	 * gap value when it is subsequently split to limits, so it is safe to
1980 	 * re-initialize the value back to 0.
1981 	 */
1982 	bio->bi_bvec_gap_bit = 0;
1983 
1984 	if (bio_flagged(bio, BIO_TRACE_COMPLETION))
1985 		bio_set_flag(split, BIO_TRACE_COMPLETION);
1986 
1987 	return split;
1988 }
1989 EXPORT_SYMBOL(bio_split);
1990 
1991 /**
1992  * bio_trim - trim a bio
1993  * @bio:	bio to trim
1994  * @offset:	number of sectors to trim from the front of @bio
1995  * @size:	size we want to trim @bio to, in sectors
1996  *
1997  * This function is typically used for bios that are cloned and submitted
1998  * to the underlying device in parts.
1999  */
bio_trim(struct bio * bio,sector_t offset,sector_t size)2000 void bio_trim(struct bio *bio, sector_t offset, sector_t size)
2001 {
2002 	/* We should never trim an atomic write */
2003 	if (WARN_ON_ONCE(bio->bi_opf & REQ_ATOMIC && size))
2004 		return;
2005 
2006 	if (WARN_ON_ONCE(offset > BIO_MAX_SECTORS || size > BIO_MAX_SECTORS ||
2007 			 offset + size > bio_sectors(bio)))
2008 		return;
2009 
2010 	size <<= 9;
2011 	if (offset == 0 && size == bio->bi_iter.bi_size)
2012 		return;
2013 
2014 	bio_advance(bio, offset << 9);
2015 	bio->bi_iter.bi_size = size;
2016 
2017 	if (bio_integrity(bio))
2018 		bio_integrity_trim(bio);
2019 }
2020 EXPORT_SYMBOL_GPL(bio_trim);
2021 
2022 /*
2023  * create memory pools for biovec's in a bio_set.
2024  * use the global biovec slabs created for general use.
2025  */
biovec_init_pool(mempool_t * pool,int pool_entries)2026 static int biovec_init_pool(mempool_t *pool, int pool_entries)
2027 {
2028 	struct biovec_slab *bp = bvec_slabs + ARRAY_SIZE(bvec_slabs) - 1;
2029 
2030 	return mempool_init_slab_pool(pool, pool_entries, bp->slab);
2031 }
2032 
2033 /*
2034  * bioset_exit - exit a bioset initialized with bioset_init()
2035  *
2036  * May be called on a zeroed but uninitialized bioset (i.e. allocated with
2037  * kzalloc()).
2038  */
bioset_exit(struct bio_set * bs)2039 void bioset_exit(struct bio_set *bs)
2040 {
2041 	bio_alloc_cache_destroy(bs);
2042 	if (bs->rescue_workqueue)
2043 		destroy_workqueue(bs->rescue_workqueue);
2044 	bs->rescue_workqueue = NULL;
2045 
2046 	mempool_exit(&bs->bio_pool);
2047 	mempool_exit(&bs->bvec_pool);
2048 
2049 	if (bs->bio_slab)
2050 		bio_put_slab(bs);
2051 	bs->bio_slab = NULL;
2052 }
2053 EXPORT_SYMBOL(bioset_exit);
2054 
2055 /**
2056  * bioset_init - Initialize a bio_set
2057  * @bs:		pool to initialize
2058  * @pool_size:	Number of bio and bio_vecs to cache in the mempool
2059  * @front_pad:	Number of bytes to allocate in front of the returned bio
2060  * @flags:	Flags to modify behavior, currently %BIOSET_NEED_BVECS
2061  *              and %BIOSET_NEED_RESCUER
2062  *
2063  * Description:
2064  *    Set up a bio_set to be used with @bio_alloc_bioset. Allows the caller
2065  *    to ask for a number of bytes to be allocated in front of the bio.
2066  *    Front pad allocation is useful for embedding the bio inside
2067  *    another structure, to avoid allocating extra data to go with the bio.
2068  *    Note that the bio must be embedded at the END of that structure always,
2069  *    or things will break badly.
2070  *    If %BIOSET_NEED_BVECS is set in @flags, a separate pool will be allocated
2071  *    for allocating iovecs.  This pool is not needed e.g. for bio_init_clone().
2072  *    If %BIOSET_NEED_RESCUER is set, a workqueue is created which can be used
2073  *    to dispatch queued requests when the mempool runs out of space.
2074  *
2075  */
bioset_init(struct bio_set * bs,unsigned int pool_size,unsigned int front_pad,int flags)2076 int bioset_init(struct bio_set *bs,
2077 		unsigned int pool_size,
2078 		unsigned int front_pad,
2079 		int flags)
2080 {
2081 	bs->front_pad = front_pad;
2082 	if (flags & BIOSET_NEED_BVECS)
2083 		bs->back_pad = BIO_INLINE_VECS * sizeof(struct bio_vec);
2084 	else
2085 		bs->back_pad = 0;
2086 
2087 	spin_lock_init(&bs->rescue_lock);
2088 	bio_list_init(&bs->rescue_list);
2089 	INIT_WORK(&bs->rescue_work, bio_alloc_rescue);
2090 
2091 	bs->bio_slab = bio_find_or_create_slab(bs);
2092 	if (!bs->bio_slab)
2093 		return -ENOMEM;
2094 
2095 	if (mempool_init_slab_pool(&bs->bio_pool, pool_size, bs->bio_slab))
2096 		goto bad;
2097 
2098 	if ((flags & BIOSET_NEED_BVECS) &&
2099 	    biovec_init_pool(&bs->bvec_pool, pool_size))
2100 		goto bad;
2101 
2102 	if (flags & BIOSET_NEED_RESCUER) {
2103 		bs->rescue_workqueue = alloc_workqueue("bioset",
2104 							WQ_MEM_RECLAIM | WQ_PERCPU, 0);
2105 		if (!bs->rescue_workqueue)
2106 			goto bad;
2107 	}
2108 	if (flags & BIOSET_PERCPU_CACHE) {
2109 		bs->cache = alloc_percpu(struct bio_alloc_cache);
2110 		if (!bs->cache)
2111 			goto bad;
2112 		cpuhp_state_add_instance_nocalls(CPUHP_BIO_DEAD, &bs->cpuhp_dead);
2113 	}
2114 
2115 	return 0;
2116 bad:
2117 	bioset_exit(bs);
2118 	return -ENOMEM;
2119 }
2120 EXPORT_SYMBOL(bioset_init);
2121 
bio_complete_batch_cpu_online(unsigned int cpu)2122 static int bio_complete_batch_cpu_online(unsigned int cpu)
2123 {
2124 	struct bio_complete_batch *batch = &per_cpu(bio_complete_batch, cpu);
2125 
2126 	enable_work(&batch->work);
2127 	if (!bio_list_empty(&batch->list))
2128 		queue_work_on(cpu, bio_complete_wq, &batch->work);
2129 	return 0;
2130 }
2131 
2132 /*
2133  * Disable this CPU's work item so that it cannot run on an unbound worker
2134  * after the CPU is offlined.
2135  */
bio_complete_batch_cpu_down_prep(unsigned int cpu)2136 static int bio_complete_batch_cpu_down_prep(unsigned int cpu)
2137 {
2138 	disable_work_sync(&per_cpu(bio_complete_batch, cpu).work);
2139 	return 0;
2140 }
2141 
2142 /*
2143  * Drain a dead CPU's deferred bio completions. The CPU is dead and the worker
2144  * is canceled so no locking is needed.
2145  */
bio_complete_batch_cpu_dead(unsigned int cpu)2146 static int bio_complete_batch_cpu_dead(unsigned int cpu)
2147 {
2148 	struct bio_complete_batch *batch =
2149 		per_cpu_ptr(&bio_complete_batch, cpu);
2150 	struct bio *bio;
2151 
2152 	while ((bio = bio_list_pop(&batch->list)))
2153 		bio->bi_end_io(bio);
2154 
2155 	return 0;
2156 }
2157 
bio_complete_batch_init(int cpu)2158 static void __init bio_complete_batch_init(int cpu)
2159 {
2160 	struct bio_complete_batch *batch =
2161 		per_cpu_ptr(&bio_complete_batch, cpu);
2162 
2163 	bio_list_init(&batch->list);
2164 	INIT_WORK(&batch->work, bio_complete_work_fn);
2165 	batch->cpu = cpu;
2166 
2167 	if (!cpu_online(cpu))
2168 		disable_work_sync(&batch->work);
2169 }
2170 
init_bio(void)2171 static int __init init_bio(void)
2172 {
2173 	int i;
2174 
2175 	BUILD_BUG_ON(BIO_FLAG_LAST > 8 * sizeof_field(struct bio, bi_flags));
2176 
2177 	for (i = 0; i < ARRAY_SIZE(bvec_slabs); i++) {
2178 		struct biovec_slab *bvs = bvec_slabs + i;
2179 
2180 		bvs->slab = kmem_cache_create(bvs->name,
2181 				bvs->nr_vecs * sizeof(struct bio_vec), 0,
2182 				SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL);
2183 	}
2184 
2185 	for_each_possible_cpu(i)
2186 		bio_complete_batch_init(i);
2187 
2188 	bio_complete_wq = alloc_workqueue("bio_complete",
2189 					   WQ_MEM_RECLAIM | WQ_PERCPU, 0);
2190 	if (!bio_complete_wq)
2191 		panic("bio: can't allocate bio_complete workqueue\n");
2192 
2193 	/*
2194 	 * bio task-context completion draining on hot-unplugged CPUs:
2195 	 *
2196 	 *   1. Stop the per-CPU work item while the CPU is still online, so
2197 	 *      that it cannot run on an unbound worker later.
2198 	 *   2. Drain leftover bios added between worker disabling and CPU
2199 	 *      offlining.
2200 	 */
2201 	cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
2202 				  "block/bio:complete:online",
2203 				  bio_complete_batch_cpu_online,
2204 				  bio_complete_batch_cpu_down_prep);
2205 	cpuhp_setup_state_nocalls(CPUHP_BP_PREPARE_DYN,
2206 				  "block/bio:complete:dead",
2207 				  NULL, bio_complete_batch_cpu_dead);
2208 
2209 	cpuhp_setup_state_multi(CPUHP_BIO_DEAD, "block/bio:dead", NULL,
2210 					bio_cpu_dead);
2211 
2212 	if (bioset_init(&fs_bio_set, BIO_POOL_SIZE, 0,
2213 			BIOSET_NEED_BVECS | BIOSET_PERCPU_CACHE))
2214 		panic("bio: can't allocate bios\n");
2215 
2216 	return 0;
2217 }
2218 subsys_initcall(init_bio);
2219