xref: /linux/fs/crypto/bio.c (revision 6fa6b5cb60490db2591bb93872b95f72315e5f53)
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 					      loff_t pos, sector_t sector,
74 					      u64 len)
75 {
76 	struct fscrypt_zero_done done = {
77 		.pending	= ATOMIC_INIT(1),
78 		.done		= COMPLETION_INITIALIZER_ONSTACK(done.done),
79 	};
80 
81 	while (len) {
82 		struct bio *bio;
83 		unsigned int n;
84 
85 		bio = bio_alloc(inode->i_sb->s_bdev, BIO_MAX_VECS, REQ_OP_WRITE,
86 				GFP_NOFS);
87 		bio->bi_iter.bi_sector = sector;
88 		bio->bi_private = &done;
89 		bio->bi_end_io = fscrypt_zeroout_range_end_io;
90 		fscrypt_set_bio_crypt_ctx(bio, inode, pos, GFP_NOFS);
91 
92 		for (n = 0; n < BIO_MAX_VECS; n++) {
93 			unsigned int bytes_this_page = min(len, PAGE_SIZE);
94 
95 			__bio_add_page(bio, ZERO_PAGE(0), bytes_this_page, 0);
96 			len -= bytes_this_page;
97 			pos += bytes_this_page;
98 			sector += (bytes_this_page >> SECTOR_SHIFT);
99 			if (!len || !fscrypt_mergeable_bio(bio, inode, pos))
100 				break;
101 		}
102 
103 		atomic_inc(&done.pending);
104 		blk_crypto_submit_bio(bio);
105 	}
106 
107 	fscrypt_zeroout_range_done(&done);
108 
109 	wait_for_completion(&done.done);
110 	return blk_status_to_errno(done.status);
111 }
112 
113 /**
114  * fscrypt_zeroout_range() - zero out a range of blocks in an encrypted file
115  * @inode: the file's inode
116  * @pos: the first file position (in bytes) to zero out
117  * @sector: the first sector to zero out
118  * @len: bytes to zero out
119  *
120  * Zero out filesystem blocks in an encrypted regular file on-disk, i.e. write
121  * ciphertext blocks which decrypt to the all-zeroes block.  The blocks must be
122  * both logically and physically contiguous.  It's also assumed that the
123  * filesystem only uses a single block device, ->s_bdev.  @len must be a
124  * multiple of the file system logical block size.
125  *
126  * Note that since each block uses a different IV, this involves writing a
127  * different ciphertext to each block; we can't simply reuse the same one.
128  *
129  * Return: 0 on success; -errno on failure.
130  */
131 int fscrypt_zeroout_range(const struct inode *inode, loff_t pos,
132 			  sector_t sector, u64 len)
133 {
134 	const struct fscrypt_inode_info *ci = fscrypt_get_inode_info_raw(inode);
135 	const unsigned int du_bits = ci->ci_data_unit_bits;
136 	const unsigned int du_size = 1U << du_bits;
137 	const unsigned int du_per_page_bits = PAGE_SHIFT - du_bits;
138 	const unsigned int du_per_page = 1U << du_per_page_bits;
139 	u64 du_index = pos >> du_bits;
140 	u64 du_remaining = len >> du_bits;
141 	struct page *pages[16]; /* write up to 16 pages at a time */
142 	unsigned int nr_pages;
143 	unsigned int i;
144 	unsigned int offset;
145 	struct bio *bio;
146 	int ret, err;
147 
148 	if (len == 0)
149 		return 0;
150 
151 	if (fscrypt_inode_uses_inline_crypto(inode))
152 		return fscrypt_zeroout_range_inline_crypt(inode, pos, sector,
153 							  len);
154 
155 	BUILD_BUG_ON(ARRAY_SIZE(pages) > BIO_MAX_VECS);
156 	nr_pages = min_t(u64, ARRAY_SIZE(pages),
157 			 (du_remaining + du_per_page - 1) >> du_per_page_bits);
158 
159 	/*
160 	 * We need at least one page for ciphertext.  Allocate the first one
161 	 * from a mempool, with __GFP_DIRECT_RECLAIM set so that it can't fail.
162 	 *
163 	 * Any additional page allocations are allowed to fail, as they only
164 	 * help performance, and waiting on the mempool for them could deadlock.
165 	 */
166 	for (i = 0; i < nr_pages; i++) {
167 		pages[i] = fscrypt_alloc_bounce_page(i == 0 ? GFP_NOFS :
168 						     GFP_NOWAIT);
169 		if (!pages[i])
170 			break;
171 	}
172 	nr_pages = i;
173 	if (WARN_ON_ONCE(nr_pages <= 0))
174 		return -EINVAL;
175 
176 	/* This always succeeds since __GFP_DIRECT_RECLAIM is set. */
177 	bio = bio_alloc(inode->i_sb->s_bdev, nr_pages, REQ_OP_WRITE, GFP_NOFS);
178 
179 	do {
180 		bio->bi_iter.bi_sector = sector;
181 
182 		i = 0;
183 		offset = 0;
184 		do {
185 			err = fscrypt_crypt_data_unit(ci, FS_ENCRYPT, du_index,
186 						      ZERO_PAGE(0), pages[i],
187 						      du_size, offset);
188 			if (err)
189 				goto out;
190 			du_index++;
191 			sector += 1U << (du_bits - SECTOR_SHIFT);
192 			du_remaining--;
193 			offset += du_size;
194 			if (offset == PAGE_SIZE || du_remaining == 0) {
195 				ret = bio_add_page(bio, pages[i++], offset, 0);
196 				if (WARN_ON_ONCE(ret != offset)) {
197 					err = -EIO;
198 					goto out;
199 				}
200 				offset = 0;
201 			}
202 		} while (i != nr_pages && du_remaining != 0);
203 
204 		err = submit_bio_wait(bio);
205 		if (err)
206 			goto out;
207 		bio_reset(bio, inode->i_sb->s_bdev, REQ_OP_WRITE);
208 	} while (du_remaining != 0);
209 	err = 0;
210 out:
211 	bio_put(bio);
212 	for (i = 0; i < nr_pages; i++)
213 		fscrypt_free_bounce_page(pages[i]);
214 	return err;
215 }
216 EXPORT_SYMBOL(fscrypt_zeroout_range);
217