1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * linux/fs/ext4/readpage.c
4  *
5  * Copyright (C) 2002, Linus Torvalds.
6  * Copyright (C) 2015, Google, Inc.
7  *
8  * This was originally taken from fs/mpage.c
9  *
10  * The ext4_mpage_readpages() function here is intended to
11  * replace mpage_readahead() in the general case, not just for
12  * encrypted files.  It has some limitations (see below), where it
13  * will fall back to read_block_full_page(), but these limitations
14  * should only be hit when page_size != block_size.
15  *
16  * This will allow us to attach a callback function to support ext4
17  * encryption.
18  *
19  * If anything unusual happens, such as:
20  *
21  * - encountering a page which has buffers
22  * - encountering a page which has a non-hole after a hole
23  * - encountering a page with non-contiguous blocks
24  *
25  * then this code just gives up and calls the buffer_head-based read function.
26  * It does handle a page which has holes at the end - that is a common case:
27  * the end-of-file on blocksize < PAGE_SIZE setups.
28  *
29  */
30 
31 #include <linux/kernel.h>
32 #include <linux/export.h>
33 #include <linux/mm.h>
34 #include <linux/kdev_t.h>
35 #include <linux/gfp.h>
36 #include <linux/bio.h>
37 #include <linux/fs.h>
38 #include <linux/buffer_head.h>
39 #include <linux/blkdev.h>
40 #include <linux/highmem.h>
41 #include <linux/prefetch.h>
42 #include <linux/mpage.h>
43 #include <linux/writeback.h>
44 #include <linux/backing-dev.h>
45 #include <linux/pagevec.h>
46 
47 #include "ext4.h"
48 
49 #define NUM_PREALLOC_POST_READ_CTXS	128
50 
51 static struct kmem_cache *bio_post_read_ctx_cache;
52 static mempool_t *bio_post_read_ctx_pool;
53 
54 /* postprocessing steps for read bios */
55 enum bio_post_read_step {
56 	STEP_INITIAL = 0,
57 	STEP_DECRYPT,
58 	STEP_VERITY,
59 	STEP_MAX,
60 };
61 
62 struct bio_post_read_ctx {
63 	struct bio *bio;
64 	struct work_struct work;
65 	unsigned int cur_step;
66 	unsigned int enabled_steps;
67 };
68 
69 static void __read_end_io(struct bio *bio)
70 {
71 	struct folio_iter fi;
72 
73 	bio_for_each_folio_all(fi, bio)
74 		folio_end_read(fi.folio, bio->bi_status == 0);
75 	if (bio->bi_private)
76 		mempool_free(bio->bi_private, bio_post_read_ctx_pool);
77 	bio_put(bio);
78 }
79 
80 static void bio_post_read_processing(struct bio_post_read_ctx *ctx);
81 
82 static void decrypt_work(struct work_struct *work)
83 {
84 	struct bio_post_read_ctx *ctx =
85 		container_of(work, struct bio_post_read_ctx, work);
86 	struct bio *bio = ctx->bio;
87 
88 	if (fscrypt_decrypt_bio(bio))
89 		bio_post_read_processing(ctx);
90 	else
91 		__read_end_io(bio);
92 }
93 
94 static void verity_work(struct work_struct *work)
95 {
96 	struct bio_post_read_ctx *ctx =
97 		container_of(work, struct bio_post_read_ctx, work);
98 	struct bio *bio = ctx->bio;
99 
100 	/*
101 	 * fsverity_verify_bio() may call readahead() again, and although verity
102 	 * will be disabled for that, decryption may still be needed, causing
103 	 * another bio_post_read_ctx to be allocated.  So to guarantee that
104 	 * mempool_alloc() never deadlocks we must free the current ctx first.
105 	 * This is safe because verity is the last post-read step.
106 	 */
107 	BUILD_BUG_ON(STEP_VERITY + 1 != STEP_MAX);
108 	mempool_free(ctx, bio_post_read_ctx_pool);
109 	bio->bi_private = NULL;
110 
111 	fsverity_verify_bio(bio);
112 
113 	__read_end_io(bio);
114 }
115 
116 static void bio_post_read_processing(struct bio_post_read_ctx *ctx)
117 {
118 	/*
119 	 * We use different work queues for decryption and for verity because
120 	 * verity may require reading metadata pages that need decryption, and
121 	 * we shouldn't recurse to the same workqueue.
122 	 */
123 	switch (++ctx->cur_step) {
124 	case STEP_DECRYPT:
125 		if (ctx->enabled_steps & (1 << STEP_DECRYPT)) {
126 			INIT_WORK(&ctx->work, decrypt_work);
127 			fscrypt_enqueue_decrypt_work(&ctx->work);
128 			return;
129 		}
130 		ctx->cur_step++;
131 		fallthrough;
132 	case STEP_VERITY:
133 		if (ctx->enabled_steps & (1 << STEP_VERITY)) {
134 			INIT_WORK(&ctx->work, verity_work);
135 			fsverity_enqueue_verify_work(&ctx->work);
136 			return;
137 		}
138 		ctx->cur_step++;
139 		fallthrough;
140 	default:
141 		__read_end_io(ctx->bio);
142 	}
143 }
144 
145 static bool bio_post_read_required(struct bio *bio)
146 {
147 	return bio->bi_private && !bio->bi_status;
148 }
149 
150 /*
151  * I/O completion handler for multipage BIOs.
152  *
153  * The mpage code never puts partial pages into a BIO (except for end-of-file).
154  * If a page does not map to a contiguous run of blocks then it simply falls
155  * back to block_read_full_folio().
156  *
157  * Why is this?  If a page's completion depends on a number of different BIOs
158  * which can complete in any order (or at the same time) then determining the
159  * status of that page is hard.  See end_buffer_async_read() for the details.
160  * There is no point in duplicating all that complexity.
161  */
162 static void mpage_end_io(struct bio *bio)
163 {
164 	if (bio_post_read_required(bio)) {
165 		struct bio_post_read_ctx *ctx = bio->bi_private;
166 
167 		ctx->cur_step = STEP_INITIAL;
168 		bio_post_read_processing(ctx);
169 		return;
170 	}
171 	__read_end_io(bio);
172 }
173 
174 static inline bool ext4_need_verity(const struct inode *inode, pgoff_t idx)
175 {
176 	return fsverity_active(inode) &&
177 	       idx < DIV_ROUND_UP(inode->i_size, PAGE_SIZE);
178 }
179 
180 static void ext4_set_bio_post_read_ctx(struct bio *bio,
181 				       const struct inode *inode,
182 				       pgoff_t first_idx)
183 {
184 	unsigned int post_read_steps = 0;
185 
186 	if (fscrypt_inode_uses_fs_layer_crypto(inode))
187 		post_read_steps |= 1 << STEP_DECRYPT;
188 
189 	if (ext4_need_verity(inode, first_idx))
190 		post_read_steps |= 1 << STEP_VERITY;
191 
192 	if (post_read_steps) {
193 		/* Due to the mempool, this never fails. */
194 		struct bio_post_read_ctx *ctx =
195 			mempool_alloc(bio_post_read_ctx_pool, GFP_NOFS);
196 
197 		ctx->bio = bio;
198 		ctx->enabled_steps = post_read_steps;
199 		bio->bi_private = ctx;
200 	}
201 }
202 
203 static inline loff_t ext4_readpage_limit(struct inode *inode)
204 {
205 	if (IS_ENABLED(CONFIG_FS_VERITY) && IS_VERITY(inode))
206 		return inode->i_sb->s_maxbytes;
207 
208 	return i_size_read(inode);
209 }
210 
211 int ext4_mpage_readpages(struct inode *inode,
212 		struct readahead_control *rac, struct folio *folio)
213 {
214 	struct bio *bio = NULL;
215 	sector_t last_block_in_bio = 0;
216 
217 	const unsigned blkbits = inode->i_blkbits;
218 	const unsigned blocks_per_page = PAGE_SIZE >> blkbits;
219 	const unsigned blocksize = 1 << blkbits;
220 	sector_t next_block;
221 	sector_t block_in_file;
222 	sector_t last_block;
223 	sector_t last_block_in_file;
224 	sector_t first_block;
225 	unsigned page_block;
226 	struct block_device *bdev = inode->i_sb->s_bdev;
227 	int length;
228 	unsigned relative_block = 0;
229 	struct ext4_map_blocks map;
230 	unsigned int nr_pages, folio_pages;
231 
232 	map.m_pblk = 0;
233 	map.m_lblk = 0;
234 	map.m_len = 0;
235 	map.m_flags = 0;
236 
237 	nr_pages = rac ? readahead_count(rac) : folio_nr_pages(folio);
238 	for (; nr_pages; nr_pages -= folio_pages) {
239 		int fully_mapped = 1;
240 		unsigned int first_hole;
241 		unsigned int blocks_per_folio;
242 
243 		if (rac)
244 			folio = readahead_folio(rac);
245 
246 		folio_pages = folio_nr_pages(folio);
247 		prefetchw(&folio->flags);
248 
249 		if (folio_buffers(folio))
250 			goto confused;
251 
252 		blocks_per_folio = folio_size(folio) >> blkbits;
253 		first_hole = blocks_per_folio;
254 		block_in_file = next_block =
255 			(sector_t)folio->index << (PAGE_SHIFT - blkbits);
256 		last_block = block_in_file + nr_pages * blocks_per_page;
257 		last_block_in_file = (ext4_readpage_limit(inode) +
258 				      blocksize - 1) >> blkbits;
259 		if (last_block > last_block_in_file)
260 			last_block = last_block_in_file;
261 		page_block = 0;
262 
263 		/*
264 		 * Map blocks using the previous result first.
265 		 */
266 		if ((map.m_flags & EXT4_MAP_MAPPED) &&
267 		    block_in_file > map.m_lblk &&
268 		    block_in_file < (map.m_lblk + map.m_len)) {
269 			unsigned map_offset = block_in_file - map.m_lblk;
270 			unsigned last = map.m_len - map_offset;
271 
272 			first_block = map.m_pblk + map_offset;
273 			for (relative_block = 0; ; relative_block++) {
274 				if (relative_block == last) {
275 					/* needed? */
276 					map.m_flags &= ~EXT4_MAP_MAPPED;
277 					break;
278 				}
279 				if (page_block == blocks_per_folio)
280 					break;
281 				page_block++;
282 				block_in_file++;
283 			}
284 		}
285 
286 		/*
287 		 * Then do more ext4_map_blocks() calls until we are
288 		 * done with this folio.
289 		 */
290 		while (page_block < blocks_per_folio) {
291 			if (block_in_file < last_block) {
292 				map.m_lblk = block_in_file;
293 				map.m_len = last_block - block_in_file;
294 
295 				if (ext4_map_blocks(NULL, inode, &map, 0) < 0) {
296 				set_error_page:
297 					folio_zero_segment(folio, 0,
298 							  folio_size(folio));
299 					folio_unlock(folio);
300 					goto next_page;
301 				}
302 			}
303 			if ((map.m_flags & EXT4_MAP_MAPPED) == 0) {
304 				fully_mapped = 0;
305 				if (first_hole == blocks_per_folio)
306 					first_hole = page_block;
307 				page_block++;
308 				block_in_file++;
309 				continue;
310 			}
311 			if (first_hole != blocks_per_folio)
312 				goto confused;		/* hole -> non-hole */
313 
314 			/* Contiguous blocks? */
315 			if (!page_block)
316 				first_block = map.m_pblk;
317 			else if (first_block + page_block != map.m_pblk)
318 				goto confused;
319 			for (relative_block = 0; ; relative_block++) {
320 				if (relative_block == map.m_len) {
321 					/* needed? */
322 					map.m_flags &= ~EXT4_MAP_MAPPED;
323 					break;
324 				} else if (page_block == blocks_per_folio)
325 					break;
326 				page_block++;
327 				block_in_file++;
328 			}
329 		}
330 		if (first_hole != blocks_per_folio) {
331 			folio_zero_segment(folio, first_hole << blkbits,
332 					  folio_size(folio));
333 			if (first_hole == 0) {
334 				if (ext4_need_verity(inode, folio->index) &&
335 				    !fsverity_verify_folio(folio))
336 					goto set_error_page;
337 				folio_end_read(folio, true);
338 				continue;
339 			}
340 		} else if (fully_mapped) {
341 			folio_set_mappedtodisk(folio);
342 		}
343 
344 		/*
345 		 * This folio will go to BIO.  Do we need to send this
346 		 * BIO off first?
347 		 */
348 		if (bio && (last_block_in_bio != first_block - 1 ||
349 			    !fscrypt_mergeable_bio(bio, inode, next_block))) {
350 		submit_and_realloc:
351 			submit_bio(bio);
352 			bio = NULL;
353 		}
354 		if (bio == NULL) {
355 			/*
356 			 * bio_alloc will _always_ be able to allocate a bio if
357 			 * __GFP_DIRECT_RECLAIM is set, see bio_alloc_bioset().
358 			 */
359 			bio = bio_alloc(bdev, bio_max_segs(nr_pages),
360 					REQ_OP_READ, GFP_KERNEL);
361 			fscrypt_set_bio_crypt_ctx(bio, inode, next_block,
362 						  GFP_KERNEL);
363 			ext4_set_bio_post_read_ctx(bio, inode, folio->index);
364 			bio->bi_iter.bi_sector = first_block << (blkbits - 9);
365 			bio->bi_end_io = mpage_end_io;
366 			if (rac)
367 				bio->bi_opf |= REQ_RAHEAD;
368 		}
369 
370 		length = first_hole << blkbits;
371 		if (!bio_add_folio(bio, folio, length, 0))
372 			goto submit_and_realloc;
373 
374 		if (((map.m_flags & EXT4_MAP_BOUNDARY) &&
375 		     (relative_block == map.m_len)) ||
376 		    (first_hole != blocks_per_folio)) {
377 			submit_bio(bio);
378 			bio = NULL;
379 		} else
380 			last_block_in_bio = first_block + blocks_per_folio - 1;
381 		continue;
382 	confused:
383 		if (bio) {
384 			submit_bio(bio);
385 			bio = NULL;
386 		}
387 		if (!folio_test_uptodate(folio))
388 			block_read_full_folio(folio, ext4_get_block);
389 		else
390 			folio_unlock(folio);
391 next_page:
392 		; /* A label shall be followed by a statement until C23 */
393 	}
394 	if (bio)
395 		submit_bio(bio);
396 	return 0;
397 }
398 
399 int __init ext4_init_post_read_processing(void)
400 {
401 	bio_post_read_ctx_cache = KMEM_CACHE(bio_post_read_ctx, SLAB_RECLAIM_ACCOUNT);
402 
403 	if (!bio_post_read_ctx_cache)
404 		goto fail;
405 	bio_post_read_ctx_pool =
406 		mempool_create_slab_pool(NUM_PREALLOC_POST_READ_CTXS,
407 					 bio_post_read_ctx_cache);
408 	if (!bio_post_read_ctx_pool)
409 		goto fail_free_cache;
410 	return 0;
411 
412 fail_free_cache:
413 	kmem_cache_destroy(bio_post_read_ctx_cache);
414 fail:
415 	return -ENOMEM;
416 }
417 
418 void ext4_exit_post_read_processing(void)
419 {
420 	mempool_destroy(bio_post_read_ctx_pool);
421 	kmem_cache_destroy(bio_post_read_ctx_cache);
422 }
423