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