xref: /linux/fs/crypto/bio.c (revision 69050f8d6d075dc01af7a5f2f550a8067510366f)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Utility functions for file contents encryption/decryption on
4  * block device-based filesystems.
5  *
6  * Copyright (C) 2015, Google, Inc.
7  * Copyright (C) 2015, Motorola Mobility
8  */
9 
10 #include <linux/bio.h>
11 #include <linux/export.h>
12 #include <linux/module.h>
13 #include <linux/namei.h>
14 #include <linux/pagemap.h>
15 
16 #include "fscrypt_private.h"
17 
18 /**
19  * fscrypt_decrypt_bio() - decrypt the contents of a bio
20  * @bio: the bio to decrypt
21  *
22  * Decrypt the contents of a "read" bio following successful completion of the
23  * underlying disk read.  The bio must be reading a whole number of blocks of an
24  * encrypted file directly into the page cache.  If the bio is reading the
25  * ciphertext into bounce pages instead of the page cache (for example, because
26  * the file is also compressed, so decompression is required after decryption),
27  * then this function isn't applicable.  This function may sleep, so it must be
28  * called from a workqueue rather than from the bio's bi_end_io callback.
29  *
30  * Return: %true on success; %false on failure.  On failure, bio->bi_status is
31  *	   also set to an error status.
32  */
33 bool fscrypt_decrypt_bio(struct bio *bio)
34 {
35 	struct folio_iter fi;
36 
37 	bio_for_each_folio_all(fi, bio) {
38 		int err = fscrypt_decrypt_pagecache_blocks(fi.folio, fi.length,
39 							   fi.offset);
40 
41 		if (err) {
42 			bio->bi_status = errno_to_blk_status(err);
43 			return false;
44 		}
45 	}
46 	return true;
47 }
48 EXPORT_SYMBOL(fscrypt_decrypt_bio);
49 
50 struct fscrypt_zero_done {
51 	atomic_t		pending;
52 	blk_status_t		status;
53 	struct completion	done;
54 };
55 
56 static void fscrypt_zeroout_range_done(struct fscrypt_zero_done *done)
57 {
58 	if (atomic_dec_and_test(&done->pending))
59 		complete(&done->done);
60 }
61 
62 static void fscrypt_zeroout_range_end_io(struct bio *bio)
63 {
64 	struct fscrypt_zero_done *done = bio->bi_private;
65 
66 	if (bio->bi_status)
67 		cmpxchg(&done->status, 0, bio->bi_status);
68 	fscrypt_zeroout_range_done(done);
69 	bio_put(bio);
70 }
71 
72 static int fscrypt_zeroout_range_inline_crypt(const struct inode *inode,
73 					      pgoff_t lblk, sector_t sector,
74 					      unsigned int len)
75 {
76 	const unsigned int blockbits = inode->i_blkbits;
77 	const unsigned int blocks_per_page = 1 << (PAGE_SHIFT - blockbits);
78 	struct fscrypt_zero_done done = {
79 		.pending	= ATOMIC_INIT(1),
80 		.done		= COMPLETION_INITIALIZER_ONSTACK(done.done),
81 	};
82 
83 	while (len) {
84 		struct bio *bio;
85 		unsigned int n;
86 
87 		bio = bio_alloc(inode->i_sb->s_bdev, BIO_MAX_VECS, REQ_OP_WRITE,
88 				GFP_NOFS);
89 		bio->bi_iter.bi_sector = sector;
90 		bio->bi_private = &done;
91 		bio->bi_end_io = fscrypt_zeroout_range_end_io;
92 		fscrypt_set_bio_crypt_ctx(bio, inode, lblk, GFP_NOFS);
93 
94 		for (n = 0; n < BIO_MAX_VECS; n++) {
95 			unsigned int blocks_this_page =
96 				min(len, blocks_per_page);
97 			unsigned int bytes_this_page = blocks_this_page << blockbits;
98 
99 			__bio_add_page(bio, ZERO_PAGE(0), bytes_this_page, 0);
100 			len -= blocks_this_page;
101 			lblk += blocks_this_page;
102 			sector += (bytes_this_page >> SECTOR_SHIFT);
103 			if (!len || !fscrypt_mergeable_bio(bio, inode, lblk))
104 				break;
105 		}
106 
107 		atomic_inc(&done.pending);
108 		blk_crypto_submit_bio(bio);
109 	}
110 
111 	fscrypt_zeroout_range_done(&done);
112 
113 	wait_for_completion(&done.done);
114 	return blk_status_to_errno(done.status);
115 }
116 
117 /**
118  * fscrypt_zeroout_range() - zero out a range of blocks in an encrypted file
119  * @inode: the file's inode
120  * @lblk: the first file logical block to zero out
121  * @pblk: the first filesystem physical block to zero out
122  * @len: number of blocks to zero out
123  *
124  * Zero out filesystem blocks in an encrypted regular file on-disk, i.e. write
125  * ciphertext blocks which decrypt to the all-zeroes block.  The blocks must be
126  * both logically and physically contiguous.  It's also assumed that the
127  * filesystem only uses a single block device, ->s_bdev.
128  *
129  * Note that since each block uses a different IV, this involves writing a
130  * different ciphertext to each block; we can't simply reuse the same one.
131  *
132  * Return: 0 on success; -errno on failure.
133  */
134 int fscrypt_zeroout_range(const struct inode *inode, pgoff_t lblk,
135 			  sector_t pblk, unsigned int len)
136 {
137 	const struct fscrypt_inode_info *ci = fscrypt_get_inode_info_raw(inode);
138 	const unsigned int du_bits = ci->ci_data_unit_bits;
139 	const unsigned int du_size = 1U << du_bits;
140 	const unsigned int du_per_page_bits = PAGE_SHIFT - du_bits;
141 	const unsigned int du_per_page = 1U << du_per_page_bits;
142 	u64 du_index = (u64)lblk << (inode->i_blkbits - du_bits);
143 	u64 du_remaining = (u64)len << (inode->i_blkbits - du_bits);
144 	sector_t sector = pblk << (inode->i_blkbits - SECTOR_SHIFT);
145 	struct page *pages[16]; /* write up to 16 pages at a time */
146 	unsigned int nr_pages;
147 	unsigned int i;
148 	unsigned int offset;
149 	struct bio *bio;
150 	int ret, err;
151 
152 	if (len == 0)
153 		return 0;
154 
155 	if (fscrypt_inode_uses_inline_crypto(inode))
156 		return fscrypt_zeroout_range_inline_crypt(inode, lblk, sector,
157 							  len);
158 
159 	BUILD_BUG_ON(ARRAY_SIZE(pages) > BIO_MAX_VECS);
160 	nr_pages = min_t(u64, ARRAY_SIZE(pages),
161 			 (du_remaining + du_per_page - 1) >> du_per_page_bits);
162 
163 	/*
164 	 * We need at least one page for ciphertext.  Allocate the first one
165 	 * from a mempool, with __GFP_DIRECT_RECLAIM set so that it can't fail.
166 	 *
167 	 * Any additional page allocations are allowed to fail, as they only
168 	 * help performance, and waiting on the mempool for them could deadlock.
169 	 */
170 	for (i = 0; i < nr_pages; i++) {
171 		pages[i] = fscrypt_alloc_bounce_page(i == 0 ? GFP_NOFS :
172 						     GFP_NOWAIT);
173 		if (!pages[i])
174 			break;
175 	}
176 	nr_pages = i;
177 	if (WARN_ON_ONCE(nr_pages <= 0))
178 		return -EINVAL;
179 
180 	/* This always succeeds since __GFP_DIRECT_RECLAIM is set. */
181 	bio = bio_alloc(inode->i_sb->s_bdev, nr_pages, REQ_OP_WRITE, GFP_NOFS);
182 
183 	do {
184 		bio->bi_iter.bi_sector = sector;
185 
186 		i = 0;
187 		offset = 0;
188 		do {
189 			err = fscrypt_crypt_data_unit(ci, FS_ENCRYPT, du_index,
190 						      ZERO_PAGE(0), pages[i],
191 						      du_size, offset);
192 			if (err)
193 				goto out;
194 			du_index++;
195 			sector += 1U << (du_bits - SECTOR_SHIFT);
196 			du_remaining--;
197 			offset += du_size;
198 			if (offset == PAGE_SIZE || du_remaining == 0) {
199 				ret = bio_add_page(bio, pages[i++], offset, 0);
200 				if (WARN_ON_ONCE(ret != offset)) {
201 					err = -EIO;
202 					goto out;
203 				}
204 				offset = 0;
205 			}
206 		} while (i != nr_pages && du_remaining != 0);
207 
208 		err = submit_bio_wait(bio);
209 		if (err)
210 			goto out;
211 		bio_reset(bio, inode->i_sb->s_bdev, REQ_OP_WRITE);
212 	} while (du_remaining != 0);
213 	err = 0;
214 out:
215 	bio_put(bio);
216 	for (i = 0; i < nr_pages; i++)
217 		fscrypt_free_bounce_page(pages[i]);
218 	return err;
219 }
220 EXPORT_SYMBOL(fscrypt_zeroout_range);
221