1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Copyright (c) 2025 Christoph Hellwig.
4 */
5 #include <linux/blk-integrity.h>
6 #include <linux/bio-integrity.h>
7 #include "blk.h"
8
9 struct fs_bio_integrity_buf {
10 struct bio_integrity_payload bip;
11 struct bio_vec bvec;
12 };
13
14 static struct kmem_cache *fs_bio_integrity_cache;
15 static mempool_t fs_bio_integrity_pool;
16
fs_bio_integrity_alloc(struct bio * bio)17 unsigned int fs_bio_integrity_alloc(struct bio *bio)
18 {
19 struct fs_bio_integrity_buf *iib;
20 unsigned int action;
21
22 action = bio_integrity_action(bio);
23 if (!action)
24 return 0;
25
26 iib = mempool_alloc(&fs_bio_integrity_pool, GFP_NOFS);
27 bio_integrity_init(bio, &iib->bip, &iib->bvec, 1);
28
29 bio_integrity_alloc_buf(bio, GFP_NOFS, action & BI_ACT_ZERO);
30 if (action & BI_ACT_CHECK)
31 bio_integrity_setup_default(bio);
32 return action;
33 }
34
fs_bio_integrity_free(struct bio * bio)35 void fs_bio_integrity_free(struct bio *bio)
36 {
37 struct bio_integrity_payload *bip = bio_integrity(bio);
38
39 bio_integrity_free_buf(bip);
40 mempool_free(container_of(bip, struct fs_bio_integrity_buf, bip),
41 &fs_bio_integrity_pool);
42
43 bio->bi_integrity = NULL;
44 bio->bi_opf &= ~REQ_INTEGRITY;
45 }
46
fs_bio_integrity_generate(struct bio * bio)47 void fs_bio_integrity_generate(struct bio *bio)
48 {
49 if (fs_bio_integrity_alloc(bio) &&
50 (bio_integrity(bio)->bip_flags & BIP_CHECK_FLAGS))
51 bio_integrity_generate(bio);
52 }
53 EXPORT_SYMBOL_GPL(fs_bio_integrity_generate);
54
fs_bio_integrity_verify(struct bio * bio,sector_t sector,unsigned int size)55 int fs_bio_integrity_verify(struct bio *bio, sector_t sector, unsigned int size)
56 {
57 struct blk_integrity *bi = blk_get_integrity(bio->bi_bdev->bd_disk);
58 struct bio_integrity_payload *bip = bio_integrity(bio);
59 struct bvec_iter data_iter = {
60 .bi_sector = sector,
61 .bi_size = size,
62 };
63
64 if (!bip || !(bip->bip_flags & BIP_CHECK_FLAGS))
65 return 0;
66
67 /*
68 * Reinitialize bip->bip_iter.
69 *
70 * This is for use in the submitter after the driver is done with the
71 * bio. Requires the submitter to remember the sector and the size.
72 */
73 memset(&bip->bip_iter, 0, sizeof(bip->bip_iter));
74 bip->bip_iter.bi_sector = sector;
75 bip->bip_iter.bi_size = bio_integrity_bytes(bi, size >> SECTOR_SHIFT);
76 return blk_status_to_errno(bio_integrity_verify(bio, &data_iter));
77 }
78
fs_bio_integrity_init(void)79 static int __init fs_bio_integrity_init(void)
80 {
81 fs_bio_integrity_cache = kmem_cache_create("fs_bio_integrity",
82 sizeof(struct fs_bio_integrity_buf), 0,
83 SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL);
84 if (mempool_init_slab_pool(&fs_bio_integrity_pool, BIO_POOL_SIZE,
85 fs_bio_integrity_cache))
86 panic("fs_bio_integrity: can't create pool\n");
87 return 0;
88 }
89 fs_initcall(fs_bio_integrity_init);
90