xref: /linux-6.15/block/bio-integrity.c (revision 25f76c3d)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * bio-integrity.c - bio data integrity extensions
4  *
5  * Copyright (C) 2007, 2008, 2009 Oracle Corporation
6  * Written by: Martin K. Petersen <[email protected]>
7  */
8 
9 #include <linux/blk-integrity.h>
10 #include <linux/mempool.h>
11 #include <linux/export.h>
12 #include <linux/bio.h>
13 #include <linux/workqueue.h>
14 #include <linux/slab.h>
15 #include "blk.h"
16 
17 static struct kmem_cache *bip_slab;
18 static struct workqueue_struct *kintegrityd_wq;
19 
20 void blk_flush_integrity(void)
21 {
22 	flush_workqueue(kintegrityd_wq);
23 }
24 
25 static void __bio_integrity_free(struct bio_set *bs,
26 				 struct bio_integrity_payload *bip)
27 {
28 	if (bs && mempool_initialized(&bs->bio_integrity_pool)) {
29 		if (bip->bip_vec)
30 			bvec_free(&bs->bvec_integrity_pool, bip->bip_vec,
31 				  bip->bip_max_vcnt);
32 		mempool_free(bip, &bs->bio_integrity_pool);
33 	} else {
34 		kfree(bip);
35 	}
36 }
37 
38 /**
39  * bio_integrity_alloc - Allocate integrity payload and attach it to bio
40  * @bio:	bio to attach integrity metadata to
41  * @gfp_mask:	Memory allocation mask
42  * @nr_vecs:	Number of integrity metadata scatter-gather elements
43  *
44  * Description: This function prepares a bio for attaching integrity
45  * metadata.  nr_vecs specifies the maximum number of pages containing
46  * integrity metadata that can be attached.
47  */
48 struct bio_integrity_payload *bio_integrity_alloc(struct bio *bio,
49 						  gfp_t gfp_mask,
50 						  unsigned int nr_vecs)
51 {
52 	struct bio_integrity_payload *bip;
53 	struct bio_set *bs = bio->bi_pool;
54 	unsigned inline_vecs;
55 
56 	if (WARN_ON_ONCE(bio_has_crypt_ctx(bio)))
57 		return ERR_PTR(-EOPNOTSUPP);
58 
59 	if (!bs || !mempool_initialized(&bs->bio_integrity_pool)) {
60 		bip = kmalloc(struct_size(bip, bip_inline_vecs, nr_vecs), gfp_mask);
61 		inline_vecs = nr_vecs;
62 	} else {
63 		bip = mempool_alloc(&bs->bio_integrity_pool, gfp_mask);
64 		inline_vecs = BIO_INLINE_VECS;
65 	}
66 
67 	if (unlikely(!bip))
68 		return ERR_PTR(-ENOMEM);
69 
70 	memset(bip, 0, sizeof(*bip));
71 
72 	/* always report as many vecs as asked explicitly, not inline vecs */
73 	bip->bip_max_vcnt = nr_vecs;
74 	if (nr_vecs > inline_vecs) {
75 		bip->bip_vec = bvec_alloc(&bs->bvec_integrity_pool,
76 					  &bip->bip_max_vcnt, gfp_mask);
77 		if (!bip->bip_vec)
78 			goto err;
79 	} else if (nr_vecs) {
80 		bip->bip_vec = bip->bip_inline_vecs;
81 	}
82 
83 	bip->bip_bio = bio;
84 	bio->bi_integrity = bip;
85 	bio->bi_opf |= REQ_INTEGRITY;
86 
87 	return bip;
88 err:
89 	__bio_integrity_free(bs, bip);
90 	return ERR_PTR(-ENOMEM);
91 }
92 EXPORT_SYMBOL(bio_integrity_alloc);
93 
94 static void bio_integrity_unpin_bvec(struct bio_vec *bv, int nr_vecs,
95 				     bool dirty)
96 {
97 	int i;
98 
99 	for (i = 0; i < nr_vecs; i++) {
100 		if (dirty && !PageCompound(bv[i].bv_page))
101 			set_page_dirty_lock(bv[i].bv_page);
102 		unpin_user_page(bv[i].bv_page);
103 	}
104 }
105 
106 static void bio_integrity_uncopy_user(struct bio_integrity_payload *bip)
107 {
108 	unsigned short nr_vecs = bip->bip_max_vcnt - 1;
109 	struct bio_vec *copy = &bip->bip_vec[1];
110 	size_t bytes = bip->bip_iter.bi_size;
111 	struct iov_iter iter;
112 	int ret;
113 
114 	iov_iter_bvec(&iter, ITER_DEST, copy, nr_vecs, bytes);
115 	ret = copy_to_iter(bvec_virt(bip->bip_vec), bytes, &iter);
116 	WARN_ON_ONCE(ret != bytes);
117 
118 	bio_integrity_unpin_bvec(copy, nr_vecs, true);
119 }
120 
121 static void bio_integrity_unmap_user(struct bio_integrity_payload *bip)
122 {
123 	bool dirty = bio_data_dir(bip->bip_bio) == READ;
124 
125 	if (bip->bip_flags & BIP_COPY_USER) {
126 		if (dirty)
127 			bio_integrity_uncopy_user(bip);
128 		kfree(bvec_virt(bip->bip_vec));
129 		return;
130 	}
131 
132 	bio_integrity_unpin_bvec(bip->bip_vec, bip->bip_max_vcnt, dirty);
133 }
134 
135 /**
136  * bio_integrity_free - Free bio integrity payload
137  * @bio:	bio containing bip to be freed
138  *
139  * Description: Used to free the integrity portion of a bio. Usually
140  * called from bio_free().
141  */
142 void bio_integrity_free(struct bio *bio)
143 {
144 	struct bio_integrity_payload *bip = bio_integrity(bio);
145 	struct bio_set *bs = bio->bi_pool;
146 
147 	if (bip->bip_flags & BIP_BLOCK_INTEGRITY)
148 		kfree(bvec_virt(bip->bip_vec));
149 	else if (bip->bip_flags & BIP_INTEGRITY_USER)
150 		bio_integrity_unmap_user(bip);
151 
152 	__bio_integrity_free(bs, bip);
153 	bio->bi_integrity = NULL;
154 	bio->bi_opf &= ~REQ_INTEGRITY;
155 }
156 
157 /**
158  * bio_integrity_add_page - Attach integrity metadata
159  * @bio:	bio to update
160  * @page:	page containing integrity metadata
161  * @len:	number of bytes of integrity metadata in page
162  * @offset:	start offset within page
163  *
164  * Description: Attach a page containing integrity metadata to bio.
165  */
166 int bio_integrity_add_page(struct bio *bio, struct page *page,
167 			   unsigned int len, unsigned int offset)
168 {
169 	struct request_queue *q = bdev_get_queue(bio->bi_bdev);
170 	struct bio_integrity_payload *bip = bio_integrity(bio);
171 
172 	if (((bip->bip_iter.bi_size + len) >> SECTOR_SHIFT) >
173 	    queue_max_hw_sectors(q))
174 		return 0;
175 
176 	if (bip->bip_vcnt > 0) {
177 		struct bio_vec *bv = &bip->bip_vec[bip->bip_vcnt - 1];
178 		bool same_page = false;
179 
180 		if (bvec_try_merge_hw_page(q, bv, page, len, offset,
181 					   &same_page)) {
182 			bip->bip_iter.bi_size += len;
183 			return len;
184 		}
185 
186 		if (bip->bip_vcnt >=
187 		    min(bip->bip_max_vcnt, queue_max_integrity_segments(q)))
188 			return 0;
189 
190 		/*
191 		 * If the queue doesn't support SG gaps and adding this segment
192 		 * would create a gap, disallow it.
193 		 */
194 		if (bvec_gap_to_prev(&q->limits, bv, offset))
195 			return 0;
196 	}
197 
198 	bvec_set_page(&bip->bip_vec[bip->bip_vcnt], page, len, offset);
199 	bip->bip_vcnt++;
200 	bip->bip_iter.bi_size += len;
201 
202 	return len;
203 }
204 EXPORT_SYMBOL(bio_integrity_add_page);
205 
206 static int bio_integrity_copy_user(struct bio *bio, struct bio_vec *bvec,
207 				   int nr_vecs, unsigned int len,
208 				   unsigned int direction, u32 seed)
209 {
210 	bool write = direction == ITER_SOURCE;
211 	struct bio_integrity_payload *bip;
212 	struct iov_iter iter;
213 	void *buf;
214 	int ret;
215 
216 	buf = kmalloc(len, GFP_KERNEL);
217 	if (!buf)
218 		return -ENOMEM;
219 
220 	if (write) {
221 		iov_iter_bvec(&iter, direction, bvec, nr_vecs, len);
222 		if (!copy_from_iter_full(buf, len, &iter)) {
223 			ret = -EFAULT;
224 			goto free_buf;
225 		}
226 
227 		bip = bio_integrity_alloc(bio, GFP_KERNEL, 1);
228 	} else {
229 		memset(buf, 0, len);
230 
231 		/*
232 		 * We need to preserve the original bvec and the number of vecs
233 		 * in it for completion handling
234 		 */
235 		bip = bio_integrity_alloc(bio, GFP_KERNEL, nr_vecs + 1);
236 	}
237 
238 	if (IS_ERR(bip)) {
239 		ret = PTR_ERR(bip);
240 		goto free_buf;
241 	}
242 
243 	if (write)
244 		bio_integrity_unpin_bvec(bvec, nr_vecs, false);
245 	else
246 		memcpy(&bip->bip_vec[1], bvec, nr_vecs * sizeof(*bvec));
247 
248 	ret = bio_integrity_add_page(bio, virt_to_page(buf), len,
249 				     offset_in_page(buf));
250 	if (ret != len) {
251 		ret = -ENOMEM;
252 		goto free_bip;
253 	}
254 
255 	bip->bip_flags |= BIP_INTEGRITY_USER | BIP_COPY_USER;
256 	bip->bip_iter.bi_sector = seed;
257 	bip->bip_vcnt = nr_vecs;
258 	return 0;
259 free_bip:
260 	bio_integrity_free(bio);
261 free_buf:
262 	kfree(buf);
263 	return ret;
264 }
265 
266 static int bio_integrity_init_user(struct bio *bio, struct bio_vec *bvec,
267 				   int nr_vecs, unsigned int len, u32 seed)
268 {
269 	struct bio_integrity_payload *bip;
270 
271 	bip = bio_integrity_alloc(bio, GFP_KERNEL, nr_vecs);
272 	if (IS_ERR(bip))
273 		return PTR_ERR(bip);
274 
275 	memcpy(bip->bip_vec, bvec, nr_vecs * sizeof(*bvec));
276 	bip->bip_flags |= BIP_INTEGRITY_USER;
277 	bip->bip_iter.bi_sector = seed;
278 	bip->bip_iter.bi_size = len;
279 	bip->bip_vcnt = nr_vecs;
280 	return 0;
281 }
282 
283 static unsigned int bvec_from_pages(struct bio_vec *bvec, struct page **pages,
284 				    int nr_vecs, ssize_t bytes, ssize_t offset)
285 {
286 	unsigned int nr_bvecs = 0;
287 	int i, j;
288 
289 	for (i = 0; i < nr_vecs; i = j) {
290 		size_t size = min_t(size_t, bytes, PAGE_SIZE - offset);
291 		struct folio *folio = page_folio(pages[i]);
292 
293 		bytes -= size;
294 		for (j = i + 1; j < nr_vecs; j++) {
295 			size_t next = min_t(size_t, PAGE_SIZE, bytes);
296 
297 			if (page_folio(pages[j]) != folio ||
298 			    pages[j] != pages[j - 1] + 1)
299 				break;
300 			unpin_user_page(pages[j]);
301 			size += next;
302 			bytes -= next;
303 		}
304 
305 		bvec_set_page(&bvec[nr_bvecs], pages[i], size, offset);
306 		offset = 0;
307 		nr_bvecs++;
308 	}
309 
310 	return nr_bvecs;
311 }
312 
313 int bio_integrity_map_user(struct bio *bio, void __user *ubuf, ssize_t bytes,
314 			   u32 seed)
315 {
316 	struct request_queue *q = bdev_get_queue(bio->bi_bdev);
317 	unsigned int align = blk_lim_dma_alignment_and_pad(&q->limits);
318 	struct page *stack_pages[UIO_FASTIOV], **pages = stack_pages;
319 	struct bio_vec stack_vec[UIO_FASTIOV], *bvec = stack_vec;
320 	unsigned int direction, nr_bvecs;
321 	struct iov_iter iter;
322 	int ret, nr_vecs;
323 	size_t offset;
324 	bool copy;
325 
326 	if (bio_integrity(bio))
327 		return -EINVAL;
328 	if (bytes >> SECTOR_SHIFT > queue_max_hw_sectors(q))
329 		return -E2BIG;
330 
331 	if (bio_data_dir(bio) == READ)
332 		direction = ITER_DEST;
333 	else
334 		direction = ITER_SOURCE;
335 
336 	iov_iter_ubuf(&iter, direction, ubuf, bytes);
337 	nr_vecs = iov_iter_npages(&iter, BIO_MAX_VECS + 1);
338 	if (nr_vecs > BIO_MAX_VECS)
339 		return -E2BIG;
340 	if (nr_vecs > UIO_FASTIOV) {
341 		bvec = kcalloc(nr_vecs, sizeof(*bvec), GFP_KERNEL);
342 		if (!bvec)
343 			return -ENOMEM;
344 		pages = NULL;
345 	}
346 
347 	copy = !iov_iter_is_aligned(&iter, align, align);
348 	ret = iov_iter_extract_pages(&iter, &pages, bytes, nr_vecs, 0, &offset);
349 	if (unlikely(ret < 0))
350 		goto free_bvec;
351 
352 	nr_bvecs = bvec_from_pages(bvec, pages, nr_vecs, bytes, offset);
353 	if (pages != stack_pages)
354 		kvfree(pages);
355 	if (nr_bvecs > queue_max_integrity_segments(q))
356 		copy = true;
357 
358 	if (copy)
359 		ret = bio_integrity_copy_user(bio, bvec, nr_bvecs, bytes,
360 					      direction, seed);
361 	else
362 		ret = bio_integrity_init_user(bio, bvec, nr_bvecs, bytes, seed);
363 	if (ret)
364 		goto release_pages;
365 	if (bvec != stack_vec)
366 		kfree(bvec);
367 
368 	return 0;
369 
370 release_pages:
371 	bio_integrity_unpin_bvec(bvec, nr_bvecs, false);
372 free_bvec:
373 	if (bvec != stack_vec)
374 		kfree(bvec);
375 	return ret;
376 }
377 EXPORT_SYMBOL_GPL(bio_integrity_map_user);
378 
379 /**
380  * bio_integrity_prep - Prepare bio for integrity I/O
381  * @bio:	bio to prepare
382  *
383  * Description:  Checks if the bio already has an integrity payload attached.
384  * If it does, the payload has been generated by another kernel subsystem,
385  * and we just pass it through. Otherwise allocates integrity payload.
386  * The bio must have data direction, target device and start sector set priot
387  * to calling.  In the WRITE case, integrity metadata will be generated using
388  * the block device's integrity function.  In the READ case, the buffer
389  * will be prepared for DMA and a suitable end_io handler set up.
390  */
391 bool bio_integrity_prep(struct bio *bio)
392 {
393 	struct bio_integrity_payload *bip;
394 	struct blk_integrity *bi = blk_get_integrity(bio->bi_bdev->bd_disk);
395 	unsigned int len;
396 	void *buf;
397 	gfp_t gfp = GFP_NOIO;
398 
399 	if (!bi)
400 		return true;
401 
402 	if (!bio_sectors(bio))
403 		return true;
404 
405 	/* Already protected? */
406 	if (bio_integrity(bio))
407 		return true;
408 
409 	switch (bio_op(bio)) {
410 	case REQ_OP_READ:
411 		if (bi->flags & BLK_INTEGRITY_NOVERIFY)
412 			return true;
413 		break;
414 	case REQ_OP_WRITE:
415 		if (bi->flags & BLK_INTEGRITY_NOGENERATE)
416 			return true;
417 
418 		/*
419 		 * Zero the memory allocated to not leak uninitialized kernel
420 		 * memory to disk for non-integrity metadata where nothing else
421 		 * initializes the memory.
422 		 */
423 		if (bi->csum_type == BLK_INTEGRITY_CSUM_NONE)
424 			gfp |= __GFP_ZERO;
425 		break;
426 	default:
427 		return true;
428 	}
429 
430 	/* Allocate kernel buffer for protection data */
431 	len = bio_integrity_bytes(bi, bio_sectors(bio));
432 	buf = kmalloc(len, gfp);
433 	if (unlikely(buf == NULL)) {
434 		goto err_end_io;
435 	}
436 
437 	bip = bio_integrity_alloc(bio, GFP_NOIO, 1);
438 	if (IS_ERR(bip)) {
439 		kfree(buf);
440 		goto err_end_io;
441 	}
442 
443 	bip->bip_flags |= BIP_BLOCK_INTEGRITY;
444 	bip_set_seed(bip, bio->bi_iter.bi_sector);
445 
446 	if (bi->csum_type == BLK_INTEGRITY_CSUM_IP)
447 		bip->bip_flags |= BIP_IP_CHECKSUM;
448 
449 	if (bio_integrity_add_page(bio, virt_to_page(buf), len,
450 			offset_in_page(buf)) < len) {
451 		printk(KERN_ERR "could not attach integrity payload\n");
452 		goto err_end_io;
453 	}
454 
455 	/* Auto-generate integrity metadata if this is a write */
456 	if (bio_data_dir(bio) == WRITE)
457 		blk_integrity_generate(bio);
458 	else
459 		bip->bio_iter = bio->bi_iter;
460 	return true;
461 
462 err_end_io:
463 	bio->bi_status = BLK_STS_RESOURCE;
464 	bio_endio(bio);
465 	return false;
466 }
467 EXPORT_SYMBOL(bio_integrity_prep);
468 
469 /**
470  * bio_integrity_verify_fn - Integrity I/O completion worker
471  * @work:	Work struct stored in bio to be verified
472  *
473  * Description: This workqueue function is called to complete a READ
474  * request.  The function verifies the transferred integrity metadata
475  * and then calls the original bio end_io function.
476  */
477 static void bio_integrity_verify_fn(struct work_struct *work)
478 {
479 	struct bio_integrity_payload *bip =
480 		container_of(work, struct bio_integrity_payload, bip_work);
481 	struct bio *bio = bip->bip_bio;
482 
483 	blk_integrity_verify(bio);
484 	bio_integrity_free(bio);
485 	bio_endio(bio);
486 }
487 
488 /**
489  * __bio_integrity_endio - Integrity I/O completion function
490  * @bio:	Protected bio
491  *
492  * Description: Completion for integrity I/O
493  *
494  * Normally I/O completion is done in interrupt context.  However,
495  * verifying I/O integrity is a time-consuming task which must be run
496  * in process context.	This function postpones completion
497  * accordingly.
498  */
499 bool __bio_integrity_endio(struct bio *bio)
500 {
501 	struct blk_integrity *bi = blk_get_integrity(bio->bi_bdev->bd_disk);
502 	struct bio_integrity_payload *bip = bio_integrity(bio);
503 
504 	if (bio_op(bio) == REQ_OP_READ && !bio->bi_status &&
505 	    (bip->bip_flags & BIP_BLOCK_INTEGRITY) && bi->csum_type) {
506 		INIT_WORK(&bip->bip_work, bio_integrity_verify_fn);
507 		queue_work(kintegrityd_wq, &bip->bip_work);
508 		return false;
509 	}
510 
511 	bio_integrity_free(bio);
512 	return true;
513 }
514 
515 /**
516  * bio_integrity_advance - Advance integrity vector
517  * @bio:	bio whose integrity vector to update
518  * @bytes_done:	number of data bytes that have been completed
519  *
520  * Description: This function calculates how many integrity bytes the
521  * number of completed data bytes correspond to and advances the
522  * integrity vector accordingly.
523  */
524 void bio_integrity_advance(struct bio *bio, unsigned int bytes_done)
525 {
526 	struct bio_integrity_payload *bip = bio_integrity(bio);
527 	struct blk_integrity *bi = blk_get_integrity(bio->bi_bdev->bd_disk);
528 	unsigned bytes = bio_integrity_bytes(bi, bytes_done >> 9);
529 
530 	bip->bip_iter.bi_sector += bio_integrity_intervals(bi, bytes_done >> 9);
531 	bvec_iter_advance(bip->bip_vec, &bip->bip_iter, bytes);
532 }
533 
534 /**
535  * bio_integrity_trim - Trim integrity vector
536  * @bio:	bio whose integrity vector to update
537  *
538  * Description: Used to trim the integrity vector in a cloned bio.
539  */
540 void bio_integrity_trim(struct bio *bio)
541 {
542 	struct bio_integrity_payload *bip = bio_integrity(bio);
543 	struct blk_integrity *bi = blk_get_integrity(bio->bi_bdev->bd_disk);
544 
545 	bip->bip_iter.bi_size = bio_integrity_bytes(bi, bio_sectors(bio));
546 }
547 EXPORT_SYMBOL(bio_integrity_trim);
548 
549 /**
550  * bio_integrity_clone - Callback for cloning bios with integrity metadata
551  * @bio:	New bio
552  * @bio_src:	Original bio
553  * @gfp_mask:	Memory allocation mask
554  *
555  * Description:	Called to allocate a bip when cloning a bio
556  */
557 int bio_integrity_clone(struct bio *bio, struct bio *bio_src,
558 			gfp_t gfp_mask)
559 {
560 	struct bio_integrity_payload *bip_src = bio_integrity(bio_src);
561 	struct bio_integrity_payload *bip;
562 
563 	BUG_ON(bip_src == NULL);
564 
565 	bip = bio_integrity_alloc(bio, gfp_mask, 0);
566 	if (IS_ERR(bip))
567 		return PTR_ERR(bip);
568 
569 	bip->bip_vec = bip_src->bip_vec;
570 	bip->bip_iter = bip_src->bip_iter;
571 	bip->bip_flags = bip_src->bip_flags & ~BIP_BLOCK_INTEGRITY;
572 
573 	return 0;
574 }
575 
576 int bioset_integrity_create(struct bio_set *bs, int pool_size)
577 {
578 	if (mempool_initialized(&bs->bio_integrity_pool))
579 		return 0;
580 
581 	if (mempool_init_slab_pool(&bs->bio_integrity_pool,
582 				   pool_size, bip_slab))
583 		return -1;
584 
585 	if (biovec_init_pool(&bs->bvec_integrity_pool, pool_size)) {
586 		mempool_exit(&bs->bio_integrity_pool);
587 		return -1;
588 	}
589 
590 	return 0;
591 }
592 EXPORT_SYMBOL(bioset_integrity_create);
593 
594 void bioset_integrity_free(struct bio_set *bs)
595 {
596 	mempool_exit(&bs->bio_integrity_pool);
597 	mempool_exit(&bs->bvec_integrity_pool);
598 }
599 
600 void __init bio_integrity_init(void)
601 {
602 	/*
603 	 * kintegrityd won't block much but may burn a lot of CPU cycles.
604 	 * Make it highpri CPU intensive wq with max concurrency of 1.
605 	 */
606 	kintegrityd_wq = alloc_workqueue("kintegrityd", WQ_MEM_RECLAIM |
607 					 WQ_HIGHPRI | WQ_CPU_INTENSIVE, 1);
608 	if (!kintegrityd_wq)
609 		panic("Failed to create kintegrityd\n");
610 
611 	bip_slab = kmem_cache_create("bio_integrity_payload",
612 				     sizeof(struct bio_integrity_payload) +
613 				     sizeof(struct bio_vec) * BIO_INLINE_VECS,
614 				     0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
615 }
616