1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  linux/fs/ext4/inode.c
4  *
5  * Copyright (C) 1992, 1993, 1994, 1995
6  * Remy Card (card@masi.ibp.fr)
7  * Laboratoire MASI - Institut Blaise Pascal
8  * Universite Pierre et Marie Curie (Paris VI)
9  *
10  *  from
11  *
12  *  linux/fs/minix/inode.c
13  *
14  *  Copyright (C) 1991, 1992  Linus Torvalds
15  *
16  *  64-bit file support on 64-bit platforms by Jakub Jelinek
17  *	(jj@sunsite.ms.mff.cuni.cz)
18  *
19  *  Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
20  */
21 
22 #include <linux/fs.h>
23 #include <linux/mount.h>
24 #include <linux/time.h>
25 #include <linux/highuid.h>
26 #include <linux/pagemap.h>
27 #include <linux/dax.h>
28 #include <linux/quotaops.h>
29 #include <linux/string.h>
30 #include <linux/buffer_head.h>
31 #include <linux/writeback.h>
32 #include <linux/pagevec.h>
33 #include <linux/mpage.h>
34 #include <linux/namei.h>
35 #include <linux/uio.h>
36 #include <linux/bio.h>
37 #include <linux/workqueue.h>
38 #include <linux/kernel.h>
39 #include <linux/printk.h>
40 #include <linux/slab.h>
41 #include <linux/bitops.h>
42 #include <linux/iomap.h>
43 #include <linux/iversion.h>
44 
45 #include "ext4_jbd2.h"
46 #include "xattr.h"
47 #include "acl.h"
48 #include "truncate.h"
49 
50 #include <trace/events/ext4.h>
51 
ext4_inode_csum(struct inode * inode,struct ext4_inode * raw,struct ext4_inode_info * ei)52 static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
53 			      struct ext4_inode_info *ei)
54 {
55 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
56 	__u32 csum;
57 	__u16 dummy_csum = 0;
58 	int offset = offsetof(struct ext4_inode, i_checksum_lo);
59 	unsigned int csum_size = sizeof(dummy_csum);
60 
61 	csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw, offset);
62 	csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, csum_size);
63 	offset += csum_size;
64 	csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
65 			   EXT4_GOOD_OLD_INODE_SIZE - offset);
66 
67 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
68 		offset = offsetof(struct ext4_inode, i_checksum_hi);
69 		csum = ext4_chksum(sbi, csum, (__u8 *)raw +
70 				   EXT4_GOOD_OLD_INODE_SIZE,
71 				   offset - EXT4_GOOD_OLD_INODE_SIZE);
72 		if (EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
73 			csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum,
74 					   csum_size);
75 			offset += csum_size;
76 		}
77 		csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
78 				   EXT4_INODE_SIZE(inode->i_sb) - offset);
79 	}
80 
81 	return csum;
82 }
83 
ext4_inode_csum_verify(struct inode * inode,struct ext4_inode * raw,struct ext4_inode_info * ei)84 static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
85 				  struct ext4_inode_info *ei)
86 {
87 	__u32 provided, calculated;
88 
89 	if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
90 	    cpu_to_le32(EXT4_OS_LINUX) ||
91 	    !ext4_has_metadata_csum(inode->i_sb))
92 		return 1;
93 
94 	provided = le16_to_cpu(raw->i_checksum_lo);
95 	calculated = ext4_inode_csum(inode, raw, ei);
96 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
97 	    EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
98 		provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
99 	else
100 		calculated &= 0xFFFF;
101 
102 	return provided == calculated;
103 }
104 
ext4_inode_csum_set(struct inode * inode,struct ext4_inode * raw,struct ext4_inode_info * ei)105 void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
106 			 struct ext4_inode_info *ei)
107 {
108 	__u32 csum;
109 
110 	if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
111 	    cpu_to_le32(EXT4_OS_LINUX) ||
112 	    !ext4_has_metadata_csum(inode->i_sb))
113 		return;
114 
115 	csum = ext4_inode_csum(inode, raw, ei);
116 	raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
117 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
118 	    EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
119 		raw->i_checksum_hi = cpu_to_le16(csum >> 16);
120 }
121 
ext4_begin_ordered_truncate(struct inode * inode,loff_t new_size)122 static inline int ext4_begin_ordered_truncate(struct inode *inode,
123 					      loff_t new_size)
124 {
125 	trace_ext4_begin_ordered_truncate(inode, new_size);
126 	/*
127 	 * If jinode is zero, then we never opened the file for
128 	 * writing, so there's no need to call
129 	 * jbd2_journal_begin_ordered_truncate() since there's no
130 	 * outstanding writes we need to flush.
131 	 */
132 	if (!EXT4_I(inode)->jinode)
133 		return 0;
134 	return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
135 						   EXT4_I(inode)->jinode,
136 						   new_size);
137 }
138 
139 static int __ext4_journalled_writepage(struct page *page, unsigned int len);
140 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
141 				  int pextents);
142 
143 /*
144  * Test whether an inode is a fast symlink.
145  * A fast symlink has its symlink data stored in ext4_inode_info->i_data.
146  */
ext4_inode_is_fast_symlink(struct inode * inode)147 int ext4_inode_is_fast_symlink(struct inode *inode)
148 {
149 	if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
150 		int ea_blocks = EXT4_I(inode)->i_file_acl ?
151 				EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
152 
153 		if (ext4_has_inline_data(inode))
154 			return 0;
155 
156 		return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
157 	}
158 	return S_ISLNK(inode->i_mode) && inode->i_size &&
159 	       (inode->i_size < EXT4_N_BLOCKS * 4);
160 }
161 
162 /*
163  * Called at the last iput() if i_nlink is zero.
164  */
ext4_evict_inode(struct inode * inode)165 void ext4_evict_inode(struct inode *inode)
166 {
167 	handle_t *handle;
168 	int err;
169 	/*
170 	 * Credits for final inode cleanup and freeing:
171 	 * sb + inode (ext4_orphan_del()), block bitmap, group descriptor
172 	 * (xattr block freeing), bitmap, group descriptor (inode freeing)
173 	 */
174 	int extra_credits = 6;
175 	struct ext4_xattr_inode_array *ea_inode_array = NULL;
176 	bool freeze_protected = false;
177 
178 	trace_ext4_evict_inode(inode);
179 
180 	if (EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)
181 		ext4_evict_ea_inode(inode);
182 	if (inode->i_nlink) {
183 		/*
184 		 * When journalling data dirty buffers are tracked only in the
185 		 * journal. So although mm thinks everything is clean and
186 		 * ready for reaping the inode might still have some pages to
187 		 * write in the running transaction or waiting to be
188 		 * checkpointed. Thus calling jbd2_journal_invalidate_folio()
189 		 * (via truncate_inode_pages()) to discard these buffers can
190 		 * cause data loss. Also even if we did not discard these
191 		 * buffers, we would have no way to find them after the inode
192 		 * is reaped and thus user could see stale data if he tries to
193 		 * read them before the transaction is checkpointed. So be
194 		 * careful and force everything to disk here... We use
195 		 * ei->i_datasync_tid to store the newest transaction
196 		 * containing inode's data.
197 		 *
198 		 * Note that directories do not have this problem because they
199 		 * don't use page cache.
200 		 */
201 		if (inode->i_ino != EXT4_JOURNAL_INO &&
202 		    ext4_should_journal_data(inode) &&
203 		    S_ISREG(inode->i_mode) && inode->i_data.nrpages) {
204 			journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
205 			tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
206 
207 			jbd2_complete_transaction(journal, commit_tid);
208 			filemap_write_and_wait(&inode->i_data);
209 		}
210 		truncate_inode_pages_final(&inode->i_data);
211 
212 		goto no_delete;
213 	}
214 
215 	if (is_bad_inode(inode))
216 		goto no_delete;
217 	dquot_initialize(inode);
218 
219 	if (ext4_should_order_data(inode))
220 		ext4_begin_ordered_truncate(inode, 0);
221 	truncate_inode_pages_final(&inode->i_data);
222 
223 	/*
224 	 * For inodes with journalled data, transaction commit could have
225 	 * dirtied the inode. And for inodes with dioread_nolock, unwritten
226 	 * extents converting worker could merge extents and also have dirtied
227 	 * the inode. Flush worker is ignoring it because of I_FREEING flag but
228 	 * we still need to remove the inode from the writeback lists.
229 	 */
230 	if (!list_empty_careful(&inode->i_io_list))
231 		inode_io_list_del(inode);
232 
233 	/*
234 	 * Protect us against freezing - iput() caller didn't have to have any
235 	 * protection against it. When we are in a running transaction though,
236 	 * we are already protected against freezing and we cannot grab further
237 	 * protection due to lock ordering constraints.
238 	 */
239 	if (!ext4_journal_current_handle()) {
240 		sb_start_intwrite(inode->i_sb);
241 		freeze_protected = true;
242 	}
243 
244 	if (!IS_NOQUOTA(inode))
245 		extra_credits += EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb);
246 
247 	/*
248 	 * Block bitmap, group descriptor, and inode are accounted in both
249 	 * ext4_blocks_for_truncate() and extra_credits. So subtract 3.
250 	 */
251 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
252 			 ext4_blocks_for_truncate(inode) + extra_credits - 3);
253 	if (IS_ERR(handle)) {
254 		ext4_std_error(inode->i_sb, PTR_ERR(handle));
255 		/*
256 		 * If we're going to skip the normal cleanup, we still need to
257 		 * make sure that the in-core orphan linked list is properly
258 		 * cleaned up.
259 		 */
260 		ext4_orphan_del(NULL, inode);
261 		if (freeze_protected)
262 			sb_end_intwrite(inode->i_sb);
263 		goto no_delete;
264 	}
265 
266 	if (IS_SYNC(inode))
267 		ext4_handle_sync(handle);
268 
269 	/*
270 	 * Set inode->i_size to 0 before calling ext4_truncate(). We need
271 	 * special handling of symlinks here because i_size is used to
272 	 * determine whether ext4_inode_info->i_data contains symlink data or
273 	 * block mappings. Setting i_size to 0 will remove its fast symlink
274 	 * status. Erase i_data so that it becomes a valid empty block map.
275 	 */
276 	if (ext4_inode_is_fast_symlink(inode))
277 		memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data));
278 	inode->i_size = 0;
279 	err = ext4_mark_inode_dirty(handle, inode);
280 	if (err) {
281 		ext4_warning(inode->i_sb,
282 			     "couldn't mark inode dirty (err %d)", err);
283 		goto stop_handle;
284 	}
285 	if (inode->i_blocks) {
286 		err = ext4_truncate(inode);
287 		if (err) {
288 			ext4_error_err(inode->i_sb, -err,
289 				       "couldn't truncate inode %lu (err %d)",
290 				       inode->i_ino, err);
291 			goto stop_handle;
292 		}
293 	}
294 
295 	/* Remove xattr references. */
296 	err = ext4_xattr_delete_inode(handle, inode, &ea_inode_array,
297 				      extra_credits);
298 	if (err) {
299 		ext4_warning(inode->i_sb, "xattr delete (err %d)", err);
300 stop_handle:
301 		ext4_journal_stop(handle);
302 		ext4_orphan_del(NULL, inode);
303 		if (freeze_protected)
304 			sb_end_intwrite(inode->i_sb);
305 		ext4_xattr_inode_array_free(ea_inode_array);
306 		goto no_delete;
307 	}
308 
309 	/*
310 	 * Kill off the orphan record which ext4_truncate created.
311 	 * AKPM: I think this can be inside the above `if'.
312 	 * Note that ext4_orphan_del() has to be able to cope with the
313 	 * deletion of a non-existent orphan - this is because we don't
314 	 * know if ext4_truncate() actually created an orphan record.
315 	 * (Well, we could do this if we need to, but heck - it works)
316 	 */
317 	ext4_orphan_del(handle, inode);
318 	EXT4_I(inode)->i_dtime	= (__u32)ktime_get_real_seconds();
319 
320 	/*
321 	 * One subtle ordering requirement: if anything has gone wrong
322 	 * (transaction abort, IO errors, whatever), then we can still
323 	 * do these next steps (the fs will already have been marked as
324 	 * having errors), but we can't free the inode if the mark_dirty
325 	 * fails.
326 	 */
327 	if (ext4_mark_inode_dirty(handle, inode))
328 		/* If that failed, just do the required in-core inode clear. */
329 		ext4_clear_inode(inode);
330 	else
331 		ext4_free_inode(handle, inode);
332 	ext4_journal_stop(handle);
333 	if (freeze_protected)
334 		sb_end_intwrite(inode->i_sb);
335 	ext4_xattr_inode_array_free(ea_inode_array);
336 	return;
337 no_delete:
338 	/*
339 	 * Check out some where else accidentally dirty the evicting inode,
340 	 * which may probably cause inode use-after-free issues later.
341 	 */
342 	WARN_ON_ONCE(!list_empty_careful(&inode->i_io_list));
343 
344 	if (!list_empty(&EXT4_I(inode)->i_fc_list))
345 		ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_NOMEM, NULL);
346 	ext4_clear_inode(inode);	/* We must guarantee clearing of inode... */
347 }
348 
349 #ifdef CONFIG_QUOTA
ext4_get_reserved_space(struct inode * inode)350 qsize_t *ext4_get_reserved_space(struct inode *inode)
351 {
352 	return &EXT4_I(inode)->i_reserved_quota;
353 }
354 #endif
355 
356 /*
357  * Called with i_data_sem down, which is important since we can call
358  * ext4_discard_preallocations() from here.
359  */
ext4_da_update_reserve_space(struct inode * inode,int used,int quota_claim)360 void ext4_da_update_reserve_space(struct inode *inode,
361 					int used, int quota_claim)
362 {
363 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
364 	struct ext4_inode_info *ei = EXT4_I(inode);
365 
366 	spin_lock(&ei->i_block_reservation_lock);
367 	trace_ext4_da_update_reserve_space(inode, used, quota_claim);
368 	if (unlikely(used > ei->i_reserved_data_blocks)) {
369 		ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
370 			 "with only %d reserved data blocks",
371 			 __func__, inode->i_ino, used,
372 			 ei->i_reserved_data_blocks);
373 		WARN_ON(1);
374 		used = ei->i_reserved_data_blocks;
375 	}
376 
377 	/* Update per-inode reservations */
378 	ei->i_reserved_data_blocks -= used;
379 	percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
380 
381 	spin_unlock(&ei->i_block_reservation_lock);
382 
383 	/* Update quota subsystem for data blocks */
384 	if (quota_claim)
385 		dquot_claim_block(inode, EXT4_C2B(sbi, used));
386 	else {
387 		/*
388 		 * We did fallocate with an offset that is already delayed
389 		 * allocated. So on delayed allocated writeback we should
390 		 * not re-claim the quota for fallocated blocks.
391 		 */
392 		dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
393 	}
394 
395 	/*
396 	 * If we have done all the pending block allocations and if
397 	 * there aren't any writers on the inode, we can discard the
398 	 * inode's preallocations.
399 	 */
400 	if ((ei->i_reserved_data_blocks == 0) &&
401 	    !inode_is_open_for_write(inode))
402 		ext4_discard_preallocations(inode, 0);
403 }
404 
__check_block_validity(struct inode * inode,const char * func,unsigned int line,struct ext4_map_blocks * map)405 static int __check_block_validity(struct inode *inode, const char *func,
406 				unsigned int line,
407 				struct ext4_map_blocks *map)
408 {
409 	if (ext4_has_feature_journal(inode->i_sb) &&
410 	    (inode->i_ino ==
411 	     le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum)))
412 		return 0;
413 	if (!ext4_inode_block_valid(inode, map->m_pblk, map->m_len)) {
414 		ext4_error_inode(inode, func, line, map->m_pblk,
415 				 "lblock %lu mapped to illegal pblock %llu "
416 				 "(length %d)", (unsigned long) map->m_lblk,
417 				 map->m_pblk, map->m_len);
418 		return -EFSCORRUPTED;
419 	}
420 	return 0;
421 }
422 
ext4_issue_zeroout(struct inode * inode,ext4_lblk_t lblk,ext4_fsblk_t pblk,ext4_lblk_t len)423 int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
424 		       ext4_lblk_t len)
425 {
426 	int ret;
427 
428 	if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode))
429 		return fscrypt_zeroout_range(inode, lblk, pblk, len);
430 
431 	ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
432 	if (ret > 0)
433 		ret = 0;
434 
435 	return ret;
436 }
437 
438 #define check_block_validity(inode, map)	\
439 	__check_block_validity((inode), __func__, __LINE__, (map))
440 
441 #ifdef ES_AGGRESSIVE_TEST
ext4_map_blocks_es_recheck(handle_t * handle,struct inode * inode,struct ext4_map_blocks * es_map,struct ext4_map_blocks * map,int flags)442 static void ext4_map_blocks_es_recheck(handle_t *handle,
443 				       struct inode *inode,
444 				       struct ext4_map_blocks *es_map,
445 				       struct ext4_map_blocks *map,
446 				       int flags)
447 {
448 	int retval;
449 
450 	map->m_flags = 0;
451 	/*
452 	 * There is a race window that the result is not the same.
453 	 * e.g. xfstests #223 when dioread_nolock enables.  The reason
454 	 * is that we lookup a block mapping in extent status tree with
455 	 * out taking i_data_sem.  So at the time the unwritten extent
456 	 * could be converted.
457 	 */
458 	down_read(&EXT4_I(inode)->i_data_sem);
459 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
460 		retval = ext4_ext_map_blocks(handle, inode, map, 0);
461 	} else {
462 		retval = ext4_ind_map_blocks(handle, inode, map, 0);
463 	}
464 	up_read((&EXT4_I(inode)->i_data_sem));
465 
466 	/*
467 	 * We don't check m_len because extent will be collpased in status
468 	 * tree.  So the m_len might not equal.
469 	 */
470 	if (es_map->m_lblk != map->m_lblk ||
471 	    es_map->m_flags != map->m_flags ||
472 	    es_map->m_pblk != map->m_pblk) {
473 		printk("ES cache assertion failed for inode: %lu "
474 		       "es_cached ex [%d/%d/%llu/%x] != "
475 		       "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
476 		       inode->i_ino, es_map->m_lblk, es_map->m_len,
477 		       es_map->m_pblk, es_map->m_flags, map->m_lblk,
478 		       map->m_len, map->m_pblk, map->m_flags,
479 		       retval, flags);
480 	}
481 }
482 #endif /* ES_AGGRESSIVE_TEST */
483 
484 /*
485  * The ext4_map_blocks() function tries to look up the requested blocks,
486  * and returns if the blocks are already mapped.
487  *
488  * Otherwise it takes the write lock of the i_data_sem and allocate blocks
489  * and store the allocated blocks in the result buffer head and mark it
490  * mapped.
491  *
492  * If file type is extents based, it will call ext4_ext_map_blocks(),
493  * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
494  * based files
495  *
496  * On success, it returns the number of blocks being mapped or allocated.  if
497  * create==0 and the blocks are pre-allocated and unwritten, the resulting @map
498  * is marked as unwritten. If the create == 1, it will mark @map as mapped.
499  *
500  * It returns 0 if plain look up failed (blocks have not been allocated), in
501  * that case, @map is returned as unmapped but we still do fill map->m_len to
502  * indicate the length of a hole starting at map->m_lblk.
503  *
504  * It returns the error in case of allocation failure.
505  */
ext4_map_blocks(handle_t * handle,struct inode * inode,struct ext4_map_blocks * map,int flags)506 int ext4_map_blocks(handle_t *handle, struct inode *inode,
507 		    struct ext4_map_blocks *map, int flags)
508 {
509 	struct extent_status es;
510 	int retval;
511 	int ret = 0;
512 #ifdef ES_AGGRESSIVE_TEST
513 	struct ext4_map_blocks orig_map;
514 
515 	memcpy(&orig_map, map, sizeof(*map));
516 #endif
517 
518 	map->m_flags = 0;
519 	ext_debug(inode, "flag 0x%x, max_blocks %u, logical block %lu\n",
520 		  flags, map->m_len, (unsigned long) map->m_lblk);
521 
522 	/*
523 	 * ext4_map_blocks returns an int, and m_len is an unsigned int
524 	 */
525 	if (unlikely(map->m_len > INT_MAX))
526 		map->m_len = INT_MAX;
527 
528 	/* We can handle the block number less than EXT_MAX_BLOCKS */
529 	if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
530 		return -EFSCORRUPTED;
531 
532 	/* Lookup extent status tree firstly */
533 	if (!(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY) &&
534 	    ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
535 		if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
536 			map->m_pblk = ext4_es_pblock(&es) +
537 					map->m_lblk - es.es_lblk;
538 			map->m_flags |= ext4_es_is_written(&es) ?
539 					EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
540 			retval = es.es_len - (map->m_lblk - es.es_lblk);
541 			if (retval > map->m_len)
542 				retval = map->m_len;
543 			map->m_len = retval;
544 		} else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
545 			map->m_pblk = 0;
546 			retval = es.es_len - (map->m_lblk - es.es_lblk);
547 			if (retval > map->m_len)
548 				retval = map->m_len;
549 			map->m_len = retval;
550 			retval = 0;
551 		} else {
552 			BUG();
553 		}
554 
555 		if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
556 			return retval;
557 #ifdef ES_AGGRESSIVE_TEST
558 		ext4_map_blocks_es_recheck(handle, inode, map,
559 					   &orig_map, flags);
560 #endif
561 		goto found;
562 	}
563 	/*
564 	 * In the query cache no-wait mode, nothing we can do more if we
565 	 * cannot find extent in the cache.
566 	 */
567 	if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
568 		return 0;
569 
570 	/*
571 	 * Try to see if we can get the block without requesting a new
572 	 * file system block.
573 	 */
574 	down_read(&EXT4_I(inode)->i_data_sem);
575 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
576 		retval = ext4_ext_map_blocks(handle, inode, map, 0);
577 	} else {
578 		retval = ext4_ind_map_blocks(handle, inode, map, 0);
579 	}
580 	if (retval > 0) {
581 		unsigned int status;
582 
583 		if (unlikely(retval != map->m_len)) {
584 			ext4_warning(inode->i_sb,
585 				     "ES len assertion failed for inode "
586 				     "%lu: retval %d != map->m_len %d",
587 				     inode->i_ino, retval, map->m_len);
588 			WARN_ON(1);
589 		}
590 
591 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
592 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
593 		if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
594 		    !(status & EXTENT_STATUS_WRITTEN) &&
595 		    ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
596 				       map->m_lblk + map->m_len - 1))
597 			status |= EXTENT_STATUS_DELAYED;
598 		ret = ext4_es_insert_extent(inode, map->m_lblk,
599 					    map->m_len, map->m_pblk, status);
600 		if (ret < 0)
601 			retval = ret;
602 	}
603 	up_read((&EXT4_I(inode)->i_data_sem));
604 
605 found:
606 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
607 		ret = check_block_validity(inode, map);
608 		if (ret != 0)
609 			return ret;
610 	}
611 
612 	/* If it is only a block(s) look up */
613 	if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
614 		return retval;
615 
616 	/*
617 	 * Returns if the blocks have already allocated
618 	 *
619 	 * Note that if blocks have been preallocated
620 	 * ext4_ext_get_block() returns the create = 0
621 	 * with buffer head unmapped.
622 	 */
623 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
624 		/*
625 		 * If we need to convert extent to unwritten
626 		 * we continue and do the actual work in
627 		 * ext4_ext_map_blocks()
628 		 */
629 		if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
630 			return retval;
631 
632 	/*
633 	 * Here we clear m_flags because after allocating an new extent,
634 	 * it will be set again.
635 	 */
636 	map->m_flags &= ~EXT4_MAP_FLAGS;
637 
638 	/*
639 	 * New blocks allocate and/or writing to unwritten extent
640 	 * will possibly result in updating i_data, so we take
641 	 * the write lock of i_data_sem, and call get_block()
642 	 * with create == 1 flag.
643 	 */
644 	down_write(&EXT4_I(inode)->i_data_sem);
645 
646 	/*
647 	 * We need to check for EXT4 here because migrate
648 	 * could have changed the inode type in between
649 	 */
650 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
651 		retval = ext4_ext_map_blocks(handle, inode, map, flags);
652 	} else {
653 		retval = ext4_ind_map_blocks(handle, inode, map, flags);
654 
655 		if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
656 			/*
657 			 * We allocated new blocks which will result in
658 			 * i_data's format changing.  Force the migrate
659 			 * to fail by clearing migrate flags
660 			 */
661 			ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
662 		}
663 
664 		/*
665 		 * Update reserved blocks/metadata blocks after successful
666 		 * block allocation which had been deferred till now. We don't
667 		 * support fallocate for non extent files. So we can update
668 		 * reserve space here.
669 		 */
670 		if ((retval > 0) &&
671 			(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
672 			ext4_da_update_reserve_space(inode, retval, 1);
673 	}
674 
675 	if (retval > 0) {
676 		unsigned int status;
677 
678 		if (unlikely(retval != map->m_len)) {
679 			ext4_warning(inode->i_sb,
680 				     "ES len assertion failed for inode "
681 				     "%lu: retval %d != map->m_len %d",
682 				     inode->i_ino, retval, map->m_len);
683 			WARN_ON(1);
684 		}
685 
686 		/*
687 		 * We have to zeroout blocks before inserting them into extent
688 		 * status tree. Otherwise someone could look them up there and
689 		 * use them before they are really zeroed. We also have to
690 		 * unmap metadata before zeroing as otherwise writeback can
691 		 * overwrite zeros with stale data from block device.
692 		 */
693 		if (flags & EXT4_GET_BLOCKS_ZERO &&
694 		    map->m_flags & EXT4_MAP_MAPPED &&
695 		    map->m_flags & EXT4_MAP_NEW) {
696 			ret = ext4_issue_zeroout(inode, map->m_lblk,
697 						 map->m_pblk, map->m_len);
698 			if (ret) {
699 				retval = ret;
700 				goto out_sem;
701 			}
702 		}
703 
704 		/*
705 		 * If the extent has been zeroed out, we don't need to update
706 		 * extent status tree.
707 		 */
708 		if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
709 		    ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
710 			if (ext4_es_is_written(&es))
711 				goto out_sem;
712 		}
713 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
714 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
715 		if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
716 		    !(status & EXTENT_STATUS_WRITTEN) &&
717 		    ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
718 				       map->m_lblk + map->m_len - 1))
719 			status |= EXTENT_STATUS_DELAYED;
720 		ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
721 					    map->m_pblk, status);
722 		if (ret < 0) {
723 			retval = ret;
724 			goto out_sem;
725 		}
726 	}
727 
728 out_sem:
729 	up_write((&EXT4_I(inode)->i_data_sem));
730 	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
731 		ret = check_block_validity(inode, map);
732 		if (ret != 0)
733 			return ret;
734 
735 		/*
736 		 * Inodes with freshly allocated blocks where contents will be
737 		 * visible after transaction commit must be on transaction's
738 		 * ordered data list.
739 		 */
740 		if (map->m_flags & EXT4_MAP_NEW &&
741 		    !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
742 		    !(flags & EXT4_GET_BLOCKS_ZERO) &&
743 		    !ext4_is_quota_file(inode) &&
744 		    ext4_should_order_data(inode)) {
745 			loff_t start_byte =
746 				(loff_t)map->m_lblk << inode->i_blkbits;
747 			loff_t length = (loff_t)map->m_len << inode->i_blkbits;
748 
749 			if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
750 				ret = ext4_jbd2_inode_add_wait(handle, inode,
751 						start_byte, length);
752 			else
753 				ret = ext4_jbd2_inode_add_write(handle, inode,
754 						start_byte, length);
755 			if (ret)
756 				return ret;
757 		}
758 	}
759 	if (retval > 0 && (map->m_flags & EXT4_MAP_UNWRITTEN ||
760 				map->m_flags & EXT4_MAP_MAPPED))
761 		ext4_fc_track_range(handle, inode, map->m_lblk,
762 					map->m_lblk + map->m_len - 1);
763 	if (retval < 0)
764 		ext_debug(inode, "failed with err %d\n", retval);
765 	return retval;
766 }
767 
768 /*
769  * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
770  * we have to be careful as someone else may be manipulating b_state as well.
771  */
ext4_update_bh_state(struct buffer_head * bh,unsigned long flags)772 static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
773 {
774 	unsigned long old_state;
775 	unsigned long new_state;
776 
777 	flags &= EXT4_MAP_FLAGS;
778 
779 	/* Dummy buffer_head? Set non-atomically. */
780 	if (!bh->b_page) {
781 		bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
782 		return;
783 	}
784 	/*
785 	 * Someone else may be modifying b_state. Be careful! This is ugly but
786 	 * once we get rid of using bh as a container for mapping information
787 	 * to pass to / from get_block functions, this can go away.
788 	 */
789 	do {
790 		old_state = READ_ONCE(bh->b_state);
791 		new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
792 	} while (unlikely(
793 		 cmpxchg(&bh->b_state, old_state, new_state) != old_state));
794 }
795 
_ext4_get_block(struct inode * inode,sector_t iblock,struct buffer_head * bh,int flags)796 static int _ext4_get_block(struct inode *inode, sector_t iblock,
797 			   struct buffer_head *bh, int flags)
798 {
799 	struct ext4_map_blocks map;
800 	int ret = 0;
801 
802 	if (ext4_has_inline_data(inode))
803 		return -ERANGE;
804 
805 	map.m_lblk = iblock;
806 	map.m_len = bh->b_size >> inode->i_blkbits;
807 
808 	ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
809 			      flags);
810 	if (ret > 0) {
811 		map_bh(bh, inode->i_sb, map.m_pblk);
812 		ext4_update_bh_state(bh, map.m_flags);
813 		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
814 		ret = 0;
815 	} else if (ret == 0) {
816 		/* hole case, need to fill in bh->b_size */
817 		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
818 	}
819 	return ret;
820 }
821 
ext4_get_block(struct inode * inode,sector_t iblock,struct buffer_head * bh,int create)822 int ext4_get_block(struct inode *inode, sector_t iblock,
823 		   struct buffer_head *bh, int create)
824 {
825 	return _ext4_get_block(inode, iblock, bh,
826 			       create ? EXT4_GET_BLOCKS_CREATE : 0);
827 }
828 
829 /*
830  * Get block function used when preparing for buffered write if we require
831  * creating an unwritten extent if blocks haven't been allocated.  The extent
832  * will be converted to written after the IO is complete.
833  */
ext4_get_block_unwritten(struct inode * inode,sector_t iblock,struct buffer_head * bh_result,int create)834 int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
835 			     struct buffer_head *bh_result, int create)
836 {
837 	ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
838 		   inode->i_ino, create);
839 	return _ext4_get_block(inode, iblock, bh_result,
840 			       EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT);
841 }
842 
843 /* Maximum number of blocks we map for direct IO at once. */
844 #define DIO_MAX_BLOCKS 4096
845 
846 /*
847  * `handle' can be NULL if create is zero
848  */
ext4_getblk(handle_t * handle,struct inode * inode,ext4_lblk_t block,int map_flags)849 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
850 				ext4_lblk_t block, int map_flags)
851 {
852 	struct ext4_map_blocks map;
853 	struct buffer_head *bh;
854 	int create = map_flags & EXT4_GET_BLOCKS_CREATE;
855 	bool nowait = map_flags & EXT4_GET_BLOCKS_CACHED_NOWAIT;
856 	int err;
857 
858 	ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
859 		    || handle != NULL || create == 0);
860 	ASSERT(create == 0 || !nowait);
861 
862 	map.m_lblk = block;
863 	map.m_len = 1;
864 	err = ext4_map_blocks(handle, inode, &map, map_flags);
865 
866 	if (err == 0)
867 		return create ? ERR_PTR(-ENOSPC) : NULL;
868 	if (err < 0)
869 		return ERR_PTR(err);
870 
871 	if (nowait)
872 		return sb_find_get_block(inode->i_sb, map.m_pblk);
873 
874 	bh = sb_getblk(inode->i_sb, map.m_pblk);
875 	if (unlikely(!bh))
876 		return ERR_PTR(-ENOMEM);
877 	if (map.m_flags & EXT4_MAP_NEW) {
878 		ASSERT(create != 0);
879 		ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
880 			    || (handle != NULL));
881 
882 		/*
883 		 * Now that we do not always journal data, we should
884 		 * keep in mind whether this should always journal the
885 		 * new buffer as metadata.  For now, regular file
886 		 * writes use ext4_get_block instead, so it's not a
887 		 * problem.
888 		 */
889 		lock_buffer(bh);
890 		BUFFER_TRACE(bh, "call get_create_access");
891 		err = ext4_journal_get_create_access(handle, inode->i_sb, bh,
892 						     EXT4_JTR_NONE);
893 		if (unlikely(err)) {
894 			unlock_buffer(bh);
895 			goto errout;
896 		}
897 		if (!buffer_uptodate(bh)) {
898 			memset(bh->b_data, 0, inode->i_sb->s_blocksize);
899 			set_buffer_uptodate(bh);
900 		}
901 		unlock_buffer(bh);
902 		BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
903 		err = ext4_handle_dirty_metadata(handle, inode, bh);
904 		if (unlikely(err))
905 			goto errout;
906 	} else
907 		BUFFER_TRACE(bh, "not a new buffer");
908 	return bh;
909 errout:
910 	brelse(bh);
911 	return ERR_PTR(err);
912 }
913 
ext4_bread(handle_t * handle,struct inode * inode,ext4_lblk_t block,int map_flags)914 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
915 			       ext4_lblk_t block, int map_flags)
916 {
917 	struct buffer_head *bh;
918 	int ret;
919 
920 	bh = ext4_getblk(handle, inode, block, map_flags);
921 	if (IS_ERR(bh))
922 		return bh;
923 	if (!bh || ext4_buffer_uptodate(bh))
924 		return bh;
925 
926 	ret = ext4_read_bh_lock(bh, REQ_META | REQ_PRIO, true);
927 	if (ret) {
928 		put_bh(bh);
929 		return ERR_PTR(ret);
930 	}
931 	return bh;
932 }
933 
934 /* Read a contiguous batch of blocks. */
ext4_bread_batch(struct inode * inode,ext4_lblk_t block,int bh_count,bool wait,struct buffer_head ** bhs)935 int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
936 		     bool wait, struct buffer_head **bhs)
937 {
938 	int i, err;
939 
940 	for (i = 0; i < bh_count; i++) {
941 		bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
942 		if (IS_ERR(bhs[i])) {
943 			err = PTR_ERR(bhs[i]);
944 			bh_count = i;
945 			goto out_brelse;
946 		}
947 	}
948 
949 	for (i = 0; i < bh_count; i++)
950 		/* Note that NULL bhs[i] is valid because of holes. */
951 		if (bhs[i] && !ext4_buffer_uptodate(bhs[i]))
952 			ext4_read_bh_lock(bhs[i], REQ_META | REQ_PRIO, false);
953 
954 	if (!wait)
955 		return 0;
956 
957 	for (i = 0; i < bh_count; i++)
958 		if (bhs[i])
959 			wait_on_buffer(bhs[i]);
960 
961 	for (i = 0; i < bh_count; i++) {
962 		if (bhs[i] && !buffer_uptodate(bhs[i])) {
963 			err = -EIO;
964 			goto out_brelse;
965 		}
966 	}
967 	return 0;
968 
969 out_brelse:
970 	for (i = 0; i < bh_count; i++) {
971 		brelse(bhs[i]);
972 		bhs[i] = NULL;
973 	}
974 	return err;
975 }
976 
ext4_walk_page_buffers(handle_t * handle,struct inode * inode,struct buffer_head * head,unsigned from,unsigned to,int * partial,int (* fn)(handle_t * handle,struct inode * inode,struct buffer_head * bh))977 int ext4_walk_page_buffers(handle_t *handle, struct inode *inode,
978 			   struct buffer_head *head,
979 			   unsigned from,
980 			   unsigned to,
981 			   int *partial,
982 			   int (*fn)(handle_t *handle, struct inode *inode,
983 				     struct buffer_head *bh))
984 {
985 	struct buffer_head *bh;
986 	unsigned block_start, block_end;
987 	unsigned blocksize = head->b_size;
988 	int err, ret = 0;
989 	struct buffer_head *next;
990 
991 	for (bh = head, block_start = 0;
992 	     ret == 0 && (bh != head || !block_start);
993 	     block_start = block_end, bh = next) {
994 		next = bh->b_this_page;
995 		block_end = block_start + blocksize;
996 		if (block_end <= from || block_start >= to) {
997 			if (partial && !buffer_uptodate(bh))
998 				*partial = 1;
999 			continue;
1000 		}
1001 		err = (*fn)(handle, inode, bh);
1002 		if (!ret)
1003 			ret = err;
1004 	}
1005 	return ret;
1006 }
1007 
1008 /*
1009  * To preserve ordering, it is essential that the hole instantiation and
1010  * the data write be encapsulated in a single transaction.  We cannot
1011  * close off a transaction and start a new one between the ext4_get_block()
1012  * and the commit_write().  So doing the jbd2_journal_start at the start of
1013  * prepare_write() is the right place.
1014  *
1015  * Also, this function can nest inside ext4_writepage().  In that case, we
1016  * *know* that ext4_writepage() has generated enough buffer credits to do the
1017  * whole page.  So we won't block on the journal in that case, which is good,
1018  * because the caller may be PF_MEMALLOC.
1019  *
1020  * By accident, ext4 can be reentered when a transaction is open via
1021  * quota file writes.  If we were to commit the transaction while thus
1022  * reentered, there can be a deadlock - we would be holding a quota
1023  * lock, and the commit would never complete if another thread had a
1024  * transaction open and was blocking on the quota lock - a ranking
1025  * violation.
1026  *
1027  * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
1028  * will _not_ run commit under these circumstances because handle->h_ref
1029  * is elevated.  We'll still have enough credits for the tiny quotafile
1030  * write.
1031  */
do_journal_get_write_access(handle_t * handle,struct inode * inode,struct buffer_head * bh)1032 int do_journal_get_write_access(handle_t *handle, struct inode *inode,
1033 				struct buffer_head *bh)
1034 {
1035 	int dirty = buffer_dirty(bh);
1036 	int ret;
1037 
1038 	if (!buffer_mapped(bh) || buffer_freed(bh))
1039 		return 0;
1040 	/*
1041 	 * __block_write_begin() could have dirtied some buffers. Clean
1042 	 * the dirty bit as jbd2_journal_get_write_access() could complain
1043 	 * otherwise about fs integrity issues. Setting of the dirty bit
1044 	 * by __block_write_begin() isn't a real problem here as we clear
1045 	 * the bit before releasing a page lock and thus writeback cannot
1046 	 * ever write the buffer.
1047 	 */
1048 	if (dirty)
1049 		clear_buffer_dirty(bh);
1050 	BUFFER_TRACE(bh, "get write access");
1051 	ret = ext4_journal_get_write_access(handle, inode->i_sb, bh,
1052 					    EXT4_JTR_NONE);
1053 	if (!ret && dirty)
1054 		ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1055 	return ret;
1056 }
1057 
1058 #ifdef CONFIG_FS_ENCRYPTION
ext4_block_write_begin(struct page * page,loff_t pos,unsigned len,get_block_t * get_block)1059 static int ext4_block_write_begin(struct page *page, loff_t pos, unsigned len,
1060 				  get_block_t *get_block)
1061 {
1062 	unsigned from = pos & (PAGE_SIZE - 1);
1063 	unsigned to = from + len;
1064 	struct inode *inode = page->mapping->host;
1065 	unsigned block_start, block_end;
1066 	sector_t block;
1067 	int err = 0;
1068 	unsigned blocksize = inode->i_sb->s_blocksize;
1069 	unsigned bbits;
1070 	struct buffer_head *bh, *head, *wait[2];
1071 	int nr_wait = 0;
1072 	int i;
1073 
1074 	BUG_ON(!PageLocked(page));
1075 	BUG_ON(from > PAGE_SIZE);
1076 	BUG_ON(to > PAGE_SIZE);
1077 	BUG_ON(from > to);
1078 
1079 	if (!page_has_buffers(page))
1080 		create_empty_buffers(page, blocksize, 0);
1081 	head = page_buffers(page);
1082 	bbits = ilog2(blocksize);
1083 	block = (sector_t)page->index << (PAGE_SHIFT - bbits);
1084 
1085 	for (bh = head, block_start = 0; bh != head || !block_start;
1086 	    block++, block_start = block_end, bh = bh->b_this_page) {
1087 		block_end = block_start + blocksize;
1088 		if (block_end <= from || block_start >= to) {
1089 			if (PageUptodate(page)) {
1090 				set_buffer_uptodate(bh);
1091 			}
1092 			continue;
1093 		}
1094 		if (buffer_new(bh))
1095 			clear_buffer_new(bh);
1096 		if (!buffer_mapped(bh)) {
1097 			WARN_ON(bh->b_size != blocksize);
1098 			err = get_block(inode, block, bh, 1);
1099 			if (err)
1100 				break;
1101 			if (buffer_new(bh)) {
1102 				if (PageUptodate(page)) {
1103 					clear_buffer_new(bh);
1104 					set_buffer_uptodate(bh);
1105 					mark_buffer_dirty(bh);
1106 					continue;
1107 				}
1108 				if (block_end > to || block_start < from)
1109 					zero_user_segments(page, to, block_end,
1110 							   block_start, from);
1111 				continue;
1112 			}
1113 		}
1114 		if (PageUptodate(page)) {
1115 			set_buffer_uptodate(bh);
1116 			continue;
1117 		}
1118 		if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
1119 		    !buffer_unwritten(bh) &&
1120 		    (block_start < from || block_end > to)) {
1121 			ext4_read_bh_lock(bh, 0, false);
1122 			wait[nr_wait++] = bh;
1123 		}
1124 	}
1125 	/*
1126 	 * If we issued read requests, let them complete.
1127 	 */
1128 	for (i = 0; i < nr_wait; i++) {
1129 		wait_on_buffer(wait[i]);
1130 		if (!buffer_uptodate(wait[i]))
1131 			err = -EIO;
1132 	}
1133 	if (unlikely(err)) {
1134 		page_zero_new_buffers(page, from, to);
1135 	} else if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
1136 		for (i = 0; i < nr_wait; i++) {
1137 			int err2;
1138 
1139 			err2 = fscrypt_decrypt_pagecache_blocks(page, blocksize,
1140 								bh_offset(wait[i]));
1141 			if (err2) {
1142 				clear_buffer_uptodate(wait[i]);
1143 				err = err2;
1144 			}
1145 		}
1146 	}
1147 
1148 	return err;
1149 }
1150 #endif
1151 
ext4_write_begin(struct file * file,struct address_space * mapping,loff_t pos,unsigned len,struct page ** pagep,void ** fsdata)1152 static int ext4_write_begin(struct file *file, struct address_space *mapping,
1153 			    loff_t pos, unsigned len,
1154 			    struct page **pagep, void **fsdata)
1155 {
1156 	struct inode *inode = mapping->host;
1157 	int ret, needed_blocks;
1158 	handle_t *handle;
1159 	int retries = 0;
1160 	struct page *page;
1161 	pgoff_t index;
1162 	unsigned from, to;
1163 
1164 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
1165 		return -EIO;
1166 
1167 	trace_ext4_write_begin(inode, pos, len);
1168 	/*
1169 	 * Reserve one block more for addition to orphan list in case
1170 	 * we allocate blocks but write fails for some reason
1171 	 */
1172 	needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
1173 	index = pos >> PAGE_SHIFT;
1174 	from = pos & (PAGE_SIZE - 1);
1175 	to = from + len;
1176 
1177 	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1178 		ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1179 						    pagep);
1180 		if (ret < 0)
1181 			return ret;
1182 		if (ret == 1)
1183 			return 0;
1184 	}
1185 
1186 	/*
1187 	 * grab_cache_page_write_begin() can take a long time if the
1188 	 * system is thrashing due to memory pressure, or if the page
1189 	 * is being written back.  So grab it first before we start
1190 	 * the transaction handle.  This also allows us to allocate
1191 	 * the page (if needed) without using GFP_NOFS.
1192 	 */
1193 retry_grab:
1194 	page = grab_cache_page_write_begin(mapping, index);
1195 	if (!page)
1196 		return -ENOMEM;
1197 	/*
1198 	 * The same as page allocation, we prealloc buffer heads before
1199 	 * starting the handle.
1200 	 */
1201 	if (!page_has_buffers(page))
1202 		create_empty_buffers(page, inode->i_sb->s_blocksize, 0);
1203 
1204 	unlock_page(page);
1205 
1206 retry_journal:
1207 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1208 	if (IS_ERR(handle)) {
1209 		put_page(page);
1210 		return PTR_ERR(handle);
1211 	}
1212 
1213 	lock_page(page);
1214 	if (page->mapping != mapping) {
1215 		/* The page got truncated from under us */
1216 		unlock_page(page);
1217 		put_page(page);
1218 		ext4_journal_stop(handle);
1219 		goto retry_grab;
1220 	}
1221 	/* In case writeback began while the page was unlocked */
1222 	wait_for_stable_page(page);
1223 
1224 #ifdef CONFIG_FS_ENCRYPTION
1225 	if (ext4_should_dioread_nolock(inode))
1226 		ret = ext4_block_write_begin(page, pos, len,
1227 					     ext4_get_block_unwritten);
1228 	else
1229 		ret = ext4_block_write_begin(page, pos, len,
1230 					     ext4_get_block);
1231 #else
1232 	if (ext4_should_dioread_nolock(inode))
1233 		ret = __block_write_begin(page, pos, len,
1234 					  ext4_get_block_unwritten);
1235 	else
1236 		ret = __block_write_begin(page, pos, len, ext4_get_block);
1237 #endif
1238 	if (!ret && ext4_should_journal_data(inode)) {
1239 		ret = ext4_walk_page_buffers(handle, inode,
1240 					     page_buffers(page), from, to, NULL,
1241 					     do_journal_get_write_access);
1242 	}
1243 
1244 	if (ret) {
1245 		bool extended = (pos + len > inode->i_size) &&
1246 				!ext4_verity_in_progress(inode);
1247 
1248 		unlock_page(page);
1249 		/*
1250 		 * __block_write_begin may have instantiated a few blocks
1251 		 * outside i_size.  Trim these off again. Don't need
1252 		 * i_size_read because we hold i_rwsem.
1253 		 *
1254 		 * Add inode to orphan list in case we crash before
1255 		 * truncate finishes
1256 		 */
1257 		if (extended && ext4_can_truncate(inode))
1258 			ext4_orphan_add(handle, inode);
1259 
1260 		ext4_journal_stop(handle);
1261 		if (extended) {
1262 			ext4_truncate_failed_write(inode);
1263 			/*
1264 			 * If truncate failed early the inode might
1265 			 * still be on the orphan list; we need to
1266 			 * make sure the inode is removed from the
1267 			 * orphan list in that case.
1268 			 */
1269 			if (inode->i_nlink)
1270 				ext4_orphan_del(NULL, inode);
1271 		}
1272 
1273 		if (ret == -ENOSPC &&
1274 		    ext4_should_retry_alloc(inode->i_sb, &retries))
1275 			goto retry_journal;
1276 		put_page(page);
1277 		return ret;
1278 	}
1279 	*pagep = page;
1280 	return ret;
1281 }
1282 
1283 /* For write_end() in data=journal mode */
write_end_fn(handle_t * handle,struct inode * inode,struct buffer_head * bh)1284 static int write_end_fn(handle_t *handle, struct inode *inode,
1285 			struct buffer_head *bh)
1286 {
1287 	int ret;
1288 	if (!buffer_mapped(bh) || buffer_freed(bh))
1289 		return 0;
1290 	set_buffer_uptodate(bh);
1291 	ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1292 	clear_buffer_meta(bh);
1293 	clear_buffer_prio(bh);
1294 	return ret;
1295 }
1296 
1297 /*
1298  * We need to pick up the new inode size which generic_commit_write gave us
1299  * `file' can be NULL - eg, when called from page_symlink().
1300  *
1301  * ext4 never places buffers on inode->i_mapping->private_list.  metadata
1302  * buffers are managed internally.
1303  */
ext4_write_end(struct file * file,struct address_space * mapping,loff_t pos,unsigned len,unsigned copied,struct page * page,void * fsdata)1304 static int ext4_write_end(struct file *file,
1305 			  struct address_space *mapping,
1306 			  loff_t pos, unsigned len, unsigned copied,
1307 			  struct page *page, void *fsdata)
1308 {
1309 	handle_t *handle = ext4_journal_current_handle();
1310 	struct inode *inode = mapping->host;
1311 	loff_t old_size = inode->i_size;
1312 	int ret = 0, ret2;
1313 	int i_size_changed = 0;
1314 	bool verity = ext4_verity_in_progress(inode);
1315 
1316 	trace_ext4_write_end(inode, pos, len, copied);
1317 
1318 	if (ext4_has_inline_data(inode) &&
1319 	    ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA))
1320 		return ext4_write_inline_data_end(inode, pos, len, copied, page);
1321 
1322 	copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
1323 	/*
1324 	 * it's important to update i_size while still holding page lock:
1325 	 * page writeout could otherwise come in and zero beyond i_size.
1326 	 *
1327 	 * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree
1328 	 * blocks are being written past EOF, so skip the i_size update.
1329 	 */
1330 	if (!verity)
1331 		i_size_changed = ext4_update_inode_size(inode, pos + copied);
1332 	unlock_page(page);
1333 	put_page(page);
1334 
1335 	if (old_size < pos && !verity)
1336 		pagecache_isize_extended(inode, old_size, pos);
1337 	/*
1338 	 * Don't mark the inode dirty under page lock. First, it unnecessarily
1339 	 * makes the holding time of page lock longer. Second, it forces lock
1340 	 * ordering of page lock and transaction start for journaling
1341 	 * filesystems.
1342 	 */
1343 	if (i_size_changed)
1344 		ret = ext4_mark_inode_dirty(handle, inode);
1345 
1346 	if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1347 		/* if we have allocated more blocks and copied
1348 		 * less. We will have blocks allocated outside
1349 		 * inode->i_size. So truncate them
1350 		 */
1351 		ext4_orphan_add(handle, inode);
1352 
1353 	ret2 = ext4_journal_stop(handle);
1354 	if (!ret)
1355 		ret = ret2;
1356 
1357 	if (pos + len > inode->i_size && !verity) {
1358 		ext4_truncate_failed_write(inode);
1359 		/*
1360 		 * If truncate failed early the inode might still be
1361 		 * on the orphan list; we need to make sure the inode
1362 		 * is removed from the orphan list in that case.
1363 		 */
1364 		if (inode->i_nlink)
1365 			ext4_orphan_del(NULL, inode);
1366 	}
1367 
1368 	return ret ? ret : copied;
1369 }
1370 
1371 /*
1372  * This is a private version of page_zero_new_buffers() which doesn't
1373  * set the buffer to be dirty, since in data=journalled mode we need
1374  * to call ext4_handle_dirty_metadata() instead.
1375  */
ext4_journalled_zero_new_buffers(handle_t * handle,struct inode * inode,struct page * page,unsigned from,unsigned to)1376 static void ext4_journalled_zero_new_buffers(handle_t *handle,
1377 					    struct inode *inode,
1378 					    struct page *page,
1379 					    unsigned from, unsigned to)
1380 {
1381 	unsigned int block_start = 0, block_end;
1382 	struct buffer_head *head, *bh;
1383 
1384 	bh = head = page_buffers(page);
1385 	do {
1386 		block_end = block_start + bh->b_size;
1387 		if (buffer_new(bh)) {
1388 			if (block_end > from && block_start < to) {
1389 				if (!PageUptodate(page)) {
1390 					unsigned start, size;
1391 
1392 					start = max(from, block_start);
1393 					size = min(to, block_end) - start;
1394 
1395 					zero_user(page, start, size);
1396 					write_end_fn(handle, inode, bh);
1397 				}
1398 				clear_buffer_new(bh);
1399 			}
1400 		}
1401 		block_start = block_end;
1402 		bh = bh->b_this_page;
1403 	} while (bh != head);
1404 }
1405 
ext4_journalled_write_end(struct file * file,struct address_space * mapping,loff_t pos,unsigned len,unsigned copied,struct page * page,void * fsdata)1406 static int ext4_journalled_write_end(struct file *file,
1407 				     struct address_space *mapping,
1408 				     loff_t pos, unsigned len, unsigned copied,
1409 				     struct page *page, void *fsdata)
1410 {
1411 	handle_t *handle = ext4_journal_current_handle();
1412 	struct inode *inode = mapping->host;
1413 	loff_t old_size = inode->i_size;
1414 	int ret = 0, ret2;
1415 	int partial = 0;
1416 	unsigned from, to;
1417 	int size_changed = 0;
1418 	bool verity = ext4_verity_in_progress(inode);
1419 
1420 	trace_ext4_journalled_write_end(inode, pos, len, copied);
1421 	from = pos & (PAGE_SIZE - 1);
1422 	to = from + len;
1423 
1424 	BUG_ON(!ext4_handle_valid(handle));
1425 
1426 	if (ext4_has_inline_data(inode))
1427 		return ext4_write_inline_data_end(inode, pos, len, copied, page);
1428 
1429 	if (unlikely(copied < len) && !PageUptodate(page)) {
1430 		copied = 0;
1431 		ext4_journalled_zero_new_buffers(handle, inode, page, from, to);
1432 	} else {
1433 		if (unlikely(copied < len))
1434 			ext4_journalled_zero_new_buffers(handle, inode, page,
1435 							 from + copied, to);
1436 		ret = ext4_walk_page_buffers(handle, inode, page_buffers(page),
1437 					     from, from + copied, &partial,
1438 					     write_end_fn);
1439 		if (!partial)
1440 			SetPageUptodate(page);
1441 	}
1442 	if (!verity)
1443 		size_changed = ext4_update_inode_size(inode, pos + copied);
1444 	ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1445 	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1446 	unlock_page(page);
1447 	put_page(page);
1448 
1449 	if (old_size < pos && !verity)
1450 		pagecache_isize_extended(inode, old_size, pos);
1451 
1452 	if (size_changed) {
1453 		ret2 = ext4_mark_inode_dirty(handle, inode);
1454 		if (!ret)
1455 			ret = ret2;
1456 	}
1457 
1458 	if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1459 		/* if we have allocated more blocks and copied
1460 		 * less. We will have blocks allocated outside
1461 		 * inode->i_size. So truncate them
1462 		 */
1463 		ext4_orphan_add(handle, inode);
1464 
1465 	ret2 = ext4_journal_stop(handle);
1466 	if (!ret)
1467 		ret = ret2;
1468 	if (pos + len > inode->i_size && !verity) {
1469 		ext4_truncate_failed_write(inode);
1470 		/*
1471 		 * If truncate failed early the inode might still be
1472 		 * on the orphan list; we need to make sure the inode
1473 		 * is removed from the orphan list in that case.
1474 		 */
1475 		if (inode->i_nlink)
1476 			ext4_orphan_del(NULL, inode);
1477 	}
1478 
1479 	return ret ? ret : copied;
1480 }
1481 
1482 /*
1483  * Reserve space for a single cluster
1484  */
ext4_da_reserve_space(struct inode * inode)1485 static int ext4_da_reserve_space(struct inode *inode)
1486 {
1487 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1488 	struct ext4_inode_info *ei = EXT4_I(inode);
1489 	int ret;
1490 
1491 	/*
1492 	 * We will charge metadata quota at writeout time; this saves
1493 	 * us from metadata over-estimation, though we may go over by
1494 	 * a small amount in the end.  Here we just reserve for data.
1495 	 */
1496 	ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1497 	if (ret)
1498 		return ret;
1499 
1500 	spin_lock(&ei->i_block_reservation_lock);
1501 	if (ext4_claim_free_clusters(sbi, 1, 0)) {
1502 		spin_unlock(&ei->i_block_reservation_lock);
1503 		dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1504 		return -ENOSPC;
1505 	}
1506 	ei->i_reserved_data_blocks++;
1507 	trace_ext4_da_reserve_space(inode);
1508 	spin_unlock(&ei->i_block_reservation_lock);
1509 
1510 	return 0;       /* success */
1511 }
1512 
ext4_da_release_space(struct inode * inode,int to_free)1513 void ext4_da_release_space(struct inode *inode, int to_free)
1514 {
1515 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1516 	struct ext4_inode_info *ei = EXT4_I(inode);
1517 
1518 	if (!to_free)
1519 		return;		/* Nothing to release, exit */
1520 
1521 	spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1522 
1523 	trace_ext4_da_release_space(inode, to_free);
1524 	if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1525 		/*
1526 		 * if there aren't enough reserved blocks, then the
1527 		 * counter is messed up somewhere.  Since this
1528 		 * function is called from invalidate page, it's
1529 		 * harmless to return without any action.
1530 		 */
1531 		ext4_warning(inode->i_sb, "ext4_da_release_space: "
1532 			 "ino %lu, to_free %d with only %d reserved "
1533 			 "data blocks", inode->i_ino, to_free,
1534 			 ei->i_reserved_data_blocks);
1535 		WARN_ON(1);
1536 		to_free = ei->i_reserved_data_blocks;
1537 	}
1538 	ei->i_reserved_data_blocks -= to_free;
1539 
1540 	/* update fs dirty data blocks counter */
1541 	percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1542 
1543 	spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1544 
1545 	dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1546 }
1547 
1548 /*
1549  * Delayed allocation stuff
1550  */
1551 
1552 struct mpage_da_data {
1553 	struct inode *inode;
1554 	struct writeback_control *wbc;
1555 
1556 	pgoff_t first_page;	/* The first page to write */
1557 	pgoff_t next_page;	/* Current page to examine */
1558 	pgoff_t last_page;	/* Last page to examine */
1559 	/*
1560 	 * Extent to map - this can be after first_page because that can be
1561 	 * fully mapped. We somewhat abuse m_flags to store whether the extent
1562 	 * is delalloc or unwritten.
1563 	 */
1564 	struct ext4_map_blocks map;
1565 	struct ext4_io_submit io_submit;	/* IO submission data */
1566 	unsigned int do_map:1;
1567 	unsigned int scanned_until_end:1;
1568 };
1569 
mpage_release_unused_pages(struct mpage_da_data * mpd,bool invalidate)1570 static void mpage_release_unused_pages(struct mpage_da_data *mpd,
1571 				       bool invalidate)
1572 {
1573 	unsigned nr, i;
1574 	pgoff_t index, end;
1575 	struct folio_batch fbatch;
1576 	struct inode *inode = mpd->inode;
1577 	struct address_space *mapping = inode->i_mapping;
1578 
1579 	/* This is necessary when next_page == 0. */
1580 	if (mpd->first_page >= mpd->next_page)
1581 		return;
1582 
1583 	mpd->scanned_until_end = 0;
1584 	index = mpd->first_page;
1585 	end   = mpd->next_page - 1;
1586 	if (invalidate) {
1587 		ext4_lblk_t start, last;
1588 		start = index << (PAGE_SHIFT - inode->i_blkbits);
1589 		last = end << (PAGE_SHIFT - inode->i_blkbits);
1590 
1591 		/*
1592 		 * avoid racing with extent status tree scans made by
1593 		 * ext4_insert_delayed_block()
1594 		 */
1595 		down_write(&EXT4_I(inode)->i_data_sem);
1596 		ext4_es_remove_extent(inode, start, last - start + 1);
1597 		up_write(&EXT4_I(inode)->i_data_sem);
1598 	}
1599 
1600 	folio_batch_init(&fbatch);
1601 	while (index <= end) {
1602 		nr = filemap_get_folios(mapping, &index, end, &fbatch);
1603 		if (nr == 0)
1604 			break;
1605 		for (i = 0; i < nr; i++) {
1606 			struct folio *folio = fbatch.folios[i];
1607 
1608 			if (folio->index < mpd->first_page)
1609 				continue;
1610 			if (folio->index + folio_nr_pages(folio) - 1 > end)
1611 				continue;
1612 			BUG_ON(!folio_test_locked(folio));
1613 			BUG_ON(folio_test_writeback(folio));
1614 			if (invalidate) {
1615 				if (folio_mapped(folio))
1616 					folio_clear_dirty_for_io(folio);
1617 				block_invalidate_folio(folio, 0,
1618 						folio_size(folio));
1619 				folio_clear_uptodate(folio);
1620 			}
1621 			folio_unlock(folio);
1622 		}
1623 		folio_batch_release(&fbatch);
1624 	}
1625 }
1626 
ext4_print_free_blocks(struct inode * inode)1627 static void ext4_print_free_blocks(struct inode *inode)
1628 {
1629 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1630 	struct super_block *sb = inode->i_sb;
1631 	struct ext4_inode_info *ei = EXT4_I(inode);
1632 
1633 	ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1634 	       EXT4_C2B(EXT4_SB(inode->i_sb),
1635 			ext4_count_free_clusters(sb)));
1636 	ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1637 	ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1638 	       (long long) EXT4_C2B(EXT4_SB(sb),
1639 		percpu_counter_sum(&sbi->s_freeclusters_counter)));
1640 	ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1641 	       (long long) EXT4_C2B(EXT4_SB(sb),
1642 		percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1643 	ext4_msg(sb, KERN_CRIT, "Block reservation details");
1644 	ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1645 		 ei->i_reserved_data_blocks);
1646 	return;
1647 }
1648 
ext4_bh_delay_or_unwritten(handle_t * handle,struct inode * inode,struct buffer_head * bh)1649 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct inode *inode,
1650 				      struct buffer_head *bh)
1651 {
1652 	return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1653 }
1654 
1655 /*
1656  * ext4_insert_delayed_block - adds a delayed block to the extents status
1657  *                             tree, incrementing the reserved cluster/block
1658  *                             count or making a pending reservation
1659  *                             where needed
1660  *
1661  * @inode - file containing the newly added block
1662  * @lblk - logical block to be added
1663  *
1664  * Returns 0 on success, negative error code on failure.
1665  */
ext4_insert_delayed_block(struct inode * inode,ext4_lblk_t lblk)1666 static int ext4_insert_delayed_block(struct inode *inode, ext4_lblk_t lblk)
1667 {
1668 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1669 	int ret;
1670 	bool allocated = false;
1671 	bool reserved = false;
1672 
1673 	/*
1674 	 * If the cluster containing lblk is shared with a delayed,
1675 	 * written, or unwritten extent in a bigalloc file system, it's
1676 	 * already been accounted for and does not need to be reserved.
1677 	 * A pending reservation must be made for the cluster if it's
1678 	 * shared with a written or unwritten extent and doesn't already
1679 	 * have one.  Written and unwritten extents can be purged from the
1680 	 * extents status tree if the system is under memory pressure, so
1681 	 * it's necessary to examine the extent tree if a search of the
1682 	 * extents status tree doesn't get a match.
1683 	 */
1684 	if (sbi->s_cluster_ratio == 1) {
1685 		ret = ext4_da_reserve_space(inode);
1686 		if (ret != 0)   /* ENOSPC */
1687 			goto errout;
1688 		reserved = true;
1689 	} else {   /* bigalloc */
1690 		if (!ext4_es_scan_clu(inode, &ext4_es_is_delonly, lblk)) {
1691 			if (!ext4_es_scan_clu(inode,
1692 					      &ext4_es_is_mapped, lblk)) {
1693 				ret = ext4_clu_mapped(inode,
1694 						      EXT4_B2C(sbi, lblk));
1695 				if (ret < 0)
1696 					goto errout;
1697 				if (ret == 0) {
1698 					ret = ext4_da_reserve_space(inode);
1699 					if (ret != 0)   /* ENOSPC */
1700 						goto errout;
1701 					reserved = true;
1702 				} else {
1703 					allocated = true;
1704 				}
1705 			} else {
1706 				allocated = true;
1707 			}
1708 		}
1709 	}
1710 
1711 	ret = ext4_es_insert_delayed_block(inode, lblk, allocated);
1712 	if (ret && reserved)
1713 		ext4_da_release_space(inode, 1);
1714 
1715 errout:
1716 	return ret;
1717 }
1718 
1719 /*
1720  * This function is grabs code from the very beginning of
1721  * ext4_map_blocks, but assumes that the caller is from delayed write
1722  * time. This function looks up the requested blocks and sets the
1723  * buffer delay bit under the protection of i_data_sem.
1724  */
ext4_da_map_blocks(struct inode * inode,sector_t iblock,struct ext4_map_blocks * map,struct buffer_head * bh)1725 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1726 			      struct ext4_map_blocks *map,
1727 			      struct buffer_head *bh)
1728 {
1729 	struct extent_status es;
1730 	int retval;
1731 	sector_t invalid_block = ~((sector_t) 0xffff);
1732 #ifdef ES_AGGRESSIVE_TEST
1733 	struct ext4_map_blocks orig_map;
1734 
1735 	memcpy(&orig_map, map, sizeof(*map));
1736 #endif
1737 
1738 	if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1739 		invalid_block = ~0;
1740 
1741 	map->m_flags = 0;
1742 	ext_debug(inode, "max_blocks %u, logical block %lu\n", map->m_len,
1743 		  (unsigned long) map->m_lblk);
1744 
1745 	/* Lookup extent status tree firstly */
1746 	if (ext4_es_lookup_extent(inode, iblock, NULL, &es)) {
1747 		if (ext4_es_is_hole(&es)) {
1748 			retval = 0;
1749 			down_read(&EXT4_I(inode)->i_data_sem);
1750 			goto add_delayed;
1751 		}
1752 
1753 		/*
1754 		 * Delayed extent could be allocated by fallocate.
1755 		 * So we need to check it.
1756 		 */
1757 		if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1758 			map_bh(bh, inode->i_sb, invalid_block);
1759 			set_buffer_new(bh);
1760 			set_buffer_delay(bh);
1761 			return 0;
1762 		}
1763 
1764 		map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1765 		retval = es.es_len - (iblock - es.es_lblk);
1766 		if (retval > map->m_len)
1767 			retval = map->m_len;
1768 		map->m_len = retval;
1769 		if (ext4_es_is_written(&es))
1770 			map->m_flags |= EXT4_MAP_MAPPED;
1771 		else if (ext4_es_is_unwritten(&es))
1772 			map->m_flags |= EXT4_MAP_UNWRITTEN;
1773 		else
1774 			BUG();
1775 
1776 #ifdef ES_AGGRESSIVE_TEST
1777 		ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1778 #endif
1779 		return retval;
1780 	}
1781 
1782 	/*
1783 	 * Try to see if we can get the block without requesting a new
1784 	 * file system block.
1785 	 */
1786 	down_read(&EXT4_I(inode)->i_data_sem);
1787 	if (ext4_has_inline_data(inode))
1788 		retval = 0;
1789 	else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1790 		retval = ext4_ext_map_blocks(NULL, inode, map, 0);
1791 	else
1792 		retval = ext4_ind_map_blocks(NULL, inode, map, 0);
1793 
1794 add_delayed:
1795 	if (retval == 0) {
1796 		int ret;
1797 
1798 		/*
1799 		 * XXX: __block_prepare_write() unmaps passed block,
1800 		 * is it OK?
1801 		 */
1802 
1803 		ret = ext4_insert_delayed_block(inode, map->m_lblk);
1804 		if (ret != 0) {
1805 			retval = ret;
1806 			goto out_unlock;
1807 		}
1808 
1809 		map_bh(bh, inode->i_sb, invalid_block);
1810 		set_buffer_new(bh);
1811 		set_buffer_delay(bh);
1812 	} else if (retval > 0) {
1813 		int ret;
1814 		unsigned int status;
1815 
1816 		if (unlikely(retval != map->m_len)) {
1817 			ext4_warning(inode->i_sb,
1818 				     "ES len assertion failed for inode "
1819 				     "%lu: retval %d != map->m_len %d",
1820 				     inode->i_ino, retval, map->m_len);
1821 			WARN_ON(1);
1822 		}
1823 
1824 		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1825 				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1826 		ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1827 					    map->m_pblk, status);
1828 		if (ret != 0)
1829 			retval = ret;
1830 	}
1831 
1832 out_unlock:
1833 	up_read((&EXT4_I(inode)->i_data_sem));
1834 
1835 	return retval;
1836 }
1837 
1838 /*
1839  * This is a special get_block_t callback which is used by
1840  * ext4_da_write_begin().  It will either return mapped block or
1841  * reserve space for a single block.
1842  *
1843  * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1844  * We also have b_blocknr = -1 and b_bdev initialized properly
1845  *
1846  * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1847  * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1848  * initialized properly.
1849  */
ext4_da_get_block_prep(struct inode * inode,sector_t iblock,struct buffer_head * bh,int create)1850 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1851 			   struct buffer_head *bh, int create)
1852 {
1853 	struct ext4_map_blocks map;
1854 	int ret = 0;
1855 
1856 	BUG_ON(create == 0);
1857 	BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1858 
1859 	map.m_lblk = iblock;
1860 	map.m_len = 1;
1861 
1862 	/*
1863 	 * first, we need to know whether the block is allocated already
1864 	 * preallocated blocks are unmapped but should treated
1865 	 * the same as allocated blocks.
1866 	 */
1867 	ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1868 	if (ret <= 0)
1869 		return ret;
1870 
1871 	map_bh(bh, inode->i_sb, map.m_pblk);
1872 	ext4_update_bh_state(bh, map.m_flags);
1873 
1874 	if (buffer_unwritten(bh)) {
1875 		/* A delayed write to unwritten bh should be marked
1876 		 * new and mapped.  Mapped ensures that we don't do
1877 		 * get_block multiple times when we write to the same
1878 		 * offset and new ensures that we do proper zero out
1879 		 * for partial write.
1880 		 */
1881 		set_buffer_new(bh);
1882 		set_buffer_mapped(bh);
1883 	}
1884 	return 0;
1885 }
1886 
__ext4_journalled_writepage(struct page * page,unsigned int len)1887 static int __ext4_journalled_writepage(struct page *page,
1888 				       unsigned int len)
1889 {
1890 	struct address_space *mapping = page->mapping;
1891 	struct inode *inode = mapping->host;
1892 	handle_t *handle = NULL;
1893 	int ret = 0, err = 0;
1894 	int inline_data = ext4_has_inline_data(inode);
1895 	struct buffer_head *inode_bh = NULL;
1896 	loff_t size;
1897 
1898 	ClearPageChecked(page);
1899 
1900 	if (inline_data) {
1901 		BUG_ON(page->index != 0);
1902 		BUG_ON(len > ext4_get_max_inline_size(inode));
1903 		inode_bh = ext4_journalled_write_inline_data(inode, len, page);
1904 		if (inode_bh == NULL)
1905 			goto out;
1906 	}
1907 	/*
1908 	 * We need to release the page lock before we start the
1909 	 * journal, so grab a reference so the page won't disappear
1910 	 * out from under us.
1911 	 */
1912 	get_page(page);
1913 	unlock_page(page);
1914 
1915 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
1916 				    ext4_writepage_trans_blocks(inode));
1917 	if (IS_ERR(handle)) {
1918 		ret = PTR_ERR(handle);
1919 		put_page(page);
1920 		goto out_no_pagelock;
1921 	}
1922 	BUG_ON(!ext4_handle_valid(handle));
1923 
1924 	lock_page(page);
1925 	put_page(page);
1926 	size = i_size_read(inode);
1927 	if (page->mapping != mapping || page_offset(page) > size) {
1928 		/* The page got truncated from under us */
1929 		ext4_journal_stop(handle);
1930 		ret = 0;
1931 		goto out;
1932 	}
1933 
1934 	if (inline_data) {
1935 		ret = ext4_mark_inode_dirty(handle, inode);
1936 	} else {
1937 		struct buffer_head *page_bufs = page_buffers(page);
1938 
1939 		if (page->index == size >> PAGE_SHIFT)
1940 			len = size & ~PAGE_MASK;
1941 		else
1942 			len = PAGE_SIZE;
1943 
1944 		ret = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
1945 					     NULL, do_journal_get_write_access);
1946 
1947 		err = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
1948 					     NULL, write_end_fn);
1949 	}
1950 	if (ret == 0)
1951 		ret = err;
1952 	err = ext4_jbd2_inode_add_write(handle, inode, page_offset(page), len);
1953 	if (ret == 0)
1954 		ret = err;
1955 	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1956 	err = ext4_journal_stop(handle);
1957 	if (!ret)
1958 		ret = err;
1959 
1960 	ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1961 out:
1962 	unlock_page(page);
1963 out_no_pagelock:
1964 	brelse(inode_bh);
1965 	return ret;
1966 }
1967 
1968 /*
1969  * Note that we don't need to start a transaction unless we're journaling data
1970  * because we should have holes filled from ext4_page_mkwrite(). We even don't
1971  * need to file the inode to the transaction's list in ordered mode because if
1972  * we are writing back data added by write(), the inode is already there and if
1973  * we are writing back data modified via mmap(), no one guarantees in which
1974  * transaction the data will hit the disk. In case we are journaling data, we
1975  * cannot start transaction directly because transaction start ranks above page
1976  * lock so we have to do some magic.
1977  *
1978  * This function can get called via...
1979  *   - ext4_writepages after taking page lock (have journal handle)
1980  *   - journal_submit_inode_data_buffers (no journal handle)
1981  *   - shrink_page_list via the kswapd/direct reclaim (no journal handle)
1982  *   - grab_page_cache when doing write_begin (have journal handle)
1983  *
1984  * We don't do any block allocation in this function. If we have page with
1985  * multiple blocks we need to write those buffer_heads that are mapped. This
1986  * is important for mmaped based write. So if we do with blocksize 1K
1987  * truncate(f, 1024);
1988  * a = mmap(f, 0, 4096);
1989  * a[0] = 'a';
1990  * truncate(f, 4096);
1991  * we have in the page first buffer_head mapped via page_mkwrite call back
1992  * but other buffer_heads would be unmapped but dirty (dirty done via the
1993  * do_wp_page). So writepage should write the first block. If we modify
1994  * the mmap area beyond 1024 we will again get a page_fault and the
1995  * page_mkwrite callback will do the block allocation and mark the
1996  * buffer_heads mapped.
1997  *
1998  * We redirty the page if we have any buffer_heads that is either delay or
1999  * unwritten in the page.
2000  *
2001  * We can get recursively called as show below.
2002  *
2003  *	ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
2004  *		ext4_writepage()
2005  *
2006  * But since we don't do any block allocation we should not deadlock.
2007  * Page also have the dirty flag cleared so we don't get recurive page_lock.
2008  */
ext4_writepage(struct page * page,struct writeback_control * wbc)2009 static int ext4_writepage(struct page *page,
2010 			  struct writeback_control *wbc)
2011 {
2012 	struct folio *folio = page_folio(page);
2013 	int ret = 0;
2014 	loff_t size;
2015 	unsigned int len;
2016 	struct buffer_head *page_bufs = NULL;
2017 	struct inode *inode = page->mapping->host;
2018 	struct ext4_io_submit io_submit;
2019 	bool keep_towrite = false;
2020 
2021 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
2022 		folio_invalidate(folio, 0, folio_size(folio));
2023 		folio_unlock(folio);
2024 		return -EIO;
2025 	}
2026 
2027 	trace_ext4_writepage(page);
2028 	size = i_size_read(inode);
2029 	if (page->index == size >> PAGE_SHIFT &&
2030 	    !ext4_verity_in_progress(inode))
2031 		len = size & ~PAGE_MASK;
2032 	else
2033 		len = PAGE_SIZE;
2034 
2035 	/* Should never happen but for bugs in other kernel subsystems */
2036 	if (!page_has_buffers(page)) {
2037 		ext4_warning_inode(inode,
2038 		   "page %lu does not have buffers attached", page->index);
2039 		ClearPageDirty(page);
2040 		unlock_page(page);
2041 		return 0;
2042 	}
2043 
2044 	page_bufs = page_buffers(page);
2045 	/*
2046 	 * We cannot do block allocation or other extent handling in this
2047 	 * function. If there are buffers needing that, we have to redirty
2048 	 * the page. But we may reach here when we do a journal commit via
2049 	 * journal_submit_inode_data_buffers() and in that case we must write
2050 	 * allocated buffers to achieve data=ordered mode guarantees.
2051 	 *
2052 	 * Also, if there is only one buffer per page (the fs block
2053 	 * size == the page size), if one buffer needs block
2054 	 * allocation or needs to modify the extent tree to clear the
2055 	 * unwritten flag, we know that the page can't be written at
2056 	 * all, so we might as well refuse the write immediately.
2057 	 * Unfortunately if the block size != page size, we can't as
2058 	 * easily detect this case using ext4_walk_page_buffers(), but
2059 	 * for the extremely common case, this is an optimization that
2060 	 * skips a useless round trip through ext4_bio_write_page().
2061 	 */
2062 	if (ext4_walk_page_buffers(NULL, inode, page_bufs, 0, len, NULL,
2063 				   ext4_bh_delay_or_unwritten)) {
2064 		redirty_page_for_writepage(wbc, page);
2065 		if ((current->flags & PF_MEMALLOC) ||
2066 		    (inode->i_sb->s_blocksize == PAGE_SIZE)) {
2067 			/*
2068 			 * For memory cleaning there's no point in writing only
2069 			 * some buffers. So just bail out. Warn if we came here
2070 			 * from direct reclaim.
2071 			 */
2072 			WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
2073 							== PF_MEMALLOC);
2074 			unlock_page(page);
2075 			return 0;
2076 		}
2077 		keep_towrite = true;
2078 	}
2079 
2080 	if (PageChecked(page) && ext4_should_journal_data(inode))
2081 		/*
2082 		 * It's mmapped pagecache.  Add buffers and journal it.  There
2083 		 * doesn't seem much point in redirtying the page here.
2084 		 */
2085 		return __ext4_journalled_writepage(page, len);
2086 
2087 	ext4_io_submit_init(&io_submit, wbc);
2088 	io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
2089 	if (!io_submit.io_end) {
2090 		redirty_page_for_writepage(wbc, page);
2091 		unlock_page(page);
2092 		return -ENOMEM;
2093 	}
2094 	ret = ext4_bio_write_page(&io_submit, page, len, keep_towrite);
2095 	ext4_io_submit(&io_submit);
2096 	/* Drop io_end reference we got from init */
2097 	ext4_put_io_end_defer(io_submit.io_end);
2098 	return ret;
2099 }
2100 
mpage_submit_page(struct mpage_da_data * mpd,struct page * page)2101 static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
2102 {
2103 	int len;
2104 	loff_t size;
2105 	int err;
2106 
2107 	BUG_ON(page->index != mpd->first_page);
2108 	clear_page_dirty_for_io(page);
2109 	/*
2110 	 * We have to be very careful here!  Nothing protects writeback path
2111 	 * against i_size changes and the page can be writeably mapped into
2112 	 * page tables. So an application can be growing i_size and writing
2113 	 * data through mmap while writeback runs. clear_page_dirty_for_io()
2114 	 * write-protects our page in page tables and the page cannot get
2115 	 * written to again until we release page lock. So only after
2116 	 * clear_page_dirty_for_io() we are safe to sample i_size for
2117 	 * ext4_bio_write_page() to zero-out tail of the written page. We rely
2118 	 * on the barrier provided by TestClearPageDirty in
2119 	 * clear_page_dirty_for_io() to make sure i_size is really sampled only
2120 	 * after page tables are updated.
2121 	 */
2122 	size = i_size_read(mpd->inode);
2123 	if (page->index == size >> PAGE_SHIFT &&
2124 	    !ext4_verity_in_progress(mpd->inode))
2125 		len = size & ~PAGE_MASK;
2126 	else
2127 		len = PAGE_SIZE;
2128 	err = ext4_bio_write_page(&mpd->io_submit, page, len, false);
2129 	if (!err)
2130 		mpd->wbc->nr_to_write--;
2131 	mpd->first_page++;
2132 
2133 	return err;
2134 }
2135 
2136 #define BH_FLAGS (BIT(BH_Unwritten) | BIT(BH_Delay))
2137 
2138 /*
2139  * mballoc gives us at most this number of blocks...
2140  * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
2141  * The rest of mballoc seems to handle chunks up to full group size.
2142  */
2143 #define MAX_WRITEPAGES_EXTENT_LEN 2048
2144 
2145 /*
2146  * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
2147  *
2148  * @mpd - extent of blocks
2149  * @lblk - logical number of the block in the file
2150  * @bh - buffer head we want to add to the extent
2151  *
2152  * The function is used to collect contig. blocks in the same state. If the
2153  * buffer doesn't require mapping for writeback and we haven't started the
2154  * extent of buffers to map yet, the function returns 'true' immediately - the
2155  * caller can write the buffer right away. Otherwise the function returns true
2156  * if the block has been added to the extent, false if the block couldn't be
2157  * added.
2158  */
mpage_add_bh_to_extent(struct mpage_da_data * mpd,ext4_lblk_t lblk,struct buffer_head * bh)2159 static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
2160 				   struct buffer_head *bh)
2161 {
2162 	struct ext4_map_blocks *map = &mpd->map;
2163 
2164 	/* Buffer that doesn't need mapping for writeback? */
2165 	if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
2166 	    (!buffer_delay(bh) && !buffer_unwritten(bh))) {
2167 		/* So far no extent to map => we write the buffer right away */
2168 		if (map->m_len == 0)
2169 			return true;
2170 		return false;
2171 	}
2172 
2173 	/* First block in the extent? */
2174 	if (map->m_len == 0) {
2175 		/* We cannot map unless handle is started... */
2176 		if (!mpd->do_map)
2177 			return false;
2178 		map->m_lblk = lblk;
2179 		map->m_len = 1;
2180 		map->m_flags = bh->b_state & BH_FLAGS;
2181 		return true;
2182 	}
2183 
2184 	/* Don't go larger than mballoc is willing to allocate */
2185 	if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
2186 		return false;
2187 
2188 	/* Can we merge the block to our big extent? */
2189 	if (lblk == map->m_lblk + map->m_len &&
2190 	    (bh->b_state & BH_FLAGS) == map->m_flags) {
2191 		map->m_len++;
2192 		return true;
2193 	}
2194 	return false;
2195 }
2196 
2197 /*
2198  * mpage_process_page_bufs - submit page buffers for IO or add them to extent
2199  *
2200  * @mpd - extent of blocks for mapping
2201  * @head - the first buffer in the page
2202  * @bh - buffer we should start processing from
2203  * @lblk - logical number of the block in the file corresponding to @bh
2204  *
2205  * Walk through page buffers from @bh upto @head (exclusive) and either submit
2206  * the page for IO if all buffers in this page were mapped and there's no
2207  * accumulated extent of buffers to map or add buffers in the page to the
2208  * extent of buffers to map. The function returns 1 if the caller can continue
2209  * by processing the next page, 0 if it should stop adding buffers to the
2210  * extent to map because we cannot extend it anymore. It can also return value
2211  * < 0 in case of error during IO submission.
2212  */
mpage_process_page_bufs(struct mpage_da_data * mpd,struct buffer_head * head,struct buffer_head * bh,ext4_lblk_t lblk)2213 static int mpage_process_page_bufs(struct mpage_da_data *mpd,
2214 				   struct buffer_head *head,
2215 				   struct buffer_head *bh,
2216 				   ext4_lblk_t lblk)
2217 {
2218 	struct inode *inode = mpd->inode;
2219 	int err;
2220 	ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
2221 							>> inode->i_blkbits;
2222 
2223 	if (ext4_verity_in_progress(inode))
2224 		blocks = EXT_MAX_BLOCKS;
2225 
2226 	do {
2227 		BUG_ON(buffer_locked(bh));
2228 
2229 		if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
2230 			/* Found extent to map? */
2231 			if (mpd->map.m_len)
2232 				return 0;
2233 			/* Buffer needs mapping and handle is not started? */
2234 			if (!mpd->do_map)
2235 				return 0;
2236 			/* Everything mapped so far and we hit EOF */
2237 			break;
2238 		}
2239 	} while (lblk++, (bh = bh->b_this_page) != head);
2240 	/* So far everything mapped? Submit the page for IO. */
2241 	if (mpd->map.m_len == 0) {
2242 		err = mpage_submit_page(mpd, head->b_page);
2243 		if (err < 0)
2244 			return err;
2245 	}
2246 	if (lblk >= blocks) {
2247 		mpd->scanned_until_end = 1;
2248 		return 0;
2249 	}
2250 	return 1;
2251 }
2252 
2253 /*
2254  * mpage_process_page - update page buffers corresponding to changed extent and
2255  *		       may submit fully mapped page for IO
2256  *
2257  * @mpd		- description of extent to map, on return next extent to map
2258  * @m_lblk	- logical block mapping.
2259  * @m_pblk	- corresponding physical mapping.
2260  * @map_bh	- determines on return whether this page requires any further
2261  *		  mapping or not.
2262  * Scan given page buffers corresponding to changed extent and update buffer
2263  * state according to new extent state.
2264  * We map delalloc buffers to their physical location, clear unwritten bits.
2265  * If the given page is not fully mapped, we update @map to the next extent in
2266  * the given page that needs mapping & return @map_bh as true.
2267  */
mpage_process_page(struct mpage_da_data * mpd,struct page * page,ext4_lblk_t * m_lblk,ext4_fsblk_t * m_pblk,bool * map_bh)2268 static int mpage_process_page(struct mpage_da_data *mpd, struct page *page,
2269 			      ext4_lblk_t *m_lblk, ext4_fsblk_t *m_pblk,
2270 			      bool *map_bh)
2271 {
2272 	struct buffer_head *head, *bh;
2273 	ext4_io_end_t *io_end = mpd->io_submit.io_end;
2274 	ext4_lblk_t lblk = *m_lblk;
2275 	ext4_fsblk_t pblock = *m_pblk;
2276 	int err = 0;
2277 	int blkbits = mpd->inode->i_blkbits;
2278 	ssize_t io_end_size = 0;
2279 	struct ext4_io_end_vec *io_end_vec = ext4_last_io_end_vec(io_end);
2280 
2281 	bh = head = page_buffers(page);
2282 	do {
2283 		if (lblk < mpd->map.m_lblk)
2284 			continue;
2285 		if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2286 			/*
2287 			 * Buffer after end of mapped extent.
2288 			 * Find next buffer in the page to map.
2289 			 */
2290 			mpd->map.m_len = 0;
2291 			mpd->map.m_flags = 0;
2292 			io_end_vec->size += io_end_size;
2293 
2294 			err = mpage_process_page_bufs(mpd, head, bh, lblk);
2295 			if (err > 0)
2296 				err = 0;
2297 			if (!err && mpd->map.m_len && mpd->map.m_lblk > lblk) {
2298 				io_end_vec = ext4_alloc_io_end_vec(io_end);
2299 				if (IS_ERR(io_end_vec)) {
2300 					err = PTR_ERR(io_end_vec);
2301 					goto out;
2302 				}
2303 				io_end_vec->offset = (loff_t)mpd->map.m_lblk << blkbits;
2304 			}
2305 			*map_bh = true;
2306 			goto out;
2307 		}
2308 		if (buffer_delay(bh)) {
2309 			clear_buffer_delay(bh);
2310 			bh->b_blocknr = pblock++;
2311 		}
2312 		clear_buffer_unwritten(bh);
2313 		io_end_size += (1 << blkbits);
2314 	} while (lblk++, (bh = bh->b_this_page) != head);
2315 
2316 	io_end_vec->size += io_end_size;
2317 	*map_bh = false;
2318 out:
2319 	*m_lblk = lblk;
2320 	*m_pblk = pblock;
2321 	return err;
2322 }
2323 
2324 /*
2325  * mpage_map_buffers - update buffers corresponding to changed extent and
2326  *		       submit fully mapped pages for IO
2327  *
2328  * @mpd - description of extent to map, on return next extent to map
2329  *
2330  * Scan buffers corresponding to changed extent (we expect corresponding pages
2331  * to be already locked) and update buffer state according to new extent state.
2332  * We map delalloc buffers to their physical location, clear unwritten bits,
2333  * and mark buffers as uninit when we perform writes to unwritten extents
2334  * and do extent conversion after IO is finished. If the last page is not fully
2335  * mapped, we update @map to the next extent in the last page that needs
2336  * mapping. Otherwise we submit the page for IO.
2337  */
mpage_map_and_submit_buffers(struct mpage_da_data * mpd)2338 static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
2339 {
2340 	struct folio_batch fbatch;
2341 	unsigned nr, i;
2342 	struct inode *inode = mpd->inode;
2343 	int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
2344 	pgoff_t start, end;
2345 	ext4_lblk_t lblk;
2346 	ext4_fsblk_t pblock;
2347 	int err;
2348 	bool map_bh = false;
2349 
2350 	start = mpd->map.m_lblk >> bpp_bits;
2351 	end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
2352 	lblk = start << bpp_bits;
2353 	pblock = mpd->map.m_pblk;
2354 
2355 	folio_batch_init(&fbatch);
2356 	while (start <= end) {
2357 		nr = filemap_get_folios(inode->i_mapping, &start, end, &fbatch);
2358 		if (nr == 0)
2359 			break;
2360 		for (i = 0; i < nr; i++) {
2361 			struct page *page = &fbatch.folios[i]->page;
2362 
2363 			err = mpage_process_page(mpd, page, &lblk, &pblock,
2364 						 &map_bh);
2365 			/*
2366 			 * If map_bh is true, means page may require further bh
2367 			 * mapping, or maybe the page was submitted for IO.
2368 			 * So we return to call further extent mapping.
2369 			 */
2370 			if (err < 0 || map_bh)
2371 				goto out;
2372 			/* Page fully mapped - let IO run! */
2373 			err = mpage_submit_page(mpd, page);
2374 			if (err < 0)
2375 				goto out;
2376 		}
2377 		folio_batch_release(&fbatch);
2378 	}
2379 	/* Extent fully mapped and matches with page boundary. We are done. */
2380 	mpd->map.m_len = 0;
2381 	mpd->map.m_flags = 0;
2382 	return 0;
2383 out:
2384 	folio_batch_release(&fbatch);
2385 	return err;
2386 }
2387 
mpage_map_one_extent(handle_t * handle,struct mpage_da_data * mpd)2388 static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2389 {
2390 	struct inode *inode = mpd->inode;
2391 	struct ext4_map_blocks *map = &mpd->map;
2392 	int get_blocks_flags;
2393 	int err, dioread_nolock;
2394 
2395 	trace_ext4_da_write_pages_extent(inode, map);
2396 	/*
2397 	 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2398 	 * to convert an unwritten extent to be initialized (in the case
2399 	 * where we have written into one or more preallocated blocks).  It is
2400 	 * possible that we're going to need more metadata blocks than
2401 	 * previously reserved. However we must not fail because we're in
2402 	 * writeback and there is nothing we can do about it so it might result
2403 	 * in data loss.  So use reserved blocks to allocate metadata if
2404 	 * possible.
2405 	 *
2406 	 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2407 	 * the blocks in question are delalloc blocks.  This indicates
2408 	 * that the blocks and quotas has already been checked when
2409 	 * the data was copied into the page cache.
2410 	 */
2411 	get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2412 			   EXT4_GET_BLOCKS_METADATA_NOFAIL |
2413 			   EXT4_GET_BLOCKS_IO_SUBMIT;
2414 	dioread_nolock = ext4_should_dioread_nolock(inode);
2415 	if (dioread_nolock)
2416 		get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2417 	if (map->m_flags & BIT(BH_Delay))
2418 		get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2419 
2420 	err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2421 	if (err < 0)
2422 		return err;
2423 	if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
2424 		if (!mpd->io_submit.io_end->handle &&
2425 		    ext4_handle_valid(handle)) {
2426 			mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2427 			handle->h_rsv_handle = NULL;
2428 		}
2429 		ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
2430 	}
2431 
2432 	BUG_ON(map->m_len == 0);
2433 	return 0;
2434 }
2435 
2436 /*
2437  * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2438  *				 mpd->len and submit pages underlying it for IO
2439  *
2440  * @handle - handle for journal operations
2441  * @mpd - extent to map
2442  * @give_up_on_write - we set this to true iff there is a fatal error and there
2443  *                     is no hope of writing the data. The caller should discard
2444  *                     dirty pages to avoid infinite loops.
2445  *
2446  * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2447  * delayed, blocks are allocated, if it is unwritten, we may need to convert
2448  * them to initialized or split the described range from larger unwritten
2449  * extent. Note that we need not map all the described range since allocation
2450  * can return less blocks or the range is covered by more unwritten extents. We
2451  * cannot map more because we are limited by reserved transaction credits. On
2452  * the other hand we always make sure that the last touched page is fully
2453  * mapped so that it can be written out (and thus forward progress is
2454  * guaranteed). After mapping we submit all mapped pages for IO.
2455  */
mpage_map_and_submit_extent(handle_t * handle,struct mpage_da_data * mpd,bool * give_up_on_write)2456 static int mpage_map_and_submit_extent(handle_t *handle,
2457 				       struct mpage_da_data *mpd,
2458 				       bool *give_up_on_write)
2459 {
2460 	struct inode *inode = mpd->inode;
2461 	struct ext4_map_blocks *map = &mpd->map;
2462 	int err;
2463 	loff_t disksize;
2464 	int progress = 0;
2465 	ext4_io_end_t *io_end = mpd->io_submit.io_end;
2466 	struct ext4_io_end_vec *io_end_vec;
2467 
2468 	io_end_vec = ext4_alloc_io_end_vec(io_end);
2469 	if (IS_ERR(io_end_vec))
2470 		return PTR_ERR(io_end_vec);
2471 	io_end_vec->offset = ((loff_t)map->m_lblk) << inode->i_blkbits;
2472 	do {
2473 		err = mpage_map_one_extent(handle, mpd);
2474 		if (err < 0) {
2475 			struct super_block *sb = inode->i_sb;
2476 
2477 			if (ext4_forced_shutdown(EXT4_SB(sb)) ||
2478 			    ext4_test_mount_flag(sb, EXT4_MF_FS_ABORTED))
2479 				goto invalidate_dirty_pages;
2480 			/*
2481 			 * Let the uper layers retry transient errors.
2482 			 * In the case of ENOSPC, if ext4_count_free_blocks()
2483 			 * is non-zero, a commit should free up blocks.
2484 			 */
2485 			if ((err == -ENOMEM) ||
2486 			    (err == -ENOSPC && ext4_count_free_clusters(sb))) {
2487 				if (progress)
2488 					goto update_disksize;
2489 				return err;
2490 			}
2491 			ext4_msg(sb, KERN_CRIT,
2492 				 "Delayed block allocation failed for "
2493 				 "inode %lu at logical offset %llu with"
2494 				 " max blocks %u with error %d",
2495 				 inode->i_ino,
2496 				 (unsigned long long)map->m_lblk,
2497 				 (unsigned)map->m_len, -err);
2498 			ext4_msg(sb, KERN_CRIT,
2499 				 "This should not happen!! Data will "
2500 				 "be lost\n");
2501 			if (err == -ENOSPC)
2502 				ext4_print_free_blocks(inode);
2503 		invalidate_dirty_pages:
2504 			*give_up_on_write = true;
2505 			return err;
2506 		}
2507 		progress = 1;
2508 		/*
2509 		 * Update buffer state, submit mapped pages, and get us new
2510 		 * extent to map
2511 		 */
2512 		err = mpage_map_and_submit_buffers(mpd);
2513 		if (err < 0)
2514 			goto update_disksize;
2515 	} while (map->m_len);
2516 
2517 update_disksize:
2518 	/*
2519 	 * Update on-disk size after IO is submitted.  Races with
2520 	 * truncate are avoided by checking i_size under i_data_sem.
2521 	 */
2522 	disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
2523 	if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
2524 		int err2;
2525 		loff_t i_size;
2526 
2527 		down_write(&EXT4_I(inode)->i_data_sem);
2528 		i_size = i_size_read(inode);
2529 		if (disksize > i_size)
2530 			disksize = i_size;
2531 		if (disksize > EXT4_I(inode)->i_disksize)
2532 			EXT4_I(inode)->i_disksize = disksize;
2533 		up_write(&EXT4_I(inode)->i_data_sem);
2534 		err2 = ext4_mark_inode_dirty(handle, inode);
2535 		if (err2) {
2536 			ext4_error_err(inode->i_sb, -err2,
2537 				       "Failed to mark inode %lu dirty",
2538 				       inode->i_ino);
2539 		}
2540 		if (!err)
2541 			err = err2;
2542 	}
2543 	return err;
2544 }
2545 
2546 /*
2547  * Calculate the total number of credits to reserve for one writepages
2548  * iteration. This is called from ext4_writepages(). We map an extent of
2549  * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2550  * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2551  * bpp - 1 blocks in bpp different extents.
2552  */
ext4_da_writepages_trans_blocks(struct inode * inode)2553 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2554 {
2555 	int bpp = ext4_journal_blocks_per_page(inode);
2556 
2557 	return ext4_meta_trans_blocks(inode,
2558 				MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2559 }
2560 
2561 /*
2562  * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2563  * 				 and underlying extent to map
2564  *
2565  * @mpd - where to look for pages
2566  *
2567  * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2568  * IO immediately. When we find a page which isn't mapped we start accumulating
2569  * extent of buffers underlying these pages that needs mapping (formed by
2570  * either delayed or unwritten buffers). We also lock the pages containing
2571  * these buffers. The extent found is returned in @mpd structure (starting at
2572  * mpd->lblk with length mpd->len blocks).
2573  *
2574  * Note that this function can attach bios to one io_end structure which are
2575  * neither logically nor physically contiguous. Although it may seem as an
2576  * unnecessary complication, it is actually inevitable in blocksize < pagesize
2577  * case as we need to track IO to all buffers underlying a page in one io_end.
2578  */
mpage_prepare_extent_to_map(struct mpage_da_data * mpd)2579 static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
2580 {
2581 	struct address_space *mapping = mpd->inode->i_mapping;
2582 	struct pagevec pvec;
2583 	unsigned int nr_pages;
2584 	long left = mpd->wbc->nr_to_write;
2585 	pgoff_t index = mpd->first_page;
2586 	pgoff_t end = mpd->last_page;
2587 	xa_mark_t tag;
2588 	int i, err = 0;
2589 	int blkbits = mpd->inode->i_blkbits;
2590 	ext4_lblk_t lblk;
2591 	struct buffer_head *head;
2592 
2593 	if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
2594 		tag = PAGECACHE_TAG_TOWRITE;
2595 	else
2596 		tag = PAGECACHE_TAG_DIRTY;
2597 
2598 	pagevec_init(&pvec);
2599 	mpd->map.m_len = 0;
2600 	mpd->next_page = index;
2601 	while (index <= end) {
2602 		nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
2603 				tag);
2604 		if (nr_pages == 0)
2605 			break;
2606 
2607 		for (i = 0; i < nr_pages; i++) {
2608 			struct page *page = pvec.pages[i];
2609 
2610 			/*
2611 			 * Accumulated enough dirty pages? This doesn't apply
2612 			 * to WB_SYNC_ALL mode. For integrity sync we have to
2613 			 * keep going because someone may be concurrently
2614 			 * dirtying pages, and we might have synced a lot of
2615 			 * newly appeared dirty pages, but have not synced all
2616 			 * of the old dirty pages.
2617 			 */
2618 			if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2619 				goto out;
2620 
2621 			/* If we can't merge this page, we are done. */
2622 			if (mpd->map.m_len > 0 && mpd->next_page != page->index)
2623 				goto out;
2624 
2625 			lock_page(page);
2626 			/*
2627 			 * If the page is no longer dirty, or its mapping no
2628 			 * longer corresponds to inode we are writing (which
2629 			 * means it has been truncated or invalidated), or the
2630 			 * page is already under writeback and we are not doing
2631 			 * a data integrity writeback, skip the page
2632 			 */
2633 			if (!PageDirty(page) ||
2634 			    (PageWriteback(page) &&
2635 			     (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
2636 			    unlikely(page->mapping != mapping)) {
2637 				unlock_page(page);
2638 				continue;
2639 			}
2640 
2641 			wait_on_page_writeback(page);
2642 			BUG_ON(PageWriteback(page));
2643 
2644 			/*
2645 			 * Should never happen but for buggy code in
2646 			 * other subsystems that call
2647 			 * set_page_dirty() without properly warning
2648 			 * the file system first.  See [1] for more
2649 			 * information.
2650 			 *
2651 			 * [1] https://lore.kernel.org/linux-mm/20180103100430.GE4911@quack2.suse.cz
2652 			 */
2653 			if (!page_has_buffers(page)) {
2654 				ext4_warning_inode(mpd->inode, "page %lu does not have buffers attached", page->index);
2655 				ClearPageDirty(page);
2656 				unlock_page(page);
2657 				continue;
2658 			}
2659 
2660 			if (mpd->map.m_len == 0)
2661 				mpd->first_page = page->index;
2662 			mpd->next_page = page->index + 1;
2663 			/* Add all dirty buffers to mpd */
2664 			lblk = ((ext4_lblk_t)page->index) <<
2665 				(PAGE_SHIFT - blkbits);
2666 			head = page_buffers(page);
2667 			err = mpage_process_page_bufs(mpd, head, head, lblk);
2668 			if (err <= 0)
2669 				goto out;
2670 			err = 0;
2671 			left--;
2672 		}
2673 		pagevec_release(&pvec);
2674 		cond_resched();
2675 	}
2676 	mpd->scanned_until_end = 1;
2677 	return 0;
2678 out:
2679 	pagevec_release(&pvec);
2680 	return err;
2681 }
2682 
ext4_writepages(struct address_space * mapping,struct writeback_control * wbc)2683 static int ext4_writepages(struct address_space *mapping,
2684 			   struct writeback_control *wbc)
2685 {
2686 	pgoff_t	writeback_index = 0;
2687 	long nr_to_write = wbc->nr_to_write;
2688 	int range_whole = 0;
2689 	int cycled = 1;
2690 	handle_t *handle = NULL;
2691 	struct mpage_da_data mpd;
2692 	struct inode *inode = mapping->host;
2693 	int needed_blocks, rsv_blocks = 0, ret = 0;
2694 	struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2695 	struct blk_plug plug;
2696 	bool give_up_on_write = false;
2697 
2698 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2699 		return -EIO;
2700 
2701 	percpu_down_read(&sbi->s_writepages_rwsem);
2702 	trace_ext4_writepages(inode, wbc);
2703 
2704 	/*
2705 	 * No pages to write? This is mainly a kludge to avoid starting
2706 	 * a transaction for special inodes like journal inode on last iput()
2707 	 * because that could violate lock ordering on umount
2708 	 */
2709 	if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2710 		goto out_writepages;
2711 
2712 	if (ext4_should_journal_data(inode)) {
2713 		ret = generic_writepages(mapping, wbc);
2714 		goto out_writepages;
2715 	}
2716 
2717 	/*
2718 	 * If the filesystem has aborted, it is read-only, so return
2719 	 * right away instead of dumping stack traces later on that
2720 	 * will obscure the real source of the problem.  We test
2721 	 * EXT4_MF_FS_ABORTED instead of sb->s_flag's SB_RDONLY because
2722 	 * the latter could be true if the filesystem is mounted
2723 	 * read-only, and in that case, ext4_writepages should
2724 	 * *never* be called, so if that ever happens, we would want
2725 	 * the stack trace.
2726 	 */
2727 	if (unlikely(ext4_forced_shutdown(EXT4_SB(mapping->host->i_sb)) ||
2728 		     ext4_test_mount_flag(inode->i_sb, EXT4_MF_FS_ABORTED))) {
2729 		ret = -EROFS;
2730 		goto out_writepages;
2731 	}
2732 
2733 	/*
2734 	 * If we have inline data and arrive here, it means that
2735 	 * we will soon create the block for the 1st page, so
2736 	 * we'd better clear the inline data here.
2737 	 */
2738 	if (ext4_has_inline_data(inode)) {
2739 		/* Just inode will be modified... */
2740 		handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2741 		if (IS_ERR(handle)) {
2742 			ret = PTR_ERR(handle);
2743 			goto out_writepages;
2744 		}
2745 		BUG_ON(ext4_test_inode_state(inode,
2746 				EXT4_STATE_MAY_INLINE_DATA));
2747 		ext4_destroy_inline_data(handle, inode);
2748 		ext4_journal_stop(handle);
2749 	}
2750 
2751 	if (ext4_should_dioread_nolock(inode)) {
2752 		/*
2753 		 * We may need to convert up to one extent per block in
2754 		 * the page and we may dirty the inode.
2755 		 */
2756 		rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
2757 						PAGE_SIZE >> inode->i_blkbits);
2758 	}
2759 
2760 	if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2761 		range_whole = 1;
2762 
2763 	if (wbc->range_cyclic) {
2764 		writeback_index = mapping->writeback_index;
2765 		if (writeback_index)
2766 			cycled = 0;
2767 		mpd.first_page = writeback_index;
2768 		mpd.last_page = -1;
2769 	} else {
2770 		mpd.first_page = wbc->range_start >> PAGE_SHIFT;
2771 		mpd.last_page = wbc->range_end >> PAGE_SHIFT;
2772 	}
2773 
2774 	mpd.inode = inode;
2775 	mpd.wbc = wbc;
2776 	ext4_io_submit_init(&mpd.io_submit, wbc);
2777 retry:
2778 	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2779 		tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
2780 	blk_start_plug(&plug);
2781 
2782 	/*
2783 	 * First writeback pages that don't need mapping - we can avoid
2784 	 * starting a transaction unnecessarily and also avoid being blocked
2785 	 * in the block layer on device congestion while having transaction
2786 	 * started.
2787 	 */
2788 	mpd.do_map = 0;
2789 	mpd.scanned_until_end = 0;
2790 	mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2791 	if (!mpd.io_submit.io_end) {
2792 		ret = -ENOMEM;
2793 		goto unplug;
2794 	}
2795 	ret = mpage_prepare_extent_to_map(&mpd);
2796 	/* Unlock pages we didn't use */
2797 	mpage_release_unused_pages(&mpd, false);
2798 	/* Submit prepared bio */
2799 	ext4_io_submit(&mpd.io_submit);
2800 	ext4_put_io_end_defer(mpd.io_submit.io_end);
2801 	mpd.io_submit.io_end = NULL;
2802 	if (ret < 0)
2803 		goto unplug;
2804 
2805 	while (!mpd.scanned_until_end && wbc->nr_to_write > 0) {
2806 		/* For each extent of pages we use new io_end */
2807 		mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2808 		if (!mpd.io_submit.io_end) {
2809 			ret = -ENOMEM;
2810 			break;
2811 		}
2812 
2813 		/*
2814 		 * We have two constraints: We find one extent to map and we
2815 		 * must always write out whole page (makes a difference when
2816 		 * blocksize < pagesize) so that we don't block on IO when we
2817 		 * try to write out the rest of the page. Journalled mode is
2818 		 * not supported by delalloc.
2819 		 */
2820 		BUG_ON(ext4_should_journal_data(inode));
2821 		needed_blocks = ext4_da_writepages_trans_blocks(inode);
2822 
2823 		/* start a new transaction */
2824 		handle = ext4_journal_start_with_reserve(inode,
2825 				EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
2826 		if (IS_ERR(handle)) {
2827 			ret = PTR_ERR(handle);
2828 			ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2829 			       "%ld pages, ino %lu; err %d", __func__,
2830 				wbc->nr_to_write, inode->i_ino, ret);
2831 			/* Release allocated io_end */
2832 			ext4_put_io_end(mpd.io_submit.io_end);
2833 			mpd.io_submit.io_end = NULL;
2834 			break;
2835 		}
2836 		mpd.do_map = 1;
2837 
2838 		trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
2839 		ret = mpage_prepare_extent_to_map(&mpd);
2840 		if (!ret && mpd.map.m_len)
2841 			ret = mpage_map_and_submit_extent(handle, &mpd,
2842 					&give_up_on_write);
2843 		/*
2844 		 * Caution: If the handle is synchronous,
2845 		 * ext4_journal_stop() can wait for transaction commit
2846 		 * to finish which may depend on writeback of pages to
2847 		 * complete or on page lock to be released.  In that
2848 		 * case, we have to wait until after we have
2849 		 * submitted all the IO, released page locks we hold,
2850 		 * and dropped io_end reference (for extent conversion
2851 		 * to be able to complete) before stopping the handle.
2852 		 */
2853 		if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
2854 			ext4_journal_stop(handle);
2855 			handle = NULL;
2856 			mpd.do_map = 0;
2857 		}
2858 		/* Unlock pages we didn't use */
2859 		mpage_release_unused_pages(&mpd, give_up_on_write);
2860 		/* Submit prepared bio */
2861 		ext4_io_submit(&mpd.io_submit);
2862 
2863 		/*
2864 		 * Drop our io_end reference we got from init. We have
2865 		 * to be careful and use deferred io_end finishing if
2866 		 * we are still holding the transaction as we can
2867 		 * release the last reference to io_end which may end
2868 		 * up doing unwritten extent conversion.
2869 		 */
2870 		if (handle) {
2871 			ext4_put_io_end_defer(mpd.io_submit.io_end);
2872 			ext4_journal_stop(handle);
2873 		} else
2874 			ext4_put_io_end(mpd.io_submit.io_end);
2875 		mpd.io_submit.io_end = NULL;
2876 
2877 		if (ret == -ENOSPC && sbi->s_journal) {
2878 			/*
2879 			 * Commit the transaction which would
2880 			 * free blocks released in the transaction
2881 			 * and try again
2882 			 */
2883 			jbd2_journal_force_commit_nested(sbi->s_journal);
2884 			ret = 0;
2885 			continue;
2886 		}
2887 		/* Fatal error - ENOMEM, EIO... */
2888 		if (ret)
2889 			break;
2890 	}
2891 unplug:
2892 	blk_finish_plug(&plug);
2893 	if (!ret && !cycled && wbc->nr_to_write > 0) {
2894 		cycled = 1;
2895 		mpd.last_page = writeback_index - 1;
2896 		mpd.first_page = 0;
2897 		goto retry;
2898 	}
2899 
2900 	/* Update index */
2901 	if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2902 		/*
2903 		 * Set the writeback_index so that range_cyclic
2904 		 * mode will write it back later
2905 		 */
2906 		mapping->writeback_index = mpd.first_page;
2907 
2908 out_writepages:
2909 	trace_ext4_writepages_result(inode, wbc, ret,
2910 				     nr_to_write - wbc->nr_to_write);
2911 	percpu_up_read(&sbi->s_writepages_rwsem);
2912 	return ret;
2913 }
2914 
ext4_dax_writepages(struct address_space * mapping,struct writeback_control * wbc)2915 static int ext4_dax_writepages(struct address_space *mapping,
2916 			       struct writeback_control *wbc)
2917 {
2918 	int ret;
2919 	long nr_to_write = wbc->nr_to_write;
2920 	struct inode *inode = mapping->host;
2921 	struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2922 
2923 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2924 		return -EIO;
2925 
2926 	percpu_down_read(&sbi->s_writepages_rwsem);
2927 	trace_ext4_writepages(inode, wbc);
2928 
2929 	ret = dax_writeback_mapping_range(mapping, sbi->s_daxdev, wbc);
2930 	trace_ext4_writepages_result(inode, wbc, ret,
2931 				     nr_to_write - wbc->nr_to_write);
2932 	percpu_up_read(&sbi->s_writepages_rwsem);
2933 	return ret;
2934 }
2935 
ext4_nonda_switch(struct super_block * sb)2936 static int ext4_nonda_switch(struct super_block *sb)
2937 {
2938 	s64 free_clusters, dirty_clusters;
2939 	struct ext4_sb_info *sbi = EXT4_SB(sb);
2940 
2941 	/*
2942 	 * switch to non delalloc mode if we are running low
2943 	 * on free block. The free block accounting via percpu
2944 	 * counters can get slightly wrong with percpu_counter_batch getting
2945 	 * accumulated on each CPU without updating global counters
2946 	 * Delalloc need an accurate free block accounting. So switch
2947 	 * to non delalloc when we are near to error range.
2948 	 */
2949 	free_clusters =
2950 		percpu_counter_read_positive(&sbi->s_freeclusters_counter);
2951 	dirty_clusters =
2952 		percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2953 	/*
2954 	 * Start pushing delalloc when 1/2 of free blocks are dirty.
2955 	 */
2956 	if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
2957 		try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2958 
2959 	if (2 * free_clusters < 3 * dirty_clusters ||
2960 	    free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
2961 		/*
2962 		 * free block count is less than 150% of dirty blocks
2963 		 * or free blocks is less than watermark
2964 		 */
2965 		return 1;
2966 	}
2967 	return 0;
2968 }
2969 
ext4_da_write_begin(struct file * file,struct address_space * mapping,loff_t pos,unsigned len,struct page ** pagep,void ** fsdata)2970 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2971 			       loff_t pos, unsigned len,
2972 			       struct page **pagep, void **fsdata)
2973 {
2974 	int ret, retries = 0;
2975 	struct page *page;
2976 	pgoff_t index;
2977 	struct inode *inode = mapping->host;
2978 
2979 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2980 		return -EIO;
2981 
2982 	index = pos >> PAGE_SHIFT;
2983 
2984 	if (ext4_nonda_switch(inode->i_sb) || ext4_verity_in_progress(inode)) {
2985 		*fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2986 		return ext4_write_begin(file, mapping, pos,
2987 					len, pagep, fsdata);
2988 	}
2989 	*fsdata = (void *)0;
2990 	trace_ext4_da_write_begin(inode, pos, len);
2991 
2992 	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2993 		ret = ext4_da_write_inline_data_begin(mapping, inode, pos, len,
2994 						      pagep, fsdata);
2995 		if (ret < 0)
2996 			return ret;
2997 		if (ret == 1)
2998 			return 0;
2999 	}
3000 
3001 retry:
3002 	page = grab_cache_page_write_begin(mapping, index);
3003 	if (!page)
3004 		return -ENOMEM;
3005 
3006 	/* In case writeback began while the page was unlocked */
3007 	wait_for_stable_page(page);
3008 
3009 #ifdef CONFIG_FS_ENCRYPTION
3010 	ret = ext4_block_write_begin(page, pos, len,
3011 				     ext4_da_get_block_prep);
3012 #else
3013 	ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
3014 #endif
3015 	if (ret < 0) {
3016 		unlock_page(page);
3017 		put_page(page);
3018 		/*
3019 		 * block_write_begin may have instantiated a few blocks
3020 		 * outside i_size.  Trim these off again. Don't need
3021 		 * i_size_read because we hold inode lock.
3022 		 */
3023 		if (pos + len > inode->i_size)
3024 			ext4_truncate_failed_write(inode);
3025 
3026 		if (ret == -ENOSPC &&
3027 		    ext4_should_retry_alloc(inode->i_sb, &retries))
3028 			goto retry;
3029 		return ret;
3030 	}
3031 
3032 	*pagep = page;
3033 	return ret;
3034 }
3035 
3036 /*
3037  * Check if we should update i_disksize
3038  * when write to the end of file but not require block allocation
3039  */
ext4_da_should_update_i_disksize(struct page * page,unsigned long offset)3040 static int ext4_da_should_update_i_disksize(struct page *page,
3041 					    unsigned long offset)
3042 {
3043 	struct buffer_head *bh;
3044 	struct inode *inode = page->mapping->host;
3045 	unsigned int idx;
3046 	int i;
3047 
3048 	bh = page_buffers(page);
3049 	idx = offset >> inode->i_blkbits;
3050 
3051 	for (i = 0; i < idx; i++)
3052 		bh = bh->b_this_page;
3053 
3054 	if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3055 		return 0;
3056 	return 1;
3057 }
3058 
ext4_da_write_end(struct file * file,struct address_space * mapping,loff_t pos,unsigned len,unsigned copied,struct page * page,void * fsdata)3059 static int ext4_da_write_end(struct file *file,
3060 			     struct address_space *mapping,
3061 			     loff_t pos, unsigned len, unsigned copied,
3062 			     struct page *page, void *fsdata)
3063 {
3064 	struct inode *inode = mapping->host;
3065 	loff_t new_i_size;
3066 	unsigned long start, end;
3067 	int write_mode = (int)(unsigned long)fsdata;
3068 
3069 	if (write_mode == FALL_BACK_TO_NONDELALLOC)
3070 		return ext4_write_end(file, mapping, pos,
3071 				      len, copied, page, fsdata);
3072 
3073 	trace_ext4_da_write_end(inode, pos, len, copied);
3074 
3075 	if (write_mode != CONVERT_INLINE_DATA &&
3076 	    ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
3077 	    ext4_has_inline_data(inode))
3078 		return ext4_write_inline_data_end(inode, pos, len, copied, page);
3079 
3080 	start = pos & (PAGE_SIZE - 1);
3081 	end = start + copied - 1;
3082 
3083 	/*
3084 	 * Since we are holding inode lock, we are sure i_disksize <=
3085 	 * i_size. We also know that if i_disksize < i_size, there are
3086 	 * delalloc writes pending in the range upto i_size. If the end of
3087 	 * the current write is <= i_size, there's no need to touch
3088 	 * i_disksize since writeback will push i_disksize upto i_size
3089 	 * eventually. If the end of the current write is > i_size and
3090 	 * inside an allocated block (ext4_da_should_update_i_disksize()
3091 	 * check), we need to update i_disksize here as neither
3092 	 * ext4_writepage() nor certain ext4_writepages() paths not
3093 	 * allocating blocks update i_disksize.
3094 	 *
3095 	 * Note that we defer inode dirtying to generic_write_end() /
3096 	 * ext4_da_write_inline_data_end().
3097 	 */
3098 	new_i_size = pos + copied;
3099 	if (copied && new_i_size > inode->i_size &&
3100 	    ext4_da_should_update_i_disksize(page, end))
3101 		ext4_update_i_disksize(inode, new_i_size);
3102 
3103 	return generic_write_end(file, mapping, pos, len, copied, page, fsdata);
3104 }
3105 
3106 /*
3107  * Force all delayed allocation blocks to be allocated for a given inode.
3108  */
ext4_alloc_da_blocks(struct inode * inode)3109 int ext4_alloc_da_blocks(struct inode *inode)
3110 {
3111 	trace_ext4_alloc_da_blocks(inode);
3112 
3113 	if (!EXT4_I(inode)->i_reserved_data_blocks)
3114 		return 0;
3115 
3116 	/*
3117 	 * We do something simple for now.  The filemap_flush() will
3118 	 * also start triggering a write of the data blocks, which is
3119 	 * not strictly speaking necessary (and for users of
3120 	 * laptop_mode, not even desirable).  However, to do otherwise
3121 	 * would require replicating code paths in:
3122 	 *
3123 	 * ext4_writepages() ->
3124 	 *    write_cache_pages() ---> (via passed in callback function)
3125 	 *        __mpage_da_writepage() -->
3126 	 *           mpage_add_bh_to_extent()
3127 	 *           mpage_da_map_blocks()
3128 	 *
3129 	 * The problem is that write_cache_pages(), located in
3130 	 * mm/page-writeback.c, marks pages clean in preparation for
3131 	 * doing I/O, which is not desirable if we're not planning on
3132 	 * doing I/O at all.
3133 	 *
3134 	 * We could call write_cache_pages(), and then redirty all of
3135 	 * the pages by calling redirty_page_for_writepage() but that
3136 	 * would be ugly in the extreme.  So instead we would need to
3137 	 * replicate parts of the code in the above functions,
3138 	 * simplifying them because we wouldn't actually intend to
3139 	 * write out the pages, but rather only collect contiguous
3140 	 * logical block extents, call the multi-block allocator, and
3141 	 * then update the buffer heads with the block allocations.
3142 	 *
3143 	 * For now, though, we'll cheat by calling filemap_flush(),
3144 	 * which will map the blocks, and start the I/O, but not
3145 	 * actually wait for the I/O to complete.
3146 	 */
3147 	return filemap_flush(inode->i_mapping);
3148 }
3149 
3150 /*
3151  * bmap() is special.  It gets used by applications such as lilo and by
3152  * the swapper to find the on-disk block of a specific piece of data.
3153  *
3154  * Naturally, this is dangerous if the block concerned is still in the
3155  * journal.  If somebody makes a swapfile on an ext4 data-journaling
3156  * filesystem and enables swap, then they may get a nasty shock when the
3157  * data getting swapped to that swapfile suddenly gets overwritten by
3158  * the original zero's written out previously to the journal and
3159  * awaiting writeback in the kernel's buffer cache.
3160  *
3161  * So, if we see any bmap calls here on a modified, data-journaled file,
3162  * take extra steps to flush any blocks which might be in the cache.
3163  */
ext4_bmap(struct address_space * mapping,sector_t block)3164 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3165 {
3166 	struct inode *inode = mapping->host;
3167 	journal_t *journal;
3168 	sector_t ret = 0;
3169 	int err;
3170 
3171 	inode_lock_shared(inode);
3172 	/*
3173 	 * We can get here for an inline file via the FIBMAP ioctl
3174 	 */
3175 	if (ext4_has_inline_data(inode))
3176 		goto out;
3177 
3178 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3179 			test_opt(inode->i_sb, DELALLOC)) {
3180 		/*
3181 		 * With delalloc we want to sync the file
3182 		 * so that we can make sure we allocate
3183 		 * blocks for file
3184 		 */
3185 		filemap_write_and_wait(mapping);
3186 	}
3187 
3188 	if (EXT4_JOURNAL(inode) &&
3189 	    ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3190 		/*
3191 		 * This is a REALLY heavyweight approach, but the use of
3192 		 * bmap on dirty files is expected to be extremely rare:
3193 		 * only if we run lilo or swapon on a freshly made file
3194 		 * do we expect this to happen.
3195 		 *
3196 		 * (bmap requires CAP_SYS_RAWIO so this does not
3197 		 * represent an unprivileged user DOS attack --- we'd be
3198 		 * in trouble if mortal users could trigger this path at
3199 		 * will.)
3200 		 *
3201 		 * NB. EXT4_STATE_JDATA is not set on files other than
3202 		 * regular files.  If somebody wants to bmap a directory
3203 		 * or symlink and gets confused because the buffer
3204 		 * hasn't yet been flushed to disk, they deserve
3205 		 * everything they get.
3206 		 */
3207 
3208 		ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3209 		journal = EXT4_JOURNAL(inode);
3210 		jbd2_journal_lock_updates(journal);
3211 		err = jbd2_journal_flush(journal, 0);
3212 		jbd2_journal_unlock_updates(journal);
3213 
3214 		if (err)
3215 			goto out;
3216 	}
3217 
3218 	ret = iomap_bmap(mapping, block, &ext4_iomap_ops);
3219 
3220 out:
3221 	inode_unlock_shared(inode);
3222 	return ret;
3223 }
3224 
ext4_read_folio(struct file * file,struct folio * folio)3225 static int ext4_read_folio(struct file *file, struct folio *folio)
3226 {
3227 	struct page *page = &folio->page;
3228 	int ret = -EAGAIN;
3229 	struct inode *inode = page->mapping->host;
3230 
3231 	trace_ext4_readpage(page);
3232 
3233 	if (ext4_has_inline_data(inode))
3234 		ret = ext4_readpage_inline(inode, page);
3235 
3236 	if (ret == -EAGAIN)
3237 		return ext4_mpage_readpages(inode, NULL, page);
3238 
3239 	return ret;
3240 }
3241 
ext4_readahead(struct readahead_control * rac)3242 static void ext4_readahead(struct readahead_control *rac)
3243 {
3244 	struct inode *inode = rac->mapping->host;
3245 
3246 	/* If the file has inline data, no need to do readahead. */
3247 	if (ext4_has_inline_data(inode))
3248 		return;
3249 
3250 	ext4_mpage_readpages(inode, rac, NULL);
3251 }
3252 
ext4_invalidate_folio(struct folio * folio,size_t offset,size_t length)3253 static void ext4_invalidate_folio(struct folio *folio, size_t offset,
3254 				size_t length)
3255 {
3256 	trace_ext4_invalidate_folio(folio, offset, length);
3257 
3258 	/* No journalling happens on data buffers when this function is used */
3259 	WARN_ON(folio_buffers(folio) && buffer_jbd(folio_buffers(folio)));
3260 
3261 	block_invalidate_folio(folio, offset, length);
3262 }
3263 
__ext4_journalled_invalidate_folio(struct folio * folio,size_t offset,size_t length)3264 static int __ext4_journalled_invalidate_folio(struct folio *folio,
3265 					    size_t offset, size_t length)
3266 {
3267 	journal_t *journal = EXT4_JOURNAL(folio->mapping->host);
3268 
3269 	trace_ext4_journalled_invalidate_folio(folio, offset, length);
3270 
3271 	/*
3272 	 * If it's a full truncate we just forget about the pending dirtying
3273 	 */
3274 	if (offset == 0 && length == folio_size(folio))
3275 		folio_clear_checked(folio);
3276 
3277 	return jbd2_journal_invalidate_folio(journal, folio, offset, length);
3278 }
3279 
3280 /* Wrapper for aops... */
ext4_journalled_invalidate_folio(struct folio * folio,size_t offset,size_t length)3281 static void ext4_journalled_invalidate_folio(struct folio *folio,
3282 					   size_t offset,
3283 					   size_t length)
3284 {
3285 	WARN_ON(__ext4_journalled_invalidate_folio(folio, offset, length) < 0);
3286 }
3287 
ext4_release_folio(struct folio * folio,gfp_t wait)3288 static bool ext4_release_folio(struct folio *folio, gfp_t wait)
3289 {
3290 	journal_t *journal = EXT4_JOURNAL(folio->mapping->host);
3291 
3292 	trace_ext4_releasepage(&folio->page);
3293 
3294 	/* Page has dirty journalled data -> cannot release */
3295 	if (folio_test_checked(folio))
3296 		return false;
3297 	if (journal)
3298 		return jbd2_journal_try_to_free_buffers(journal, folio);
3299 	else
3300 		return try_to_free_buffers(folio);
3301 }
3302 
ext4_inode_datasync_dirty(struct inode * inode)3303 static bool ext4_inode_datasync_dirty(struct inode *inode)
3304 {
3305 	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
3306 
3307 	if (journal) {
3308 		if (jbd2_transaction_committed(journal,
3309 			EXT4_I(inode)->i_datasync_tid))
3310 			return false;
3311 		if (test_opt2(inode->i_sb, JOURNAL_FAST_COMMIT))
3312 			return !list_empty(&EXT4_I(inode)->i_fc_list);
3313 		return true;
3314 	}
3315 
3316 	/* Any metadata buffers to write? */
3317 	if (!list_empty(&inode->i_mapping->private_list))
3318 		return true;
3319 	return inode->i_state & I_DIRTY_DATASYNC;
3320 }
3321 
ext4_set_iomap(struct inode * inode,struct iomap * iomap,struct ext4_map_blocks * map,loff_t offset,loff_t length,unsigned int flags)3322 static void ext4_set_iomap(struct inode *inode, struct iomap *iomap,
3323 			   struct ext4_map_blocks *map, loff_t offset,
3324 			   loff_t length, unsigned int flags)
3325 {
3326 	u8 blkbits = inode->i_blkbits;
3327 
3328 	/*
3329 	 * Writes that span EOF might trigger an I/O size update on completion,
3330 	 * so consider them to be dirty for the purpose of O_DSYNC, even if
3331 	 * there is no other metadata changes being made or are pending.
3332 	 */
3333 	iomap->flags = 0;
3334 	if (ext4_inode_datasync_dirty(inode) ||
3335 	    offset + length > i_size_read(inode))
3336 		iomap->flags |= IOMAP_F_DIRTY;
3337 
3338 	if (map->m_flags & EXT4_MAP_NEW)
3339 		iomap->flags |= IOMAP_F_NEW;
3340 
3341 	if (flags & IOMAP_DAX)
3342 		iomap->dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
3343 	else
3344 		iomap->bdev = inode->i_sb->s_bdev;
3345 	iomap->offset = (u64) map->m_lblk << blkbits;
3346 	iomap->length = (u64) map->m_len << blkbits;
3347 
3348 	if ((map->m_flags & EXT4_MAP_MAPPED) &&
3349 	    !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3350 		iomap->flags |= IOMAP_F_MERGED;
3351 
3352 	/*
3353 	 * Flags passed to ext4_map_blocks() for direct I/O writes can result
3354 	 * in m_flags having both EXT4_MAP_MAPPED and EXT4_MAP_UNWRITTEN bits
3355 	 * set. In order for any allocated unwritten extents to be converted
3356 	 * into written extents correctly within the ->end_io() handler, we
3357 	 * need to ensure that the iomap->type is set appropriately. Hence, the
3358 	 * reason why we need to check whether the EXT4_MAP_UNWRITTEN bit has
3359 	 * been set first.
3360 	 */
3361 	if (map->m_flags & EXT4_MAP_UNWRITTEN) {
3362 		iomap->type = IOMAP_UNWRITTEN;
3363 		iomap->addr = (u64) map->m_pblk << blkbits;
3364 		if (flags & IOMAP_DAX)
3365 			iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
3366 	} else if (map->m_flags & EXT4_MAP_MAPPED) {
3367 		iomap->type = IOMAP_MAPPED;
3368 		iomap->addr = (u64) map->m_pblk << blkbits;
3369 		if (flags & IOMAP_DAX)
3370 			iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
3371 	} else {
3372 		iomap->type = IOMAP_HOLE;
3373 		iomap->addr = IOMAP_NULL_ADDR;
3374 	}
3375 }
3376 
ext4_iomap_alloc(struct inode * inode,struct ext4_map_blocks * map,unsigned int flags)3377 static int ext4_iomap_alloc(struct inode *inode, struct ext4_map_blocks *map,
3378 			    unsigned int flags)
3379 {
3380 	handle_t *handle;
3381 	u8 blkbits = inode->i_blkbits;
3382 	int ret, dio_credits, m_flags = 0, retries = 0;
3383 
3384 	/*
3385 	 * Trim the mapping request to the maximum value that we can map at
3386 	 * once for direct I/O.
3387 	 */
3388 	if (map->m_len > DIO_MAX_BLOCKS)
3389 		map->m_len = DIO_MAX_BLOCKS;
3390 	dio_credits = ext4_chunk_trans_blocks(inode, map->m_len);
3391 
3392 retry:
3393 	/*
3394 	 * Either we allocate blocks and then don't get an unwritten extent, so
3395 	 * in that case we have reserved enough credits. Or, the blocks are
3396 	 * already allocated and unwritten. In that case, the extent conversion
3397 	 * fits into the credits as well.
3398 	 */
3399 	handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
3400 	if (IS_ERR(handle))
3401 		return PTR_ERR(handle);
3402 
3403 	/*
3404 	 * DAX and direct I/O are the only two operations that are currently
3405 	 * supported with IOMAP_WRITE.
3406 	 */
3407 	WARN_ON(!(flags & (IOMAP_DAX | IOMAP_DIRECT)));
3408 	if (flags & IOMAP_DAX)
3409 		m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
3410 	/*
3411 	 * We use i_size instead of i_disksize here because delalloc writeback
3412 	 * can complete at any point during the I/O and subsequently push the
3413 	 * i_disksize out to i_size. This could be beyond where direct I/O is
3414 	 * happening and thus expose allocated blocks to direct I/O reads.
3415 	 */
3416 	else if (((loff_t)map->m_lblk << blkbits) >= i_size_read(inode))
3417 		m_flags = EXT4_GET_BLOCKS_CREATE;
3418 	else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3419 		m_flags = EXT4_GET_BLOCKS_IO_CREATE_EXT;
3420 
3421 	ret = ext4_map_blocks(handle, inode, map, m_flags);
3422 
3423 	/*
3424 	 * We cannot fill holes in indirect tree based inodes as that could
3425 	 * expose stale data in the case of a crash. Use the magic error code
3426 	 * to fallback to buffered I/O.
3427 	 */
3428 	if (!m_flags && !ret)
3429 		ret = -ENOTBLK;
3430 
3431 	ext4_journal_stop(handle);
3432 	if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3433 		goto retry;
3434 
3435 	return ret;
3436 }
3437 
3438 
ext4_iomap_begin(struct inode * inode,loff_t offset,loff_t length,unsigned flags,struct iomap * iomap,struct iomap * srcmap)3439 static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3440 		unsigned flags, struct iomap *iomap, struct iomap *srcmap)
3441 {
3442 	int ret;
3443 	struct ext4_map_blocks map;
3444 	u8 blkbits = inode->i_blkbits;
3445 
3446 	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3447 		return -EINVAL;
3448 
3449 	if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3450 		return -ERANGE;
3451 
3452 	/*
3453 	 * Calculate the first and last logical blocks respectively.
3454 	 */
3455 	map.m_lblk = offset >> blkbits;
3456 	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3457 			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3458 
3459 	if (flags & IOMAP_WRITE) {
3460 		/*
3461 		 * We check here if the blocks are already allocated, then we
3462 		 * don't need to start a journal txn and we can directly return
3463 		 * the mapping information. This could boost performance
3464 		 * especially in multi-threaded overwrite requests.
3465 		 */
3466 		if (offset + length <= i_size_read(inode)) {
3467 			ret = ext4_map_blocks(NULL, inode, &map, 0);
3468 			if (ret > 0 && (map.m_flags & EXT4_MAP_MAPPED))
3469 				goto out;
3470 		}
3471 		ret = ext4_iomap_alloc(inode, &map, flags);
3472 	} else {
3473 		ret = ext4_map_blocks(NULL, inode, &map, 0);
3474 	}
3475 
3476 	if (ret < 0)
3477 		return ret;
3478 out:
3479 	/*
3480 	 * When inline encryption is enabled, sometimes I/O to an encrypted file
3481 	 * has to be broken up to guarantee DUN contiguity.  Handle this by
3482 	 * limiting the length of the mapping returned.
3483 	 */
3484 	map.m_len = fscrypt_limit_io_blocks(inode, map.m_lblk, map.m_len);
3485 
3486 	ext4_set_iomap(inode, iomap, &map, offset, length, flags);
3487 
3488 	return 0;
3489 }
3490 
ext4_iomap_overwrite_begin(struct inode * inode,loff_t offset,loff_t length,unsigned flags,struct iomap * iomap,struct iomap * srcmap)3491 static int ext4_iomap_overwrite_begin(struct inode *inode, loff_t offset,
3492 		loff_t length, unsigned flags, struct iomap *iomap,
3493 		struct iomap *srcmap)
3494 {
3495 	int ret;
3496 
3497 	/*
3498 	 * Even for writes we don't need to allocate blocks, so just pretend
3499 	 * we are reading to save overhead of starting a transaction.
3500 	 */
3501 	flags &= ~IOMAP_WRITE;
3502 	ret = ext4_iomap_begin(inode, offset, length, flags, iomap, srcmap);
3503 	WARN_ON_ONCE(iomap->type != IOMAP_MAPPED);
3504 	return ret;
3505 }
3506 
ext4_iomap_end(struct inode * inode,loff_t offset,loff_t length,ssize_t written,unsigned flags,struct iomap * iomap)3507 static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3508 			  ssize_t written, unsigned flags, struct iomap *iomap)
3509 {
3510 	/*
3511 	 * Check to see whether an error occurred while writing out the data to
3512 	 * the allocated blocks. If so, return the magic error code so that we
3513 	 * fallback to buffered I/O and attempt to complete the remainder of
3514 	 * the I/O. Any blocks that may have been allocated in preparation for
3515 	 * the direct I/O will be reused during buffered I/O.
3516 	 */
3517 	if (flags & (IOMAP_WRITE | IOMAP_DIRECT) && written == 0)
3518 		return -ENOTBLK;
3519 
3520 	return 0;
3521 }
3522 
3523 const struct iomap_ops ext4_iomap_ops = {
3524 	.iomap_begin		= ext4_iomap_begin,
3525 	.iomap_end		= ext4_iomap_end,
3526 };
3527 
3528 const struct iomap_ops ext4_iomap_overwrite_ops = {
3529 	.iomap_begin		= ext4_iomap_overwrite_begin,
3530 	.iomap_end		= ext4_iomap_end,
3531 };
3532 
ext4_iomap_is_delalloc(struct inode * inode,struct ext4_map_blocks * map)3533 static bool ext4_iomap_is_delalloc(struct inode *inode,
3534 				   struct ext4_map_blocks *map)
3535 {
3536 	struct extent_status es;
3537 	ext4_lblk_t offset = 0, end = map->m_lblk + map->m_len - 1;
3538 
3539 	ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
3540 				  map->m_lblk, end, &es);
3541 
3542 	if (!es.es_len || es.es_lblk > end)
3543 		return false;
3544 
3545 	if (es.es_lblk > map->m_lblk) {
3546 		map->m_len = es.es_lblk - map->m_lblk;
3547 		return false;
3548 	}
3549 
3550 	offset = map->m_lblk - es.es_lblk;
3551 	map->m_len = es.es_len - offset;
3552 
3553 	return true;
3554 }
3555 
ext4_iomap_begin_report(struct inode * inode,loff_t offset,loff_t length,unsigned int flags,struct iomap * iomap,struct iomap * srcmap)3556 static int ext4_iomap_begin_report(struct inode *inode, loff_t offset,
3557 				   loff_t length, unsigned int flags,
3558 				   struct iomap *iomap, struct iomap *srcmap)
3559 {
3560 	int ret;
3561 	bool delalloc = false;
3562 	struct ext4_map_blocks map;
3563 	u8 blkbits = inode->i_blkbits;
3564 
3565 	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3566 		return -EINVAL;
3567 
3568 	if (ext4_has_inline_data(inode)) {
3569 		ret = ext4_inline_data_iomap(inode, iomap);
3570 		if (ret != -EAGAIN) {
3571 			if (ret == 0 && offset >= iomap->length)
3572 				ret = -ENOENT;
3573 			return ret;
3574 		}
3575 	}
3576 
3577 	/*
3578 	 * Calculate the first and last logical block respectively.
3579 	 */
3580 	map.m_lblk = offset >> blkbits;
3581 	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3582 			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3583 
3584 	/*
3585 	 * Fiemap callers may call for offset beyond s_bitmap_maxbytes.
3586 	 * So handle it here itself instead of querying ext4_map_blocks().
3587 	 * Since ext4_map_blocks() will warn about it and will return
3588 	 * -EIO error.
3589 	 */
3590 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
3591 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3592 
3593 		if (offset >= sbi->s_bitmap_maxbytes) {
3594 			map.m_flags = 0;
3595 			goto set_iomap;
3596 		}
3597 	}
3598 
3599 	ret = ext4_map_blocks(NULL, inode, &map, 0);
3600 	if (ret < 0)
3601 		return ret;
3602 	if (ret == 0)
3603 		delalloc = ext4_iomap_is_delalloc(inode, &map);
3604 
3605 set_iomap:
3606 	ext4_set_iomap(inode, iomap, &map, offset, length, flags);
3607 	if (delalloc && iomap->type == IOMAP_HOLE)
3608 		iomap->type = IOMAP_DELALLOC;
3609 
3610 	return 0;
3611 }
3612 
3613 const struct iomap_ops ext4_iomap_report_ops = {
3614 	.iomap_begin = ext4_iomap_begin_report,
3615 };
3616 
3617 /*
3618  * Whenever the folio is being dirtied, corresponding buffers should already
3619  * be attached to the transaction (we take care of this in ext4_page_mkwrite()
3620  * and ext4_write_begin()). However we cannot move buffers to dirty transaction
3621  * lists here because ->dirty_folio is called under VFS locks and the folio
3622  * is not necessarily locked.
3623  *
3624  * We cannot just dirty the folio and leave attached buffers clean, because the
3625  * buffers' dirty state is "definitive".  We cannot just set the buffers dirty
3626  * or jbddirty because all the journalling code will explode.
3627  *
3628  * So what we do is to mark the folio "pending dirty" and next time writepage
3629  * is called, propagate that into the buffers appropriately.
3630  */
ext4_journalled_dirty_folio(struct address_space * mapping,struct folio * folio)3631 static bool ext4_journalled_dirty_folio(struct address_space *mapping,
3632 		struct folio *folio)
3633 {
3634 	WARN_ON_ONCE(!folio_buffers(folio));
3635 	folio_set_checked(folio);
3636 	return filemap_dirty_folio(mapping, folio);
3637 }
3638 
ext4_dirty_folio(struct address_space * mapping,struct folio * folio)3639 static bool ext4_dirty_folio(struct address_space *mapping, struct folio *folio)
3640 {
3641 	WARN_ON_ONCE(!folio_test_locked(folio) && !folio_test_dirty(folio));
3642 	WARN_ON_ONCE(!folio_buffers(folio));
3643 	return block_dirty_folio(mapping, folio);
3644 }
3645 
ext4_iomap_swap_activate(struct swap_info_struct * sis,struct file * file,sector_t * span)3646 static int ext4_iomap_swap_activate(struct swap_info_struct *sis,
3647 				    struct file *file, sector_t *span)
3648 {
3649 	return iomap_swapfile_activate(sis, file, span,
3650 				       &ext4_iomap_report_ops);
3651 }
3652 
3653 static const struct address_space_operations ext4_aops = {
3654 	.read_folio		= ext4_read_folio,
3655 	.readahead		= ext4_readahead,
3656 	.writepage		= ext4_writepage,
3657 	.writepages		= ext4_writepages,
3658 	.write_begin		= ext4_write_begin,
3659 	.write_end		= ext4_write_end,
3660 	.dirty_folio		= ext4_dirty_folio,
3661 	.bmap			= ext4_bmap,
3662 	.invalidate_folio	= ext4_invalidate_folio,
3663 	.release_folio		= ext4_release_folio,
3664 	.direct_IO		= noop_direct_IO,
3665 	.migrate_folio		= buffer_migrate_folio,
3666 	.is_partially_uptodate  = block_is_partially_uptodate,
3667 	.error_remove_page	= generic_error_remove_page,
3668 	.swap_activate		= ext4_iomap_swap_activate,
3669 };
3670 
3671 static const struct address_space_operations ext4_journalled_aops = {
3672 	.read_folio		= ext4_read_folio,
3673 	.readahead		= ext4_readahead,
3674 	.writepage		= ext4_writepage,
3675 	.writepages		= ext4_writepages,
3676 	.write_begin		= ext4_write_begin,
3677 	.write_end		= ext4_journalled_write_end,
3678 	.dirty_folio		= ext4_journalled_dirty_folio,
3679 	.bmap			= ext4_bmap,
3680 	.invalidate_folio	= ext4_journalled_invalidate_folio,
3681 	.release_folio		= ext4_release_folio,
3682 	.direct_IO		= noop_direct_IO,
3683 	.is_partially_uptodate  = block_is_partially_uptodate,
3684 	.error_remove_page	= generic_error_remove_page,
3685 	.swap_activate		= ext4_iomap_swap_activate,
3686 };
3687 
3688 static const struct address_space_operations ext4_da_aops = {
3689 	.read_folio		= ext4_read_folio,
3690 	.readahead		= ext4_readahead,
3691 	.writepage		= ext4_writepage,
3692 	.writepages		= ext4_writepages,
3693 	.write_begin		= ext4_da_write_begin,
3694 	.write_end		= ext4_da_write_end,
3695 	.dirty_folio		= ext4_dirty_folio,
3696 	.bmap			= ext4_bmap,
3697 	.invalidate_folio	= ext4_invalidate_folio,
3698 	.release_folio		= ext4_release_folio,
3699 	.direct_IO		= noop_direct_IO,
3700 	.migrate_folio		= buffer_migrate_folio,
3701 	.is_partially_uptodate  = block_is_partially_uptodate,
3702 	.error_remove_page	= generic_error_remove_page,
3703 	.swap_activate		= ext4_iomap_swap_activate,
3704 };
3705 
3706 static const struct address_space_operations ext4_dax_aops = {
3707 	.writepages		= ext4_dax_writepages,
3708 	.direct_IO		= noop_direct_IO,
3709 	.dirty_folio		= noop_dirty_folio,
3710 	.bmap			= ext4_bmap,
3711 	.swap_activate		= ext4_iomap_swap_activate,
3712 };
3713 
ext4_set_aops(struct inode * inode)3714 void ext4_set_aops(struct inode *inode)
3715 {
3716 	switch (ext4_inode_journal_mode(inode)) {
3717 	case EXT4_INODE_ORDERED_DATA_MODE:
3718 	case EXT4_INODE_WRITEBACK_DATA_MODE:
3719 		break;
3720 	case EXT4_INODE_JOURNAL_DATA_MODE:
3721 		inode->i_mapping->a_ops = &ext4_journalled_aops;
3722 		return;
3723 	default:
3724 		BUG();
3725 	}
3726 	if (IS_DAX(inode))
3727 		inode->i_mapping->a_ops = &ext4_dax_aops;
3728 	else if (test_opt(inode->i_sb, DELALLOC))
3729 		inode->i_mapping->a_ops = &ext4_da_aops;
3730 	else
3731 		inode->i_mapping->a_ops = &ext4_aops;
3732 }
3733 
__ext4_block_zero_page_range(handle_t * handle,struct address_space * mapping,loff_t from,loff_t length)3734 static int __ext4_block_zero_page_range(handle_t *handle,
3735 		struct address_space *mapping, loff_t from, loff_t length)
3736 {
3737 	ext4_fsblk_t index = from >> PAGE_SHIFT;
3738 	unsigned offset = from & (PAGE_SIZE-1);
3739 	unsigned blocksize, pos;
3740 	ext4_lblk_t iblock;
3741 	struct inode *inode = mapping->host;
3742 	struct buffer_head *bh;
3743 	struct page *page;
3744 	int err = 0;
3745 
3746 	page = find_or_create_page(mapping, from >> PAGE_SHIFT,
3747 				   mapping_gfp_constraint(mapping, ~__GFP_FS));
3748 	if (!page)
3749 		return -ENOMEM;
3750 
3751 	blocksize = inode->i_sb->s_blocksize;
3752 
3753 	iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
3754 
3755 	if (!page_has_buffers(page))
3756 		create_empty_buffers(page, blocksize, 0);
3757 
3758 	/* Find the buffer that contains "offset" */
3759 	bh = page_buffers(page);
3760 	pos = blocksize;
3761 	while (offset >= pos) {
3762 		bh = bh->b_this_page;
3763 		iblock++;
3764 		pos += blocksize;
3765 	}
3766 	if (buffer_freed(bh)) {
3767 		BUFFER_TRACE(bh, "freed: skip");
3768 		goto unlock;
3769 	}
3770 	if (!buffer_mapped(bh)) {
3771 		BUFFER_TRACE(bh, "unmapped");
3772 		ext4_get_block(inode, iblock, bh, 0);
3773 		/* unmapped? It's a hole - nothing to do */
3774 		if (!buffer_mapped(bh)) {
3775 			BUFFER_TRACE(bh, "still unmapped");
3776 			goto unlock;
3777 		}
3778 	}
3779 
3780 	/* Ok, it's mapped. Make sure it's up-to-date */
3781 	if (PageUptodate(page))
3782 		set_buffer_uptodate(bh);
3783 
3784 	if (!buffer_uptodate(bh)) {
3785 		err = ext4_read_bh_lock(bh, 0, true);
3786 		if (err)
3787 			goto unlock;
3788 		if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
3789 			/* We expect the key to be set. */
3790 			BUG_ON(!fscrypt_has_encryption_key(inode));
3791 			err = fscrypt_decrypt_pagecache_blocks(page, blocksize,
3792 							       bh_offset(bh));
3793 			if (err) {
3794 				clear_buffer_uptodate(bh);
3795 				goto unlock;
3796 			}
3797 		}
3798 	}
3799 	if (ext4_should_journal_data(inode)) {
3800 		BUFFER_TRACE(bh, "get write access");
3801 		err = ext4_journal_get_write_access(handle, inode->i_sb, bh,
3802 						    EXT4_JTR_NONE);
3803 		if (err)
3804 			goto unlock;
3805 	}
3806 	zero_user(page, offset, length);
3807 	BUFFER_TRACE(bh, "zeroed end of block");
3808 
3809 	if (ext4_should_journal_data(inode)) {
3810 		err = ext4_handle_dirty_metadata(handle, inode, bh);
3811 	} else {
3812 		err = 0;
3813 		mark_buffer_dirty(bh);
3814 		if (ext4_should_order_data(inode))
3815 			err = ext4_jbd2_inode_add_write(handle, inode, from,
3816 					length);
3817 	}
3818 
3819 unlock:
3820 	unlock_page(page);
3821 	put_page(page);
3822 	return err;
3823 }
3824 
3825 /*
3826  * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3827  * starting from file offset 'from'.  The range to be zero'd must
3828  * be contained with in one block.  If the specified range exceeds
3829  * the end of the block it will be shortened to end of the block
3830  * that corresponds to 'from'
3831  */
ext4_block_zero_page_range(handle_t * handle,struct address_space * mapping,loff_t from,loff_t length)3832 static int ext4_block_zero_page_range(handle_t *handle,
3833 		struct address_space *mapping, loff_t from, loff_t length)
3834 {
3835 	struct inode *inode = mapping->host;
3836 	unsigned offset = from & (PAGE_SIZE-1);
3837 	unsigned blocksize = inode->i_sb->s_blocksize;
3838 	unsigned max = blocksize - (offset & (blocksize - 1));
3839 
3840 	/*
3841 	 * correct length if it does not fall between
3842 	 * 'from' and the end of the block
3843 	 */
3844 	if (length > max || length < 0)
3845 		length = max;
3846 
3847 	if (IS_DAX(inode)) {
3848 		return dax_zero_range(inode, from, length, NULL,
3849 				      &ext4_iomap_ops);
3850 	}
3851 	return __ext4_block_zero_page_range(handle, mapping, from, length);
3852 }
3853 
3854 /*
3855  * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3856  * up to the end of the block which corresponds to `from'.
3857  * This required during truncate. We need to physically zero the tail end
3858  * of that block so it doesn't yield old data if the file is later grown.
3859  */
ext4_block_truncate_page(handle_t * handle,struct address_space * mapping,loff_t from)3860 static int ext4_block_truncate_page(handle_t *handle,
3861 		struct address_space *mapping, loff_t from)
3862 {
3863 	unsigned offset = from & (PAGE_SIZE-1);
3864 	unsigned length;
3865 	unsigned blocksize;
3866 	struct inode *inode = mapping->host;
3867 
3868 	/* If we are processing an encrypted inode during orphan list handling */
3869 	if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode))
3870 		return 0;
3871 
3872 	blocksize = inode->i_sb->s_blocksize;
3873 	length = blocksize - (offset & (blocksize - 1));
3874 
3875 	return ext4_block_zero_page_range(handle, mapping, from, length);
3876 }
3877 
ext4_zero_partial_blocks(handle_t * handle,struct inode * inode,loff_t lstart,loff_t length)3878 int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3879 			     loff_t lstart, loff_t length)
3880 {
3881 	struct super_block *sb = inode->i_sb;
3882 	struct address_space *mapping = inode->i_mapping;
3883 	unsigned partial_start, partial_end;
3884 	ext4_fsblk_t start, end;
3885 	loff_t byte_end = (lstart + length - 1);
3886 	int err = 0;
3887 
3888 	partial_start = lstart & (sb->s_blocksize - 1);
3889 	partial_end = byte_end & (sb->s_blocksize - 1);
3890 
3891 	start = lstart >> sb->s_blocksize_bits;
3892 	end = byte_end >> sb->s_blocksize_bits;
3893 
3894 	/* Handle partial zero within the single block */
3895 	if (start == end &&
3896 	    (partial_start || (partial_end != sb->s_blocksize - 1))) {
3897 		err = ext4_block_zero_page_range(handle, mapping,
3898 						 lstart, length);
3899 		return err;
3900 	}
3901 	/* Handle partial zero out on the start of the range */
3902 	if (partial_start) {
3903 		err = ext4_block_zero_page_range(handle, mapping,
3904 						 lstart, sb->s_blocksize);
3905 		if (err)
3906 			return err;
3907 	}
3908 	/* Handle partial zero out on the end of the range */
3909 	if (partial_end != sb->s_blocksize - 1)
3910 		err = ext4_block_zero_page_range(handle, mapping,
3911 						 byte_end - partial_end,
3912 						 partial_end + 1);
3913 	return err;
3914 }
3915 
ext4_can_truncate(struct inode * inode)3916 int ext4_can_truncate(struct inode *inode)
3917 {
3918 	if (S_ISREG(inode->i_mode))
3919 		return 1;
3920 	if (S_ISDIR(inode->i_mode))
3921 		return 1;
3922 	if (S_ISLNK(inode->i_mode))
3923 		return !ext4_inode_is_fast_symlink(inode);
3924 	return 0;
3925 }
3926 
3927 /*
3928  * We have to make sure i_disksize gets properly updated before we truncate
3929  * page cache due to hole punching or zero range. Otherwise i_disksize update
3930  * can get lost as it may have been postponed to submission of writeback but
3931  * that will never happen after we truncate page cache.
3932  */
ext4_update_disksize_before_punch(struct inode * inode,loff_t offset,loff_t len)3933 int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
3934 				      loff_t len)
3935 {
3936 	handle_t *handle;
3937 	int ret;
3938 
3939 	loff_t size = i_size_read(inode);
3940 
3941 	WARN_ON(!inode_is_locked(inode));
3942 	if (offset > size || offset + len < size)
3943 		return 0;
3944 
3945 	if (EXT4_I(inode)->i_disksize >= size)
3946 		return 0;
3947 
3948 	handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
3949 	if (IS_ERR(handle))
3950 		return PTR_ERR(handle);
3951 	ext4_update_i_disksize(inode, size);
3952 	ret = ext4_mark_inode_dirty(handle, inode);
3953 	ext4_journal_stop(handle);
3954 
3955 	return ret;
3956 }
3957 
ext4_wait_dax_page(struct inode * inode)3958 static void ext4_wait_dax_page(struct inode *inode)
3959 {
3960 	filemap_invalidate_unlock(inode->i_mapping);
3961 	schedule();
3962 	filemap_invalidate_lock(inode->i_mapping);
3963 }
3964 
ext4_break_layouts(struct inode * inode)3965 int ext4_break_layouts(struct inode *inode)
3966 {
3967 	struct page *page;
3968 	int error;
3969 
3970 	if (WARN_ON_ONCE(!rwsem_is_locked(&inode->i_mapping->invalidate_lock)))
3971 		return -EINVAL;
3972 
3973 	do {
3974 		page = dax_layout_busy_page(inode->i_mapping);
3975 		if (!page)
3976 			return 0;
3977 
3978 		error = ___wait_var_event(&page->_refcount,
3979 				atomic_read(&page->_refcount) == 1,
3980 				TASK_INTERRUPTIBLE, 0, 0,
3981 				ext4_wait_dax_page(inode));
3982 	} while (error == 0);
3983 
3984 	return error;
3985 }
3986 
3987 /*
3988  * ext4_punch_hole: punches a hole in a file by releasing the blocks
3989  * associated with the given offset and length
3990  *
3991  * @inode:  File inode
3992  * @offset: The offset where the hole will begin
3993  * @len:    The length of the hole
3994  *
3995  * Returns: 0 on success or negative on failure
3996  */
3997 
ext4_punch_hole(struct file * file,loff_t offset,loff_t length)3998 int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
3999 {
4000 	struct inode *inode = file_inode(file);
4001 	struct super_block *sb = inode->i_sb;
4002 	ext4_lblk_t first_block, stop_block;
4003 	struct address_space *mapping = inode->i_mapping;
4004 	loff_t first_block_offset, last_block_offset, max_length;
4005 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4006 	handle_t *handle;
4007 	unsigned int credits;
4008 	int ret = 0, ret2 = 0;
4009 
4010 	trace_ext4_punch_hole(inode, offset, length, 0);
4011 
4012 	/*
4013 	 * Write out all dirty pages to avoid race conditions
4014 	 * Then release them.
4015 	 */
4016 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
4017 		ret = filemap_write_and_wait_range(mapping, offset,
4018 						   offset + length - 1);
4019 		if (ret)
4020 			return ret;
4021 	}
4022 
4023 	inode_lock(inode);
4024 
4025 	/* No need to punch hole beyond i_size */
4026 	if (offset >= inode->i_size)
4027 		goto out_mutex;
4028 
4029 	/*
4030 	 * If the hole extends beyond i_size, set the hole
4031 	 * to end after the page that contains i_size
4032 	 */
4033 	if (offset + length > inode->i_size) {
4034 		length = inode->i_size +
4035 		   PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
4036 		   offset;
4037 	}
4038 
4039 	/*
4040 	 * For punch hole the length + offset needs to be within one block
4041 	 * before last range. Adjust the length if it goes beyond that limit.
4042 	 */
4043 	max_length = sbi->s_bitmap_maxbytes - inode->i_sb->s_blocksize;
4044 	if (offset + length > max_length)
4045 		length = max_length - offset;
4046 
4047 	if (offset & (sb->s_blocksize - 1) ||
4048 	    (offset + length) & (sb->s_blocksize - 1)) {
4049 		/*
4050 		 * Attach jinode to inode for jbd2 if we do any zeroing of
4051 		 * partial block
4052 		 */
4053 		ret = ext4_inode_attach_jinode(inode);
4054 		if (ret < 0)
4055 			goto out_mutex;
4056 
4057 	}
4058 
4059 	/* Wait all existing dio workers, newcomers will block on i_rwsem */
4060 	inode_dio_wait(inode);
4061 
4062 	ret = file_modified(file);
4063 	if (ret)
4064 		goto out_mutex;
4065 
4066 	/*
4067 	 * Prevent page faults from reinstantiating pages we have released from
4068 	 * page cache.
4069 	 */
4070 	filemap_invalidate_lock(mapping);
4071 
4072 	ret = ext4_break_layouts(inode);
4073 	if (ret)
4074 		goto out_dio;
4075 
4076 	first_block_offset = round_up(offset, sb->s_blocksize);
4077 	last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
4078 
4079 	/* Now release the pages and zero block aligned part of pages*/
4080 	if (last_block_offset > first_block_offset) {
4081 		ret = ext4_update_disksize_before_punch(inode, offset, length);
4082 		if (ret)
4083 			goto out_dio;
4084 		truncate_pagecache_range(inode, first_block_offset,
4085 					 last_block_offset);
4086 	}
4087 
4088 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4089 		credits = ext4_writepage_trans_blocks(inode);
4090 	else
4091 		credits = ext4_blocks_for_truncate(inode);
4092 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4093 	if (IS_ERR(handle)) {
4094 		ret = PTR_ERR(handle);
4095 		ext4_std_error(sb, ret);
4096 		goto out_dio;
4097 	}
4098 
4099 	ret = ext4_zero_partial_blocks(handle, inode, offset,
4100 				       length);
4101 	if (ret)
4102 		goto out_stop;
4103 
4104 	first_block = (offset + sb->s_blocksize - 1) >>
4105 		EXT4_BLOCK_SIZE_BITS(sb);
4106 	stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
4107 
4108 	/* If there are blocks to remove, do it */
4109 	if (stop_block > first_block) {
4110 
4111 		down_write(&EXT4_I(inode)->i_data_sem);
4112 		ext4_discard_preallocations(inode, 0);
4113 
4114 		ret = ext4_es_remove_extent(inode, first_block,
4115 					    stop_block - first_block);
4116 		if (ret) {
4117 			up_write(&EXT4_I(inode)->i_data_sem);
4118 			goto out_stop;
4119 		}
4120 
4121 		if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4122 			ret = ext4_ext_remove_space(inode, first_block,
4123 						    stop_block - 1);
4124 		else
4125 			ret = ext4_ind_remove_space(handle, inode, first_block,
4126 						    stop_block);
4127 
4128 		up_write(&EXT4_I(inode)->i_data_sem);
4129 	}
4130 	ext4_fc_track_range(handle, inode, first_block, stop_block);
4131 	if (IS_SYNC(inode))
4132 		ext4_handle_sync(handle);
4133 
4134 	inode->i_mtime = inode->i_ctime = current_time(inode);
4135 	ret2 = ext4_mark_inode_dirty(handle, inode);
4136 	if (unlikely(ret2))
4137 		ret = ret2;
4138 	if (ret >= 0)
4139 		ext4_update_inode_fsync_trans(handle, inode, 1);
4140 out_stop:
4141 	ext4_journal_stop(handle);
4142 out_dio:
4143 	filemap_invalidate_unlock(mapping);
4144 out_mutex:
4145 	inode_unlock(inode);
4146 	return ret;
4147 }
4148 
ext4_inode_attach_jinode(struct inode * inode)4149 int ext4_inode_attach_jinode(struct inode *inode)
4150 {
4151 	struct ext4_inode_info *ei = EXT4_I(inode);
4152 	struct jbd2_inode *jinode;
4153 
4154 	if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4155 		return 0;
4156 
4157 	jinode = jbd2_alloc_inode(GFP_KERNEL);
4158 	spin_lock(&inode->i_lock);
4159 	if (!ei->jinode) {
4160 		if (!jinode) {
4161 			spin_unlock(&inode->i_lock);
4162 			return -ENOMEM;
4163 		}
4164 		ei->jinode = jinode;
4165 		jbd2_journal_init_jbd_inode(ei->jinode, inode);
4166 		jinode = NULL;
4167 	}
4168 	spin_unlock(&inode->i_lock);
4169 	if (unlikely(jinode != NULL))
4170 		jbd2_free_inode(jinode);
4171 	return 0;
4172 }
4173 
4174 /*
4175  * ext4_truncate()
4176  *
4177  * We block out ext4_get_block() block instantiations across the entire
4178  * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4179  * simultaneously on behalf of the same inode.
4180  *
4181  * As we work through the truncate and commit bits of it to the journal there
4182  * is one core, guiding principle: the file's tree must always be consistent on
4183  * disk.  We must be able to restart the truncate after a crash.
4184  *
4185  * The file's tree may be transiently inconsistent in memory (although it
4186  * probably isn't), but whenever we close off and commit a journal transaction,
4187  * the contents of (the filesystem + the journal) must be consistent and
4188  * restartable.  It's pretty simple, really: bottom up, right to left (although
4189  * left-to-right works OK too).
4190  *
4191  * Note that at recovery time, journal replay occurs *before* the restart of
4192  * truncate against the orphan inode list.
4193  *
4194  * The committed inode has the new, desired i_size (which is the same as
4195  * i_disksize in this case).  After a crash, ext4_orphan_cleanup() will see
4196  * that this inode's truncate did not complete and it will again call
4197  * ext4_truncate() to have another go.  So there will be instantiated blocks
4198  * to the right of the truncation point in a crashed ext4 filesystem.  But
4199  * that's fine - as long as they are linked from the inode, the post-crash
4200  * ext4_truncate() run will find them and release them.
4201  */
ext4_truncate(struct inode * inode)4202 int ext4_truncate(struct inode *inode)
4203 {
4204 	struct ext4_inode_info *ei = EXT4_I(inode);
4205 	unsigned int credits;
4206 	int err = 0, err2;
4207 	handle_t *handle;
4208 	struct address_space *mapping = inode->i_mapping;
4209 
4210 	/*
4211 	 * There is a possibility that we're either freeing the inode
4212 	 * or it's a completely new inode. In those cases we might not
4213 	 * have i_rwsem locked because it's not necessary.
4214 	 */
4215 	if (!(inode->i_state & (I_NEW|I_FREEING)))
4216 		WARN_ON(!inode_is_locked(inode));
4217 	trace_ext4_truncate_enter(inode);
4218 
4219 	if (!ext4_can_truncate(inode))
4220 		goto out_trace;
4221 
4222 	if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
4223 		ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
4224 
4225 	if (ext4_has_inline_data(inode)) {
4226 		int has_inline = 1;
4227 
4228 		err = ext4_inline_data_truncate(inode, &has_inline);
4229 		if (err || has_inline)
4230 			goto out_trace;
4231 	}
4232 
4233 	/* If we zero-out tail of the page, we have to create jinode for jbd2 */
4234 	if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4235 		err = ext4_inode_attach_jinode(inode);
4236 		if (err)
4237 			goto out_trace;
4238 	}
4239 
4240 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4241 		credits = ext4_writepage_trans_blocks(inode);
4242 	else
4243 		credits = ext4_blocks_for_truncate(inode);
4244 
4245 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4246 	if (IS_ERR(handle)) {
4247 		err = PTR_ERR(handle);
4248 		goto out_trace;
4249 	}
4250 
4251 	if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4252 		ext4_block_truncate_page(handle, mapping, inode->i_size);
4253 
4254 	/*
4255 	 * We add the inode to the orphan list, so that if this
4256 	 * truncate spans multiple transactions, and we crash, we will
4257 	 * resume the truncate when the filesystem recovers.  It also
4258 	 * marks the inode dirty, to catch the new size.
4259 	 *
4260 	 * Implication: the file must always be in a sane, consistent
4261 	 * truncatable state while each transaction commits.
4262 	 */
4263 	err = ext4_orphan_add(handle, inode);
4264 	if (err)
4265 		goto out_stop;
4266 
4267 	down_write(&EXT4_I(inode)->i_data_sem);
4268 
4269 	ext4_discard_preallocations(inode, 0);
4270 
4271 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4272 		err = ext4_ext_truncate(handle, inode);
4273 	else
4274 		ext4_ind_truncate(handle, inode);
4275 
4276 	up_write(&ei->i_data_sem);
4277 	if (err)
4278 		goto out_stop;
4279 
4280 	if (IS_SYNC(inode))
4281 		ext4_handle_sync(handle);
4282 
4283 out_stop:
4284 	/*
4285 	 * If this was a simple ftruncate() and the file will remain alive,
4286 	 * then we need to clear up the orphan record which we created above.
4287 	 * However, if this was a real unlink then we were called by
4288 	 * ext4_evict_inode(), and we allow that function to clean up the
4289 	 * orphan info for us.
4290 	 */
4291 	if (inode->i_nlink)
4292 		ext4_orphan_del(handle, inode);
4293 
4294 	inode->i_mtime = inode->i_ctime = current_time(inode);
4295 	err2 = ext4_mark_inode_dirty(handle, inode);
4296 	if (unlikely(err2 && !err))
4297 		err = err2;
4298 	ext4_journal_stop(handle);
4299 
4300 out_trace:
4301 	trace_ext4_truncate_exit(inode);
4302 	return err;
4303 }
4304 
ext4_inode_peek_iversion(const struct inode * inode)4305 static inline u64 ext4_inode_peek_iversion(const struct inode *inode)
4306 {
4307 	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4308 		return inode_peek_iversion_raw(inode);
4309 	else
4310 		return inode_peek_iversion(inode);
4311 }
4312 
ext4_inode_blocks_set(struct ext4_inode * raw_inode,struct ext4_inode_info * ei)4313 static int ext4_inode_blocks_set(struct ext4_inode *raw_inode,
4314 				 struct ext4_inode_info *ei)
4315 {
4316 	struct inode *inode = &(ei->vfs_inode);
4317 	u64 i_blocks = READ_ONCE(inode->i_blocks);
4318 	struct super_block *sb = inode->i_sb;
4319 
4320 	if (i_blocks <= ~0U) {
4321 		/*
4322 		 * i_blocks can be represented in a 32 bit variable
4323 		 * as multiple of 512 bytes
4324 		 */
4325 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
4326 		raw_inode->i_blocks_high = 0;
4327 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4328 		return 0;
4329 	}
4330 
4331 	/*
4332 	 * This should never happen since sb->s_maxbytes should not have
4333 	 * allowed this, sb->s_maxbytes was set according to the huge_file
4334 	 * feature in ext4_fill_super().
4335 	 */
4336 	if (!ext4_has_feature_huge_file(sb))
4337 		return -EFSCORRUPTED;
4338 
4339 	if (i_blocks <= 0xffffffffffffULL) {
4340 		/*
4341 		 * i_blocks can be represented in a 48 bit variable
4342 		 * as multiple of 512 bytes
4343 		 */
4344 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
4345 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4346 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4347 	} else {
4348 		ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4349 		/* i_block is stored in file system block size */
4350 		i_blocks = i_blocks >> (inode->i_blkbits - 9);
4351 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
4352 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4353 	}
4354 	return 0;
4355 }
4356 
ext4_fill_raw_inode(struct inode * inode,struct ext4_inode * raw_inode)4357 static int ext4_fill_raw_inode(struct inode *inode, struct ext4_inode *raw_inode)
4358 {
4359 	struct ext4_inode_info *ei = EXT4_I(inode);
4360 	uid_t i_uid;
4361 	gid_t i_gid;
4362 	projid_t i_projid;
4363 	int block;
4364 	int err;
4365 
4366 	err = ext4_inode_blocks_set(raw_inode, ei);
4367 
4368 	raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4369 	i_uid = i_uid_read(inode);
4370 	i_gid = i_gid_read(inode);
4371 	i_projid = from_kprojid(&init_user_ns, ei->i_projid);
4372 	if (!(test_opt(inode->i_sb, NO_UID32))) {
4373 		raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
4374 		raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
4375 		/*
4376 		 * Fix up interoperability with old kernels. Otherwise,
4377 		 * old inodes get re-used with the upper 16 bits of the
4378 		 * uid/gid intact.
4379 		 */
4380 		if (ei->i_dtime && list_empty(&ei->i_orphan)) {
4381 			raw_inode->i_uid_high = 0;
4382 			raw_inode->i_gid_high = 0;
4383 		} else {
4384 			raw_inode->i_uid_high =
4385 				cpu_to_le16(high_16_bits(i_uid));
4386 			raw_inode->i_gid_high =
4387 				cpu_to_le16(high_16_bits(i_gid));
4388 		}
4389 	} else {
4390 		raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
4391 		raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
4392 		raw_inode->i_uid_high = 0;
4393 		raw_inode->i_gid_high = 0;
4394 	}
4395 	raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4396 
4397 	EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4398 	EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4399 	EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4400 	EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4401 
4402 	raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4403 	raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4404 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
4405 		raw_inode->i_file_acl_high =
4406 			cpu_to_le16(ei->i_file_acl >> 32);
4407 	raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4408 	ext4_isize_set(raw_inode, ei->i_disksize);
4409 
4410 	raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4411 	if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4412 		if (old_valid_dev(inode->i_rdev)) {
4413 			raw_inode->i_block[0] =
4414 				cpu_to_le32(old_encode_dev(inode->i_rdev));
4415 			raw_inode->i_block[1] = 0;
4416 		} else {
4417 			raw_inode->i_block[0] = 0;
4418 			raw_inode->i_block[1] =
4419 				cpu_to_le32(new_encode_dev(inode->i_rdev));
4420 			raw_inode->i_block[2] = 0;
4421 		}
4422 	} else if (!ext4_has_inline_data(inode)) {
4423 		for (block = 0; block < EXT4_N_BLOCKS; block++)
4424 			raw_inode->i_block[block] = ei->i_data[block];
4425 	}
4426 
4427 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4428 		u64 ivers = ext4_inode_peek_iversion(inode);
4429 
4430 		raw_inode->i_disk_version = cpu_to_le32(ivers);
4431 		if (ei->i_extra_isize) {
4432 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4433 				raw_inode->i_version_hi =
4434 					cpu_to_le32(ivers >> 32);
4435 			raw_inode->i_extra_isize =
4436 				cpu_to_le16(ei->i_extra_isize);
4437 		}
4438 	}
4439 
4440 	if (i_projid != EXT4_DEF_PROJID &&
4441 	    !ext4_has_feature_project(inode->i_sb))
4442 		err = err ?: -EFSCORRUPTED;
4443 
4444 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4445 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4446 		raw_inode->i_projid = cpu_to_le32(i_projid);
4447 
4448 	ext4_inode_csum_set(inode, raw_inode, ei);
4449 	return err;
4450 }
4451 
4452 /*
4453  * ext4_get_inode_loc returns with an extra refcount against the inode's
4454  * underlying buffer_head on success. If we pass 'inode' and it does not
4455  * have in-inode xattr, we have all inode data in memory that is needed
4456  * to recreate the on-disk version of this inode.
4457  */
__ext4_get_inode_loc(struct super_block * sb,unsigned long ino,struct inode * inode,struct ext4_iloc * iloc,ext4_fsblk_t * ret_block)4458 static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino,
4459 				struct inode *inode, struct ext4_iloc *iloc,
4460 				ext4_fsblk_t *ret_block)
4461 {
4462 	struct ext4_group_desc	*gdp;
4463 	struct buffer_head	*bh;
4464 	ext4_fsblk_t		block;
4465 	struct blk_plug		plug;
4466 	int			inodes_per_block, inode_offset;
4467 
4468 	iloc->bh = NULL;
4469 	if (ino < EXT4_ROOT_INO ||
4470 	    ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
4471 		return -EFSCORRUPTED;
4472 
4473 	iloc->block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
4474 	gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4475 	if (!gdp)
4476 		return -EIO;
4477 
4478 	/*
4479 	 * Figure out the offset within the block group inode table
4480 	 */
4481 	inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4482 	inode_offset = ((ino - 1) %
4483 			EXT4_INODES_PER_GROUP(sb));
4484 	iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4485 
4486 	block = ext4_inode_table(sb, gdp);
4487 	if ((block <= le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block)) ||
4488 	    (block >= ext4_blocks_count(EXT4_SB(sb)->s_es))) {
4489 		ext4_error(sb, "Invalid inode table block %llu in "
4490 			   "block_group %u", block, iloc->block_group);
4491 		return -EFSCORRUPTED;
4492 	}
4493 	block += (inode_offset / inodes_per_block);
4494 
4495 	bh = sb_getblk(sb, block);
4496 	if (unlikely(!bh))
4497 		return -ENOMEM;
4498 	if (ext4_buffer_uptodate(bh))
4499 		goto has_buffer;
4500 
4501 	lock_buffer(bh);
4502 	if (ext4_buffer_uptodate(bh)) {
4503 		/* Someone brought it uptodate while we waited */
4504 		unlock_buffer(bh);
4505 		goto has_buffer;
4506 	}
4507 
4508 	/*
4509 	 * If we have all information of the inode in memory and this
4510 	 * is the only valid inode in the block, we need not read the
4511 	 * block.
4512 	 */
4513 	if (inode && !ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
4514 		struct buffer_head *bitmap_bh;
4515 		int i, start;
4516 
4517 		start = inode_offset & ~(inodes_per_block - 1);
4518 
4519 		/* Is the inode bitmap in cache? */
4520 		bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4521 		if (unlikely(!bitmap_bh))
4522 			goto make_io;
4523 
4524 		/*
4525 		 * If the inode bitmap isn't in cache then the
4526 		 * optimisation may end up performing two reads instead
4527 		 * of one, so skip it.
4528 		 */
4529 		if (!buffer_uptodate(bitmap_bh)) {
4530 			brelse(bitmap_bh);
4531 			goto make_io;
4532 		}
4533 		for (i = start; i < start + inodes_per_block; i++) {
4534 			if (i == inode_offset)
4535 				continue;
4536 			if (ext4_test_bit(i, bitmap_bh->b_data))
4537 				break;
4538 		}
4539 		brelse(bitmap_bh);
4540 		if (i == start + inodes_per_block) {
4541 			struct ext4_inode *raw_inode =
4542 				(struct ext4_inode *) (bh->b_data + iloc->offset);
4543 
4544 			/* all other inodes are free, so skip I/O */
4545 			memset(bh->b_data, 0, bh->b_size);
4546 			if (!ext4_test_inode_state(inode, EXT4_STATE_NEW))
4547 				ext4_fill_raw_inode(inode, raw_inode);
4548 			set_buffer_uptodate(bh);
4549 			unlock_buffer(bh);
4550 			goto has_buffer;
4551 		}
4552 	}
4553 
4554 make_io:
4555 	/*
4556 	 * If we need to do any I/O, try to pre-readahead extra
4557 	 * blocks from the inode table.
4558 	 */
4559 	blk_start_plug(&plug);
4560 	if (EXT4_SB(sb)->s_inode_readahead_blks) {
4561 		ext4_fsblk_t b, end, table;
4562 		unsigned num;
4563 		__u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4564 
4565 		table = ext4_inode_table(sb, gdp);
4566 		/* s_inode_readahead_blks is always a power of 2 */
4567 		b = block & ~((ext4_fsblk_t) ra_blks - 1);
4568 		if (table > b)
4569 			b = table;
4570 		end = b + ra_blks;
4571 		num = EXT4_INODES_PER_GROUP(sb);
4572 		if (ext4_has_group_desc_csum(sb))
4573 			num -= ext4_itable_unused_count(sb, gdp);
4574 		table += num / inodes_per_block;
4575 		if (end > table)
4576 			end = table;
4577 		while (b <= end)
4578 			ext4_sb_breadahead_unmovable(sb, b++);
4579 	}
4580 
4581 	/*
4582 	 * There are other valid inodes in the buffer, this inode
4583 	 * has in-inode xattrs, or we don't have this inode in memory.
4584 	 * Read the block from disk.
4585 	 */
4586 	trace_ext4_load_inode(sb, ino);
4587 	ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO, NULL);
4588 	blk_finish_plug(&plug);
4589 	wait_on_buffer(bh);
4590 	ext4_simulate_fail_bh(sb, bh, EXT4_SIM_INODE_EIO);
4591 	if (!buffer_uptodate(bh)) {
4592 		if (ret_block)
4593 			*ret_block = block;
4594 		brelse(bh);
4595 		return -EIO;
4596 	}
4597 has_buffer:
4598 	iloc->bh = bh;
4599 	return 0;
4600 }
4601 
__ext4_get_inode_loc_noinmem(struct inode * inode,struct ext4_iloc * iloc)4602 static int __ext4_get_inode_loc_noinmem(struct inode *inode,
4603 					struct ext4_iloc *iloc)
4604 {
4605 	ext4_fsblk_t err_blk = 0;
4606 	int ret;
4607 
4608 	ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, NULL, iloc,
4609 					&err_blk);
4610 
4611 	if (ret == -EIO)
4612 		ext4_error_inode_block(inode, err_blk, EIO,
4613 					"unable to read itable block");
4614 
4615 	return ret;
4616 }
4617 
ext4_get_inode_loc(struct inode * inode,struct ext4_iloc * iloc)4618 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4619 {
4620 	ext4_fsblk_t err_blk = 0;
4621 	int ret;
4622 
4623 	ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, inode, iloc,
4624 					&err_blk);
4625 
4626 	if (ret == -EIO)
4627 		ext4_error_inode_block(inode, err_blk, EIO,
4628 					"unable to read itable block");
4629 
4630 	return ret;
4631 }
4632 
4633 
ext4_get_fc_inode_loc(struct super_block * sb,unsigned long ino,struct ext4_iloc * iloc)4634 int ext4_get_fc_inode_loc(struct super_block *sb, unsigned long ino,
4635 			  struct ext4_iloc *iloc)
4636 {
4637 	return __ext4_get_inode_loc(sb, ino, NULL, iloc, NULL);
4638 }
4639 
ext4_should_enable_dax(struct inode * inode)4640 static bool ext4_should_enable_dax(struct inode *inode)
4641 {
4642 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4643 
4644 	if (test_opt2(inode->i_sb, DAX_NEVER))
4645 		return false;
4646 	if (!S_ISREG(inode->i_mode))
4647 		return false;
4648 	if (ext4_should_journal_data(inode))
4649 		return false;
4650 	if (ext4_has_inline_data(inode))
4651 		return false;
4652 	if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT))
4653 		return false;
4654 	if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY))
4655 		return false;
4656 	if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags))
4657 		return false;
4658 	if (test_opt(inode->i_sb, DAX_ALWAYS))
4659 		return true;
4660 
4661 	return ext4_test_inode_flag(inode, EXT4_INODE_DAX);
4662 }
4663 
ext4_set_inode_flags(struct inode * inode,bool init)4664 void ext4_set_inode_flags(struct inode *inode, bool init)
4665 {
4666 	unsigned int flags = EXT4_I(inode)->i_flags;
4667 	unsigned int new_fl = 0;
4668 
4669 	WARN_ON_ONCE(IS_DAX(inode) && init);
4670 
4671 	if (flags & EXT4_SYNC_FL)
4672 		new_fl |= S_SYNC;
4673 	if (flags & EXT4_APPEND_FL)
4674 		new_fl |= S_APPEND;
4675 	if (flags & EXT4_IMMUTABLE_FL)
4676 		new_fl |= S_IMMUTABLE;
4677 	if (flags & EXT4_NOATIME_FL)
4678 		new_fl |= S_NOATIME;
4679 	if (flags & EXT4_DIRSYNC_FL)
4680 		new_fl |= S_DIRSYNC;
4681 
4682 	/* Because of the way inode_set_flags() works we must preserve S_DAX
4683 	 * here if already set. */
4684 	new_fl |= (inode->i_flags & S_DAX);
4685 	if (init && ext4_should_enable_dax(inode))
4686 		new_fl |= S_DAX;
4687 
4688 	if (flags & EXT4_ENCRYPT_FL)
4689 		new_fl |= S_ENCRYPTED;
4690 	if (flags & EXT4_CASEFOLD_FL)
4691 		new_fl |= S_CASEFOLD;
4692 	if (flags & EXT4_VERITY_FL)
4693 		new_fl |= S_VERITY;
4694 	inode_set_flags(inode, new_fl,
4695 			S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX|
4696 			S_ENCRYPTED|S_CASEFOLD|S_VERITY);
4697 }
4698 
ext4_inode_blocks(struct ext4_inode * raw_inode,struct ext4_inode_info * ei)4699 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4700 				  struct ext4_inode_info *ei)
4701 {
4702 	blkcnt_t i_blocks ;
4703 	struct inode *inode = &(ei->vfs_inode);
4704 	struct super_block *sb = inode->i_sb;
4705 
4706 	if (ext4_has_feature_huge_file(sb)) {
4707 		/* we are using combined 48 bit field */
4708 		i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4709 					le32_to_cpu(raw_inode->i_blocks_lo);
4710 		if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
4711 			/* i_blocks represent file system block size */
4712 			return i_blocks  << (inode->i_blkbits - 9);
4713 		} else {
4714 			return i_blocks;
4715 		}
4716 	} else {
4717 		return le32_to_cpu(raw_inode->i_blocks_lo);
4718 	}
4719 }
4720 
ext4_iget_extra_inode(struct inode * inode,struct ext4_inode * raw_inode,struct ext4_inode_info * ei)4721 static inline int ext4_iget_extra_inode(struct inode *inode,
4722 					 struct ext4_inode *raw_inode,
4723 					 struct ext4_inode_info *ei)
4724 {
4725 	__le32 *magic = (void *)raw_inode +
4726 			EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4727 
4728 	if (EXT4_INODE_HAS_XATTR_SPACE(inode)  &&
4729 	    *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4730 		ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4731 		return ext4_find_inline_data_nolock(inode);
4732 	} else
4733 		EXT4_I(inode)->i_inline_off = 0;
4734 	return 0;
4735 }
4736 
ext4_get_projid(struct inode * inode,kprojid_t * projid)4737 int ext4_get_projid(struct inode *inode, kprojid_t *projid)
4738 {
4739 	if (!ext4_has_feature_project(inode->i_sb))
4740 		return -EOPNOTSUPP;
4741 	*projid = EXT4_I(inode)->i_projid;
4742 	return 0;
4743 }
4744 
4745 /*
4746  * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of
4747  * refcount in i_version, so use raw values if inode has EXT4_EA_INODE_FL flag
4748  * set.
4749  */
ext4_inode_set_iversion_queried(struct inode * inode,u64 val)4750 static inline void ext4_inode_set_iversion_queried(struct inode *inode, u64 val)
4751 {
4752 	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4753 		inode_set_iversion_raw(inode, val);
4754 	else
4755 		inode_set_iversion_queried(inode, val);
4756 }
4757 
__ext4_iget(struct super_block * sb,unsigned long ino,ext4_iget_flags flags,const char * function,unsigned int line)4758 struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
4759 			  ext4_iget_flags flags, const char *function,
4760 			  unsigned int line)
4761 {
4762 	struct ext4_iloc iloc;
4763 	struct ext4_inode *raw_inode;
4764 	struct ext4_inode_info *ei;
4765 	struct ext4_super_block *es = EXT4_SB(sb)->s_es;
4766 	struct inode *inode;
4767 	journal_t *journal = EXT4_SB(sb)->s_journal;
4768 	long ret;
4769 	loff_t size;
4770 	int block;
4771 	uid_t i_uid;
4772 	gid_t i_gid;
4773 	projid_t i_projid;
4774 
4775 	if ((!(flags & EXT4_IGET_SPECIAL) &&
4776 	     ((ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO) ||
4777 	      ino == le32_to_cpu(es->s_usr_quota_inum) ||
4778 	      ino == le32_to_cpu(es->s_grp_quota_inum) ||
4779 	      ino == le32_to_cpu(es->s_prj_quota_inum) ||
4780 	      ino == le32_to_cpu(es->s_orphan_file_inum))) ||
4781 	    (ino < EXT4_ROOT_INO) ||
4782 	    (ino > le32_to_cpu(es->s_inodes_count))) {
4783 		if (flags & EXT4_IGET_HANDLE)
4784 			return ERR_PTR(-ESTALE);
4785 		__ext4_error(sb, function, line, false, EFSCORRUPTED, 0,
4786 			     "inode #%lu: comm %s: iget: illegal inode #",
4787 			     ino, current->comm);
4788 		return ERR_PTR(-EFSCORRUPTED);
4789 	}
4790 
4791 	inode = iget_locked(sb, ino);
4792 	if (!inode)
4793 		return ERR_PTR(-ENOMEM);
4794 	if (!(inode->i_state & I_NEW))
4795 		return inode;
4796 
4797 	ei = EXT4_I(inode);
4798 	iloc.bh = NULL;
4799 
4800 	ret = __ext4_get_inode_loc_noinmem(inode, &iloc);
4801 	if (ret < 0)
4802 		goto bad_inode;
4803 	raw_inode = ext4_raw_inode(&iloc);
4804 
4805 	if ((ino == EXT4_ROOT_INO) && (raw_inode->i_links_count == 0)) {
4806 		ext4_error_inode(inode, function, line, 0,
4807 				 "iget: root inode unallocated");
4808 		ret = -EFSCORRUPTED;
4809 		goto bad_inode;
4810 	}
4811 
4812 	if ((flags & EXT4_IGET_HANDLE) &&
4813 	    (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
4814 		ret = -ESTALE;
4815 		goto bad_inode;
4816 	}
4817 
4818 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4819 		ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4820 		if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4821 			EXT4_INODE_SIZE(inode->i_sb) ||
4822 		    (ei->i_extra_isize & 3)) {
4823 			ext4_error_inode(inode, function, line, 0,
4824 					 "iget: bad extra_isize %u "
4825 					 "(inode size %u)",
4826 					 ei->i_extra_isize,
4827 					 EXT4_INODE_SIZE(inode->i_sb));
4828 			ret = -EFSCORRUPTED;
4829 			goto bad_inode;
4830 		}
4831 	} else
4832 		ei->i_extra_isize = 0;
4833 
4834 	/* Precompute checksum seed for inode metadata */
4835 	if (ext4_has_metadata_csum(sb)) {
4836 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4837 		__u32 csum;
4838 		__le32 inum = cpu_to_le32(inode->i_ino);
4839 		__le32 gen = raw_inode->i_generation;
4840 		csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4841 				   sizeof(inum));
4842 		ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4843 					      sizeof(gen));
4844 	}
4845 
4846 	if ((!ext4_inode_csum_verify(inode, raw_inode, ei) ||
4847 	    ext4_simulate_fail(sb, EXT4_SIM_INODE_CRC)) &&
4848 	     (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY))) {
4849 		ext4_error_inode_err(inode, function, line, 0,
4850 				EFSBADCRC, "iget: checksum invalid");
4851 		ret = -EFSBADCRC;
4852 		goto bad_inode;
4853 	}
4854 
4855 	inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4856 	i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4857 	i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4858 	if (ext4_has_feature_project(sb) &&
4859 	    EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4860 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4861 		i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
4862 	else
4863 		i_projid = EXT4_DEF_PROJID;
4864 
4865 	if (!(test_opt(inode->i_sb, NO_UID32))) {
4866 		i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4867 		i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4868 	}
4869 	i_uid_write(inode, i_uid);
4870 	i_gid_write(inode, i_gid);
4871 	ei->i_projid = make_kprojid(&init_user_ns, i_projid);
4872 	set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4873 
4874 	ext4_clear_state_flags(ei);	/* Only relevant on 32-bit archs */
4875 	ei->i_inline_off = 0;
4876 	ei->i_dir_start_lookup = 0;
4877 	ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4878 	/* We now have enough fields to check if the inode was active or not.
4879 	 * This is needed because nfsd might try to access dead inodes
4880 	 * the test is that same one that e2fsck uses
4881 	 * NeilBrown 1999oct15
4882 	 */
4883 	if (inode->i_nlink == 0) {
4884 		if ((inode->i_mode == 0 ||
4885 		     !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4886 		    ino != EXT4_BOOT_LOADER_INO) {
4887 			/* this inode is deleted */
4888 			ret = -ESTALE;
4889 			goto bad_inode;
4890 		}
4891 		/* The only unlinked inodes we let through here have
4892 		 * valid i_mode and are being read by the orphan
4893 		 * recovery code: that's fine, we're about to complete
4894 		 * the process of deleting those.
4895 		 * OR it is the EXT4_BOOT_LOADER_INO which is
4896 		 * not initialized on a new filesystem. */
4897 	}
4898 	ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4899 	ext4_set_inode_flags(inode, true);
4900 	inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4901 	ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4902 	if (ext4_has_feature_64bit(sb))
4903 		ei->i_file_acl |=
4904 			((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4905 	inode->i_size = ext4_isize(sb, raw_inode);
4906 	if ((size = i_size_read(inode)) < 0) {
4907 		ext4_error_inode(inode, function, line, 0,
4908 				 "iget: bad i_size value: %lld", size);
4909 		ret = -EFSCORRUPTED;
4910 		goto bad_inode;
4911 	}
4912 	/*
4913 	 * If dir_index is not enabled but there's dir with INDEX flag set,
4914 	 * we'd normally treat htree data as empty space. But with metadata
4915 	 * checksumming that corrupts checksums so forbid that.
4916 	 */
4917 	if (!ext4_has_feature_dir_index(sb) && ext4_has_metadata_csum(sb) &&
4918 	    ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
4919 		ext4_error_inode(inode, function, line, 0,
4920 			 "iget: Dir with htree data on filesystem without dir_index feature.");
4921 		ret = -EFSCORRUPTED;
4922 		goto bad_inode;
4923 	}
4924 	ei->i_disksize = inode->i_size;
4925 #ifdef CONFIG_QUOTA
4926 	ei->i_reserved_quota = 0;
4927 #endif
4928 	inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4929 	ei->i_block_group = iloc.block_group;
4930 	ei->i_last_alloc_group = ~0;
4931 	/*
4932 	 * NOTE! The in-memory inode i_data array is in little-endian order
4933 	 * even on big-endian machines: we do NOT byteswap the block numbers!
4934 	 */
4935 	for (block = 0; block < EXT4_N_BLOCKS; block++)
4936 		ei->i_data[block] = raw_inode->i_block[block];
4937 	INIT_LIST_HEAD(&ei->i_orphan);
4938 	ext4_fc_init_inode(&ei->vfs_inode);
4939 
4940 	/*
4941 	 * Set transaction id's of transactions that have to be committed
4942 	 * to finish f[data]sync. We set them to currently running transaction
4943 	 * as we cannot be sure that the inode or some of its metadata isn't
4944 	 * part of the transaction - the inode could have been reclaimed and
4945 	 * now it is reread from disk.
4946 	 */
4947 	if (journal) {
4948 		transaction_t *transaction;
4949 		tid_t tid;
4950 
4951 		read_lock(&journal->j_state_lock);
4952 		if (journal->j_running_transaction)
4953 			transaction = journal->j_running_transaction;
4954 		else
4955 			transaction = journal->j_committing_transaction;
4956 		if (transaction)
4957 			tid = transaction->t_tid;
4958 		else
4959 			tid = journal->j_commit_sequence;
4960 		read_unlock(&journal->j_state_lock);
4961 		ei->i_sync_tid = tid;
4962 		ei->i_datasync_tid = tid;
4963 	}
4964 
4965 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4966 		if (ei->i_extra_isize == 0) {
4967 			/* The extra space is currently unused. Use it. */
4968 			BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
4969 			ei->i_extra_isize = sizeof(struct ext4_inode) -
4970 					    EXT4_GOOD_OLD_INODE_SIZE;
4971 		} else {
4972 			ret = ext4_iget_extra_inode(inode, raw_inode, ei);
4973 			if (ret)
4974 				goto bad_inode;
4975 		}
4976 	}
4977 
4978 	EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4979 	EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4980 	EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4981 	EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4982 
4983 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4984 		u64 ivers = le32_to_cpu(raw_inode->i_disk_version);
4985 
4986 		if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4987 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4988 				ivers |=
4989 		    (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4990 		}
4991 		ext4_inode_set_iversion_queried(inode, ivers);
4992 	}
4993 
4994 	ret = 0;
4995 	if (ei->i_file_acl &&
4996 	    !ext4_inode_block_valid(inode, ei->i_file_acl, 1)) {
4997 		ext4_error_inode(inode, function, line, 0,
4998 				 "iget: bad extended attribute block %llu",
4999 				 ei->i_file_acl);
5000 		ret = -EFSCORRUPTED;
5001 		goto bad_inode;
5002 	} else if (!ext4_has_inline_data(inode)) {
5003 		/* validate the block references in the inode */
5004 		if (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY) &&
5005 			(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
5006 			(S_ISLNK(inode->i_mode) &&
5007 			!ext4_inode_is_fast_symlink(inode)))) {
5008 			if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
5009 				ret = ext4_ext_check_inode(inode);
5010 			else
5011 				ret = ext4_ind_check_inode(inode);
5012 		}
5013 	}
5014 	if (ret)
5015 		goto bad_inode;
5016 
5017 	if (S_ISREG(inode->i_mode)) {
5018 		inode->i_op = &ext4_file_inode_operations;
5019 		inode->i_fop = &ext4_file_operations;
5020 		ext4_set_aops(inode);
5021 	} else if (S_ISDIR(inode->i_mode)) {
5022 		inode->i_op = &ext4_dir_inode_operations;
5023 		inode->i_fop = &ext4_dir_operations;
5024 	} else if (S_ISLNK(inode->i_mode)) {
5025 		/* VFS does not allow setting these so must be corruption */
5026 		if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
5027 			ext4_error_inode(inode, function, line, 0,
5028 					 "iget: immutable or append flags "
5029 					 "not allowed on symlinks");
5030 			ret = -EFSCORRUPTED;
5031 			goto bad_inode;
5032 		}
5033 		if (IS_ENCRYPTED(inode)) {
5034 			inode->i_op = &ext4_encrypted_symlink_inode_operations;
5035 		} else if (ext4_inode_is_fast_symlink(inode)) {
5036 			inode->i_link = (char *)ei->i_data;
5037 			inode->i_op = &ext4_fast_symlink_inode_operations;
5038 			nd_terminate_link(ei->i_data, inode->i_size,
5039 				sizeof(ei->i_data) - 1);
5040 		} else {
5041 			inode->i_op = &ext4_symlink_inode_operations;
5042 		}
5043 	} else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
5044 	      S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
5045 		inode->i_op = &ext4_special_inode_operations;
5046 		if (raw_inode->i_block[0])
5047 			init_special_inode(inode, inode->i_mode,
5048 			   old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
5049 		else
5050 			init_special_inode(inode, inode->i_mode,
5051 			   new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
5052 	} else if (ino == EXT4_BOOT_LOADER_INO) {
5053 		make_bad_inode(inode);
5054 	} else {
5055 		ret = -EFSCORRUPTED;
5056 		ext4_error_inode(inode, function, line, 0,
5057 				 "iget: bogus i_mode (%o)", inode->i_mode);
5058 		goto bad_inode;
5059 	}
5060 	if (IS_CASEFOLDED(inode) && !ext4_has_feature_casefold(inode->i_sb))
5061 		ext4_error_inode(inode, function, line, 0,
5062 				 "casefold flag without casefold feature");
5063 	if (is_bad_inode(inode) && !(flags & EXT4_IGET_BAD)) {
5064 		ext4_error_inode(inode, function, line, 0,
5065 				 "bad inode without EXT4_IGET_BAD flag");
5066 		ret = -EUCLEAN;
5067 		goto bad_inode;
5068 	}
5069 
5070 	brelse(iloc.bh);
5071 	unlock_new_inode(inode);
5072 	return inode;
5073 
5074 bad_inode:
5075 	brelse(iloc.bh);
5076 	iget_failed(inode);
5077 	return ERR_PTR(ret);
5078 }
5079 
__ext4_update_other_inode_time(struct super_block * sb,unsigned long orig_ino,unsigned long ino,struct ext4_inode * raw_inode)5080 static void __ext4_update_other_inode_time(struct super_block *sb,
5081 					   unsigned long orig_ino,
5082 					   unsigned long ino,
5083 					   struct ext4_inode *raw_inode)
5084 {
5085 	struct inode *inode;
5086 
5087 	inode = find_inode_by_ino_rcu(sb, ino);
5088 	if (!inode)
5089 		return;
5090 
5091 	if (!inode_is_dirtytime_only(inode))
5092 		return;
5093 
5094 	spin_lock(&inode->i_lock);
5095 	if (inode_is_dirtytime_only(inode)) {
5096 		struct ext4_inode_info	*ei = EXT4_I(inode);
5097 
5098 		inode->i_state &= ~I_DIRTY_TIME;
5099 		spin_unlock(&inode->i_lock);
5100 
5101 		spin_lock(&ei->i_raw_lock);
5102 		EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
5103 		EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
5104 		EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
5105 		ext4_inode_csum_set(inode, raw_inode, ei);
5106 		spin_unlock(&ei->i_raw_lock);
5107 		trace_ext4_other_inode_update_time(inode, orig_ino);
5108 		return;
5109 	}
5110 	spin_unlock(&inode->i_lock);
5111 }
5112 
5113 /*
5114  * Opportunistically update the other time fields for other inodes in
5115  * the same inode table block.
5116  */
ext4_update_other_inodes_time(struct super_block * sb,unsigned long orig_ino,char * buf)5117 static void ext4_update_other_inodes_time(struct super_block *sb,
5118 					  unsigned long orig_ino, char *buf)
5119 {
5120 	unsigned long ino;
5121 	int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
5122 	int inode_size = EXT4_INODE_SIZE(sb);
5123 
5124 	/*
5125 	 * Calculate the first inode in the inode table block.  Inode
5126 	 * numbers are one-based.  That is, the first inode in a block
5127 	 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
5128 	 */
5129 	ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
5130 	rcu_read_lock();
5131 	for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
5132 		if (ino == orig_ino)
5133 			continue;
5134 		__ext4_update_other_inode_time(sb, orig_ino, ino,
5135 					       (struct ext4_inode *)buf);
5136 	}
5137 	rcu_read_unlock();
5138 }
5139 
5140 /*
5141  * Post the struct inode info into an on-disk inode location in the
5142  * buffer-cache.  This gobbles the caller's reference to the
5143  * buffer_head in the inode location struct.
5144  *
5145  * The caller must have write access to iloc->bh.
5146  */
ext4_do_update_inode(handle_t * handle,struct inode * inode,struct ext4_iloc * iloc)5147 static int ext4_do_update_inode(handle_t *handle,
5148 				struct inode *inode,
5149 				struct ext4_iloc *iloc)
5150 {
5151 	struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5152 	struct ext4_inode_info *ei = EXT4_I(inode);
5153 	struct buffer_head *bh = iloc->bh;
5154 	struct super_block *sb = inode->i_sb;
5155 	int err;
5156 	int need_datasync = 0, set_large_file = 0;
5157 
5158 	spin_lock(&ei->i_raw_lock);
5159 
5160 	/*
5161 	 * For fields not tracked in the in-memory inode, initialise them
5162 	 * to zero for new inodes.
5163 	 */
5164 	if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5165 		memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5166 
5167 	if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode))
5168 		need_datasync = 1;
5169 	if (ei->i_disksize > 0x7fffffffULL) {
5170 		if (!ext4_has_feature_large_file(sb) ||
5171 		    EXT4_SB(sb)->s_es->s_rev_level == cpu_to_le32(EXT4_GOOD_OLD_REV))
5172 			set_large_file = 1;
5173 	}
5174 
5175 	err = ext4_fill_raw_inode(inode, raw_inode);
5176 	spin_unlock(&ei->i_raw_lock);
5177 	if (err) {
5178 		EXT4_ERROR_INODE(inode, "corrupted inode contents");
5179 		goto out_brelse;
5180 	}
5181 
5182 	if (inode->i_sb->s_flags & SB_LAZYTIME)
5183 		ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5184 					      bh->b_data);
5185 
5186 	BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
5187 	err = ext4_handle_dirty_metadata(handle, NULL, bh);
5188 	if (err)
5189 		goto out_error;
5190 	ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5191 	if (set_large_file) {
5192 		BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
5193 		err = ext4_journal_get_write_access(handle, sb,
5194 						    EXT4_SB(sb)->s_sbh,
5195 						    EXT4_JTR_NONE);
5196 		if (err)
5197 			goto out_error;
5198 		lock_buffer(EXT4_SB(sb)->s_sbh);
5199 		ext4_set_feature_large_file(sb);
5200 		ext4_superblock_csum_set(sb);
5201 		unlock_buffer(EXT4_SB(sb)->s_sbh);
5202 		ext4_handle_sync(handle);
5203 		err = ext4_handle_dirty_metadata(handle, NULL,
5204 						 EXT4_SB(sb)->s_sbh);
5205 	}
5206 	ext4_update_inode_fsync_trans(handle, inode, need_datasync);
5207 out_error:
5208 	ext4_std_error(inode->i_sb, err);
5209 out_brelse:
5210 	brelse(bh);
5211 	return err;
5212 }
5213 
5214 /*
5215  * ext4_write_inode()
5216  *
5217  * We are called from a few places:
5218  *
5219  * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
5220  *   Here, there will be no transaction running. We wait for any running
5221  *   transaction to commit.
5222  *
5223  * - Within flush work (sys_sync(), kupdate and such).
5224  *   We wait on commit, if told to.
5225  *
5226  * - Within iput_final() -> write_inode_now()
5227  *   We wait on commit, if told to.
5228  *
5229  * In all cases it is actually safe for us to return without doing anything,
5230  * because the inode has been copied into a raw inode buffer in
5231  * ext4_mark_inode_dirty().  This is a correctness thing for WB_SYNC_ALL
5232  * writeback.
5233  *
5234  * Note that we are absolutely dependent upon all inode dirtiers doing the
5235  * right thing: they *must* call mark_inode_dirty() after dirtying info in
5236  * which we are interested.
5237  *
5238  * It would be a bug for them to not do this.  The code:
5239  *
5240  *	mark_inode_dirty(inode)
5241  *	stuff();
5242  *	inode->i_size = expr;
5243  *
5244  * is in error because write_inode() could occur while `stuff()' is running,
5245  * and the new i_size will be lost.  Plus the inode will no longer be on the
5246  * superblock's dirty inode list.
5247  */
ext4_write_inode(struct inode * inode,struct writeback_control * wbc)5248 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5249 {
5250 	int err;
5251 
5252 	if (WARN_ON_ONCE(current->flags & PF_MEMALLOC) ||
5253 	    sb_rdonly(inode->i_sb))
5254 		return 0;
5255 
5256 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5257 		return -EIO;
5258 
5259 	if (EXT4_SB(inode->i_sb)->s_journal) {
5260 		if (ext4_journal_current_handle()) {
5261 			ext4_debug("called recursively, non-PF_MEMALLOC!\n");
5262 			dump_stack();
5263 			return -EIO;
5264 		}
5265 
5266 		/*
5267 		 * No need to force transaction in WB_SYNC_NONE mode. Also
5268 		 * ext4_sync_fs() will force the commit after everything is
5269 		 * written.
5270 		 */
5271 		if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
5272 			return 0;
5273 
5274 		err = ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal,
5275 						EXT4_I(inode)->i_sync_tid);
5276 	} else {
5277 		struct ext4_iloc iloc;
5278 
5279 		err = __ext4_get_inode_loc_noinmem(inode, &iloc);
5280 		if (err)
5281 			return err;
5282 		/*
5283 		 * sync(2) will flush the whole buffer cache. No need to do
5284 		 * it here separately for each inode.
5285 		 */
5286 		if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
5287 			sync_dirty_buffer(iloc.bh);
5288 		if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
5289 			ext4_error_inode_block(inode, iloc.bh->b_blocknr, EIO,
5290 					       "IO error syncing inode");
5291 			err = -EIO;
5292 		}
5293 		brelse(iloc.bh);
5294 	}
5295 	return err;
5296 }
5297 
5298 /*
5299  * In data=journal mode ext4_journalled_invalidate_folio() may fail to invalidate
5300  * buffers that are attached to a folio straddling i_size and are undergoing
5301  * commit. In that case we have to wait for commit to finish and try again.
5302  */
ext4_wait_for_tail_page_commit(struct inode * inode)5303 static void ext4_wait_for_tail_page_commit(struct inode *inode)
5304 {
5305 	unsigned offset;
5306 	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
5307 	tid_t commit_tid = 0;
5308 	int ret;
5309 
5310 	offset = inode->i_size & (PAGE_SIZE - 1);
5311 	/*
5312 	 * If the folio is fully truncated, we don't need to wait for any commit
5313 	 * (and we even should not as __ext4_journalled_invalidate_folio() may
5314 	 * strip all buffers from the folio but keep the folio dirty which can then
5315 	 * confuse e.g. concurrent ext4_writepage() seeing dirty folio without
5316 	 * buffers). Also we don't need to wait for any commit if all buffers in
5317 	 * the folio remain valid. This is most beneficial for the common case of
5318 	 * blocksize == PAGESIZE.
5319 	 */
5320 	if (!offset || offset > (PAGE_SIZE - i_blocksize(inode)))
5321 		return;
5322 	while (1) {
5323 		struct folio *folio = filemap_lock_folio(inode->i_mapping,
5324 				      inode->i_size >> PAGE_SHIFT);
5325 		if (!folio)
5326 			return;
5327 		ret = __ext4_journalled_invalidate_folio(folio, offset,
5328 						folio_size(folio) - offset);
5329 		folio_unlock(folio);
5330 		folio_put(folio);
5331 		if (ret != -EBUSY)
5332 			return;
5333 		commit_tid = 0;
5334 		read_lock(&journal->j_state_lock);
5335 		if (journal->j_committing_transaction)
5336 			commit_tid = journal->j_committing_transaction->t_tid;
5337 		read_unlock(&journal->j_state_lock);
5338 		if (commit_tid)
5339 			jbd2_log_wait_commit(journal, commit_tid);
5340 	}
5341 }
5342 
5343 /*
5344  * ext4_setattr()
5345  *
5346  * Called from notify_change.
5347  *
5348  * We want to trap VFS attempts to truncate the file as soon as
5349  * possible.  In particular, we want to make sure that when the VFS
5350  * shrinks i_size, we put the inode on the orphan list and modify
5351  * i_disksize immediately, so that during the subsequent flushing of
5352  * dirty pages and freeing of disk blocks, we can guarantee that any
5353  * commit will leave the blocks being flushed in an unused state on
5354  * disk.  (On recovery, the inode will get truncated and the blocks will
5355  * be freed, so we have a strong guarantee that no future commit will
5356  * leave these blocks visible to the user.)
5357  *
5358  * Another thing we have to assure is that if we are in ordered mode
5359  * and inode is still attached to the committing transaction, we must
5360  * we start writeout of all the dirty pages which are being truncated.
5361  * This way we are sure that all the data written in the previous
5362  * transaction are already on disk (truncate waits for pages under
5363  * writeback).
5364  *
5365  * Called with inode->i_rwsem down.
5366  */
ext4_setattr(struct user_namespace * mnt_userns,struct dentry * dentry,struct iattr * attr)5367 int ext4_setattr(struct user_namespace *mnt_userns, struct dentry *dentry,
5368 		 struct iattr *attr)
5369 {
5370 	struct inode *inode = d_inode(dentry);
5371 	int error, rc = 0;
5372 	int orphan = 0;
5373 	const unsigned int ia_valid = attr->ia_valid;
5374 	bool inc_ivers = true;
5375 
5376 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5377 		return -EIO;
5378 
5379 	if (unlikely(IS_IMMUTABLE(inode)))
5380 		return -EPERM;
5381 
5382 	if (unlikely(IS_APPEND(inode) &&
5383 		     (ia_valid & (ATTR_MODE | ATTR_UID |
5384 				  ATTR_GID | ATTR_TIMES_SET))))
5385 		return -EPERM;
5386 
5387 	error = setattr_prepare(mnt_userns, dentry, attr);
5388 	if (error)
5389 		return error;
5390 
5391 	error = fscrypt_prepare_setattr(dentry, attr);
5392 	if (error)
5393 		return error;
5394 
5395 	error = fsverity_prepare_setattr(dentry, attr);
5396 	if (error)
5397 		return error;
5398 
5399 	if (is_quota_modification(mnt_userns, inode, attr)) {
5400 		error = dquot_initialize(inode);
5401 		if (error)
5402 			return error;
5403 	}
5404 
5405 	if (i_uid_needs_update(mnt_userns, attr, inode) ||
5406 	    i_gid_needs_update(mnt_userns, attr, inode)) {
5407 		handle_t *handle;
5408 
5409 		/* (user+group)*(old+new) structure, inode write (sb,
5410 		 * inode block, ? - but truncate inode update has it) */
5411 		handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
5412 			(EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5413 			 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
5414 		if (IS_ERR(handle)) {
5415 			error = PTR_ERR(handle);
5416 			goto err_out;
5417 		}
5418 
5419 		/* dquot_transfer() calls back ext4_get_inode_usage() which
5420 		 * counts xattr inode references.
5421 		 */
5422 		down_read(&EXT4_I(inode)->xattr_sem);
5423 		error = dquot_transfer(mnt_userns, inode, attr);
5424 		up_read(&EXT4_I(inode)->xattr_sem);
5425 
5426 		if (error) {
5427 			ext4_journal_stop(handle);
5428 			return error;
5429 		}
5430 		/* Update corresponding info in inode so that everything is in
5431 		 * one transaction */
5432 		i_uid_update(mnt_userns, attr, inode);
5433 		i_gid_update(mnt_userns, attr, inode);
5434 		error = ext4_mark_inode_dirty(handle, inode);
5435 		ext4_journal_stop(handle);
5436 		if (unlikely(error)) {
5437 			return error;
5438 		}
5439 	}
5440 
5441 	if (attr->ia_valid & ATTR_SIZE) {
5442 		handle_t *handle;
5443 		loff_t oldsize = inode->i_size;
5444 		loff_t old_disksize;
5445 		int shrink = (attr->ia_size < inode->i_size);
5446 
5447 		if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5448 			struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5449 
5450 			if (attr->ia_size > sbi->s_bitmap_maxbytes) {
5451 				return -EFBIG;
5452 			}
5453 		}
5454 		if (!S_ISREG(inode->i_mode)) {
5455 			return -EINVAL;
5456 		}
5457 
5458 		if (attr->ia_size == inode->i_size)
5459 			inc_ivers = false;
5460 
5461 		if (shrink) {
5462 			if (ext4_should_order_data(inode)) {
5463 				error = ext4_begin_ordered_truncate(inode,
5464 							    attr->ia_size);
5465 				if (error)
5466 					goto err_out;
5467 			}
5468 			/*
5469 			 * Blocks are going to be removed from the inode. Wait
5470 			 * for dio in flight.
5471 			 */
5472 			inode_dio_wait(inode);
5473 		}
5474 
5475 		filemap_invalidate_lock(inode->i_mapping);
5476 
5477 		rc = ext4_break_layouts(inode);
5478 		if (rc) {
5479 			filemap_invalidate_unlock(inode->i_mapping);
5480 			goto err_out;
5481 		}
5482 
5483 		if (attr->ia_size != inode->i_size) {
5484 			handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5485 			if (IS_ERR(handle)) {
5486 				error = PTR_ERR(handle);
5487 				goto out_mmap_sem;
5488 			}
5489 			if (ext4_handle_valid(handle) && shrink) {
5490 				error = ext4_orphan_add(handle, inode);
5491 				orphan = 1;
5492 			}
5493 			/*
5494 			 * Update c/mtime on truncate up, ext4_truncate() will
5495 			 * update c/mtime in shrink case below
5496 			 */
5497 			if (!shrink) {
5498 				inode->i_mtime = current_time(inode);
5499 				inode->i_ctime = inode->i_mtime;
5500 			}
5501 
5502 			if (shrink)
5503 				ext4_fc_track_range(handle, inode,
5504 					(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5505 					inode->i_sb->s_blocksize_bits,
5506 					EXT_MAX_BLOCKS - 1);
5507 			else
5508 				ext4_fc_track_range(
5509 					handle, inode,
5510 					(oldsize > 0 ? oldsize - 1 : oldsize) >>
5511 					inode->i_sb->s_blocksize_bits,
5512 					(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5513 					inode->i_sb->s_blocksize_bits);
5514 
5515 			down_write(&EXT4_I(inode)->i_data_sem);
5516 			old_disksize = EXT4_I(inode)->i_disksize;
5517 			EXT4_I(inode)->i_disksize = attr->ia_size;
5518 			rc = ext4_mark_inode_dirty(handle, inode);
5519 			if (!error)
5520 				error = rc;
5521 			/*
5522 			 * We have to update i_size under i_data_sem together
5523 			 * with i_disksize to avoid races with writeback code
5524 			 * running ext4_wb_update_i_disksize().
5525 			 */
5526 			if (!error)
5527 				i_size_write(inode, attr->ia_size);
5528 			else
5529 				EXT4_I(inode)->i_disksize = old_disksize;
5530 			up_write(&EXT4_I(inode)->i_data_sem);
5531 			ext4_journal_stop(handle);
5532 			if (error)
5533 				goto out_mmap_sem;
5534 			if (!shrink) {
5535 				pagecache_isize_extended(inode, oldsize,
5536 							 inode->i_size);
5537 			} else if (ext4_should_journal_data(inode)) {
5538 				ext4_wait_for_tail_page_commit(inode);
5539 			}
5540 		}
5541 
5542 		/*
5543 		 * Truncate pagecache after we've waited for commit
5544 		 * in data=journal mode to make pages freeable.
5545 		 */
5546 		truncate_pagecache(inode, inode->i_size);
5547 		/*
5548 		 * Call ext4_truncate() even if i_size didn't change to
5549 		 * truncate possible preallocated blocks.
5550 		 */
5551 		if (attr->ia_size <= oldsize) {
5552 			rc = ext4_truncate(inode);
5553 			if (rc)
5554 				error = rc;
5555 		}
5556 out_mmap_sem:
5557 		filemap_invalidate_unlock(inode->i_mapping);
5558 	}
5559 
5560 	if (!error) {
5561 		if (inc_ivers)
5562 			inode_inc_iversion(inode);
5563 		setattr_copy(mnt_userns, inode, attr);
5564 		mark_inode_dirty(inode);
5565 	}
5566 
5567 	/*
5568 	 * If the call to ext4_truncate failed to get a transaction handle at
5569 	 * all, we need to clean up the in-core orphan list manually.
5570 	 */
5571 	if (orphan && inode->i_nlink)
5572 		ext4_orphan_del(NULL, inode);
5573 
5574 	if (!error && (ia_valid & ATTR_MODE))
5575 		rc = posix_acl_chmod(mnt_userns, inode, inode->i_mode);
5576 
5577 err_out:
5578 	if  (error)
5579 		ext4_std_error(inode->i_sb, error);
5580 	if (!error)
5581 		error = rc;
5582 	return error;
5583 }
5584 
ext4_dio_alignment(struct inode * inode)5585 u32 ext4_dio_alignment(struct inode *inode)
5586 {
5587 	if (fsverity_active(inode))
5588 		return 0;
5589 	if (ext4_should_journal_data(inode))
5590 		return 0;
5591 	if (ext4_has_inline_data(inode))
5592 		return 0;
5593 	if (IS_ENCRYPTED(inode)) {
5594 		if (!fscrypt_dio_supported(inode))
5595 			return 0;
5596 		return i_blocksize(inode);
5597 	}
5598 	return 1; /* use the iomap defaults */
5599 }
5600 
ext4_getattr(struct user_namespace * mnt_userns,const struct path * path,struct kstat * stat,u32 request_mask,unsigned int query_flags)5601 int ext4_getattr(struct user_namespace *mnt_userns, const struct path *path,
5602 		 struct kstat *stat, u32 request_mask, unsigned int query_flags)
5603 {
5604 	struct inode *inode = d_inode(path->dentry);
5605 	struct ext4_inode *raw_inode;
5606 	struct ext4_inode_info *ei = EXT4_I(inode);
5607 	unsigned int flags;
5608 
5609 	if ((request_mask & STATX_BTIME) &&
5610 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
5611 		stat->result_mask |= STATX_BTIME;
5612 		stat->btime.tv_sec = ei->i_crtime.tv_sec;
5613 		stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
5614 	}
5615 
5616 	/*
5617 	 * Return the DIO alignment restrictions if requested.  We only return
5618 	 * this information when requested, since on encrypted files it might
5619 	 * take a fair bit of work to get if the file wasn't opened recently.
5620 	 */
5621 	if ((request_mask & STATX_DIOALIGN) && S_ISREG(inode->i_mode)) {
5622 		u32 dio_align = ext4_dio_alignment(inode);
5623 
5624 		stat->result_mask |= STATX_DIOALIGN;
5625 		if (dio_align == 1) {
5626 			struct block_device *bdev = inode->i_sb->s_bdev;
5627 
5628 			/* iomap defaults */
5629 			stat->dio_mem_align = bdev_dma_alignment(bdev) + 1;
5630 			stat->dio_offset_align = bdev_logical_block_size(bdev);
5631 		} else {
5632 			stat->dio_mem_align = dio_align;
5633 			stat->dio_offset_align = dio_align;
5634 		}
5635 	}
5636 
5637 	flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
5638 	if (flags & EXT4_APPEND_FL)
5639 		stat->attributes |= STATX_ATTR_APPEND;
5640 	if (flags & EXT4_COMPR_FL)
5641 		stat->attributes |= STATX_ATTR_COMPRESSED;
5642 	if (flags & EXT4_ENCRYPT_FL)
5643 		stat->attributes |= STATX_ATTR_ENCRYPTED;
5644 	if (flags & EXT4_IMMUTABLE_FL)
5645 		stat->attributes |= STATX_ATTR_IMMUTABLE;
5646 	if (flags & EXT4_NODUMP_FL)
5647 		stat->attributes |= STATX_ATTR_NODUMP;
5648 	if (flags & EXT4_VERITY_FL)
5649 		stat->attributes |= STATX_ATTR_VERITY;
5650 
5651 	stat->attributes_mask |= (STATX_ATTR_APPEND |
5652 				  STATX_ATTR_COMPRESSED |
5653 				  STATX_ATTR_ENCRYPTED |
5654 				  STATX_ATTR_IMMUTABLE |
5655 				  STATX_ATTR_NODUMP |
5656 				  STATX_ATTR_VERITY);
5657 
5658 	generic_fillattr(mnt_userns, inode, stat);
5659 	return 0;
5660 }
5661 
ext4_file_getattr(struct user_namespace * mnt_userns,const struct path * path,struct kstat * stat,u32 request_mask,unsigned int query_flags)5662 int ext4_file_getattr(struct user_namespace *mnt_userns,
5663 		      const struct path *path, struct kstat *stat,
5664 		      u32 request_mask, unsigned int query_flags)
5665 {
5666 	struct inode *inode = d_inode(path->dentry);
5667 	u64 delalloc_blocks;
5668 
5669 	ext4_getattr(mnt_userns, path, stat, request_mask, query_flags);
5670 
5671 	/*
5672 	 * If there is inline data in the inode, the inode will normally not
5673 	 * have data blocks allocated (it may have an external xattr block).
5674 	 * Report at least one sector for such files, so tools like tar, rsync,
5675 	 * others don't incorrectly think the file is completely sparse.
5676 	 */
5677 	if (unlikely(ext4_has_inline_data(inode)))
5678 		stat->blocks += (stat->size + 511) >> 9;
5679 
5680 	/*
5681 	 * We can't update i_blocks if the block allocation is delayed
5682 	 * otherwise in the case of system crash before the real block
5683 	 * allocation is done, we will have i_blocks inconsistent with
5684 	 * on-disk file blocks.
5685 	 * We always keep i_blocks updated together with real
5686 	 * allocation. But to not confuse with user, stat
5687 	 * will return the blocks that include the delayed allocation
5688 	 * blocks for this file.
5689 	 */
5690 	delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
5691 				   EXT4_I(inode)->i_reserved_data_blocks);
5692 	stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
5693 	return 0;
5694 }
5695 
ext4_index_trans_blocks(struct inode * inode,int lblocks,int pextents)5696 static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5697 				   int pextents)
5698 {
5699 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5700 		return ext4_ind_trans_blocks(inode, lblocks);
5701 	return ext4_ext_index_trans_blocks(inode, pextents);
5702 }
5703 
5704 /*
5705  * Account for index blocks, block groups bitmaps and block group
5706  * descriptor blocks if modify datablocks and index blocks
5707  * worse case, the indexs blocks spread over different block groups
5708  *
5709  * If datablocks are discontiguous, they are possible to spread over
5710  * different block groups too. If they are contiguous, with flexbg,
5711  * they could still across block group boundary.
5712  *
5713  * Also account for superblock, inode, quota and xattr blocks
5714  */
ext4_meta_trans_blocks(struct inode * inode,int lblocks,int pextents)5715 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5716 				  int pextents)
5717 {
5718 	ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
5719 	int gdpblocks;
5720 	int idxblocks;
5721 	int ret = 0;
5722 
5723 	/*
5724 	 * How many index blocks need to touch to map @lblocks logical blocks
5725 	 * to @pextents physical extents?
5726 	 */
5727 	idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5728 
5729 	ret = idxblocks;
5730 
5731 	/*
5732 	 * Now let's see how many group bitmaps and group descriptors need
5733 	 * to account
5734 	 */
5735 	groups = idxblocks + pextents;
5736 	gdpblocks = groups;
5737 	if (groups > ngroups)
5738 		groups = ngroups;
5739 	if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5740 		gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5741 
5742 	/* bitmaps and block group descriptor blocks */
5743 	ret += groups + gdpblocks;
5744 
5745 	/* Blocks for super block, inode, quota and xattr blocks */
5746 	ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5747 
5748 	return ret;
5749 }
5750 
5751 /*
5752  * Calculate the total number of credits to reserve to fit
5753  * the modification of a single pages into a single transaction,
5754  * which may include multiple chunks of block allocations.
5755  *
5756  * This could be called via ext4_write_begin()
5757  *
5758  * We need to consider the worse case, when
5759  * one new block per extent.
5760  */
ext4_writepage_trans_blocks(struct inode * inode)5761 int ext4_writepage_trans_blocks(struct inode *inode)
5762 {
5763 	int bpp = ext4_journal_blocks_per_page(inode);
5764 	int ret;
5765 
5766 	ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5767 
5768 	/* Account for data blocks for journalled mode */
5769 	if (ext4_should_journal_data(inode))
5770 		ret += bpp;
5771 	return ret;
5772 }
5773 
5774 /*
5775  * Calculate the journal credits for a chunk of data modification.
5776  *
5777  * This is called from DIO, fallocate or whoever calling
5778  * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5779  *
5780  * journal buffers for data blocks are not included here, as DIO
5781  * and fallocate do no need to journal data buffers.
5782  */
ext4_chunk_trans_blocks(struct inode * inode,int nrblocks)5783 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5784 {
5785 	return ext4_meta_trans_blocks(inode, nrblocks, 1);
5786 }
5787 
5788 /*
5789  * The caller must have previously called ext4_reserve_inode_write().
5790  * Give this, we know that the caller already has write access to iloc->bh.
5791  */
ext4_mark_iloc_dirty(handle_t * handle,struct inode * inode,struct ext4_iloc * iloc)5792 int ext4_mark_iloc_dirty(handle_t *handle,
5793 			 struct inode *inode, struct ext4_iloc *iloc)
5794 {
5795 	int err = 0;
5796 
5797 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
5798 		put_bh(iloc->bh);
5799 		return -EIO;
5800 	}
5801 	ext4_fc_track_inode(handle, inode);
5802 
5803 	/* the do_update_inode consumes one bh->b_count */
5804 	get_bh(iloc->bh);
5805 
5806 	/* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5807 	err = ext4_do_update_inode(handle, inode, iloc);
5808 	put_bh(iloc->bh);
5809 	return err;
5810 }
5811 
5812 /*
5813  * On success, We end up with an outstanding reference count against
5814  * iloc->bh.  This _must_ be cleaned up later.
5815  */
5816 
5817 int
ext4_reserve_inode_write(handle_t * handle,struct inode * inode,struct ext4_iloc * iloc)5818 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5819 			 struct ext4_iloc *iloc)
5820 {
5821 	int err;
5822 
5823 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5824 		return -EIO;
5825 
5826 	err = ext4_get_inode_loc(inode, iloc);
5827 	if (!err) {
5828 		BUFFER_TRACE(iloc->bh, "get_write_access");
5829 		err = ext4_journal_get_write_access(handle, inode->i_sb,
5830 						    iloc->bh, EXT4_JTR_NONE);
5831 		if (err) {
5832 			brelse(iloc->bh);
5833 			iloc->bh = NULL;
5834 		}
5835 	}
5836 	ext4_std_error(inode->i_sb, err);
5837 	return err;
5838 }
5839 
__ext4_expand_extra_isize(struct inode * inode,unsigned int new_extra_isize,struct ext4_iloc * iloc,handle_t * handle,int * no_expand)5840 static int __ext4_expand_extra_isize(struct inode *inode,
5841 				     unsigned int new_extra_isize,
5842 				     struct ext4_iloc *iloc,
5843 				     handle_t *handle, int *no_expand)
5844 {
5845 	struct ext4_inode *raw_inode;
5846 	struct ext4_xattr_ibody_header *header;
5847 	unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
5848 	struct ext4_inode_info *ei = EXT4_I(inode);
5849 	int error;
5850 
5851 	/* this was checked at iget time, but double check for good measure */
5852 	if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
5853 	    (ei->i_extra_isize & 3)) {
5854 		EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
5855 				 ei->i_extra_isize,
5856 				 EXT4_INODE_SIZE(inode->i_sb));
5857 		return -EFSCORRUPTED;
5858 	}
5859 	if ((new_extra_isize < ei->i_extra_isize) ||
5860 	    (new_extra_isize < 4) ||
5861 	    (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
5862 		return -EINVAL;	/* Should never happen */
5863 
5864 	raw_inode = ext4_raw_inode(iloc);
5865 
5866 	header = IHDR(inode, raw_inode);
5867 
5868 	/* No extended attributes present */
5869 	if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5870 	    header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5871 		memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
5872 		       EXT4_I(inode)->i_extra_isize, 0,
5873 		       new_extra_isize - EXT4_I(inode)->i_extra_isize);
5874 		EXT4_I(inode)->i_extra_isize = new_extra_isize;
5875 		return 0;
5876 	}
5877 
5878 	/*
5879 	 * We may need to allocate external xattr block so we need quotas
5880 	 * initialized. Here we can be called with various locks held so we
5881 	 * cannot affort to initialize quotas ourselves. So just bail.
5882 	 */
5883 	if (dquot_initialize_needed(inode))
5884 		return -EAGAIN;
5885 
5886 	/* try to expand with EAs present */
5887 	error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
5888 					   raw_inode, handle);
5889 	if (error) {
5890 		/*
5891 		 * Inode size expansion failed; don't try again
5892 		 */
5893 		*no_expand = 1;
5894 	}
5895 
5896 	return error;
5897 }
5898 
5899 /*
5900  * Expand an inode by new_extra_isize bytes.
5901  * Returns 0 on success or negative error number on failure.
5902  */
ext4_try_to_expand_extra_isize(struct inode * inode,unsigned int new_extra_isize,struct ext4_iloc iloc,handle_t * handle)5903 static int ext4_try_to_expand_extra_isize(struct inode *inode,
5904 					  unsigned int new_extra_isize,
5905 					  struct ext4_iloc iloc,
5906 					  handle_t *handle)
5907 {
5908 	int no_expand;
5909 	int error;
5910 
5911 	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
5912 		return -EOVERFLOW;
5913 
5914 	/*
5915 	 * In nojournal mode, we can immediately attempt to expand
5916 	 * the inode.  When journaled, we first need to obtain extra
5917 	 * buffer credits since we may write into the EA block
5918 	 * with this same handle. If journal_extend fails, then it will
5919 	 * only result in a minor loss of functionality for that inode.
5920 	 * If this is felt to be critical, then e2fsck should be run to
5921 	 * force a large enough s_min_extra_isize.
5922 	 */
5923 	if (ext4_journal_extend(handle,
5924 				EXT4_DATA_TRANS_BLOCKS(inode->i_sb), 0) != 0)
5925 		return -ENOSPC;
5926 
5927 	if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
5928 		return -EBUSY;
5929 
5930 	error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
5931 					  handle, &no_expand);
5932 	ext4_write_unlock_xattr(inode, &no_expand);
5933 
5934 	return error;
5935 }
5936 
ext4_expand_extra_isize(struct inode * inode,unsigned int new_extra_isize,struct ext4_iloc * iloc)5937 int ext4_expand_extra_isize(struct inode *inode,
5938 			    unsigned int new_extra_isize,
5939 			    struct ext4_iloc *iloc)
5940 {
5941 	handle_t *handle;
5942 	int no_expand;
5943 	int error, rc;
5944 
5945 	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5946 		brelse(iloc->bh);
5947 		return -EOVERFLOW;
5948 	}
5949 
5950 	handle = ext4_journal_start(inode, EXT4_HT_INODE,
5951 				    EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
5952 	if (IS_ERR(handle)) {
5953 		error = PTR_ERR(handle);
5954 		brelse(iloc->bh);
5955 		return error;
5956 	}
5957 
5958 	ext4_write_lock_xattr(inode, &no_expand);
5959 
5960 	BUFFER_TRACE(iloc->bh, "get_write_access");
5961 	error = ext4_journal_get_write_access(handle, inode->i_sb, iloc->bh,
5962 					      EXT4_JTR_NONE);
5963 	if (error) {
5964 		brelse(iloc->bh);
5965 		goto out_unlock;
5966 	}
5967 
5968 	error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
5969 					  handle, &no_expand);
5970 
5971 	rc = ext4_mark_iloc_dirty(handle, inode, iloc);
5972 	if (!error)
5973 		error = rc;
5974 
5975 out_unlock:
5976 	ext4_write_unlock_xattr(inode, &no_expand);
5977 	ext4_journal_stop(handle);
5978 	return error;
5979 }
5980 
5981 /*
5982  * What we do here is to mark the in-core inode as clean with respect to inode
5983  * dirtiness (it may still be data-dirty).
5984  * This means that the in-core inode may be reaped by prune_icache
5985  * without having to perform any I/O.  This is a very good thing,
5986  * because *any* task may call prune_icache - even ones which
5987  * have a transaction open against a different journal.
5988  *
5989  * Is this cheating?  Not really.  Sure, we haven't written the
5990  * inode out, but prune_icache isn't a user-visible syncing function.
5991  * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5992  * we start and wait on commits.
5993  */
__ext4_mark_inode_dirty(handle_t * handle,struct inode * inode,const char * func,unsigned int line)5994 int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode,
5995 				const char *func, unsigned int line)
5996 {
5997 	struct ext4_iloc iloc;
5998 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5999 	int err;
6000 
6001 	might_sleep();
6002 	trace_ext4_mark_inode_dirty(inode, _RET_IP_);
6003 	err = ext4_reserve_inode_write(handle, inode, &iloc);
6004 	if (err)
6005 		goto out;
6006 
6007 	if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
6008 		ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
6009 					       iloc, handle);
6010 
6011 	err = ext4_mark_iloc_dirty(handle, inode, &iloc);
6012 out:
6013 	if (unlikely(err))
6014 		ext4_error_inode_err(inode, func, line, 0, err,
6015 					"mark_inode_dirty error");
6016 	return err;
6017 }
6018 
6019 /*
6020  * ext4_dirty_inode() is called from __mark_inode_dirty()
6021  *
6022  * We're really interested in the case where a file is being extended.
6023  * i_size has been changed by generic_commit_write() and we thus need
6024  * to include the updated inode in the current transaction.
6025  *
6026  * Also, dquot_alloc_block() will always dirty the inode when blocks
6027  * are allocated to the file.
6028  *
6029  * If the inode is marked synchronous, we don't honour that here - doing
6030  * so would cause a commit on atime updates, which we don't bother doing.
6031  * We handle synchronous inodes at the highest possible level.
6032  */
ext4_dirty_inode(struct inode * inode,int flags)6033 void ext4_dirty_inode(struct inode *inode, int flags)
6034 {
6035 	handle_t *handle;
6036 
6037 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
6038 	if (IS_ERR(handle))
6039 		return;
6040 	ext4_mark_inode_dirty(handle, inode);
6041 	ext4_journal_stop(handle);
6042 }
6043 
ext4_change_inode_journal_flag(struct inode * inode,int val)6044 int ext4_change_inode_journal_flag(struct inode *inode, int val)
6045 {
6046 	journal_t *journal;
6047 	handle_t *handle;
6048 	int err;
6049 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
6050 
6051 	/*
6052 	 * We have to be very careful here: changing a data block's
6053 	 * journaling status dynamically is dangerous.  If we write a
6054 	 * data block to the journal, change the status and then delete
6055 	 * that block, we risk forgetting to revoke the old log record
6056 	 * from the journal and so a subsequent replay can corrupt data.
6057 	 * So, first we make sure that the journal is empty and that
6058 	 * nobody is changing anything.
6059 	 */
6060 
6061 	journal = EXT4_JOURNAL(inode);
6062 	if (!journal)
6063 		return 0;
6064 	if (is_journal_aborted(journal))
6065 		return -EROFS;
6066 
6067 	/* Wait for all existing dio workers */
6068 	inode_dio_wait(inode);
6069 
6070 	/*
6071 	 * Before flushing the journal and switching inode's aops, we have
6072 	 * to flush all dirty data the inode has. There can be outstanding
6073 	 * delayed allocations, there can be unwritten extents created by
6074 	 * fallocate or buffered writes in dioread_nolock mode covered by
6075 	 * dirty data which can be converted only after flushing the dirty
6076 	 * data (and journalled aops don't know how to handle these cases).
6077 	 */
6078 	if (val) {
6079 		filemap_invalidate_lock(inode->i_mapping);
6080 		err = filemap_write_and_wait(inode->i_mapping);
6081 		if (err < 0) {
6082 			filemap_invalidate_unlock(inode->i_mapping);
6083 			return err;
6084 		}
6085 	}
6086 
6087 	percpu_down_write(&sbi->s_writepages_rwsem);
6088 	jbd2_journal_lock_updates(journal);
6089 
6090 	/*
6091 	 * OK, there are no updates running now, and all cached data is
6092 	 * synced to disk.  We are now in a completely consistent state
6093 	 * which doesn't have anything in the journal, and we know that
6094 	 * no filesystem updates are running, so it is safe to modify
6095 	 * the inode's in-core data-journaling state flag now.
6096 	 */
6097 
6098 	if (val)
6099 		ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6100 	else {
6101 		err = jbd2_journal_flush(journal, 0);
6102 		if (err < 0) {
6103 			jbd2_journal_unlock_updates(journal);
6104 			percpu_up_write(&sbi->s_writepages_rwsem);
6105 			return err;
6106 		}
6107 		ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6108 	}
6109 	ext4_set_aops(inode);
6110 
6111 	jbd2_journal_unlock_updates(journal);
6112 	percpu_up_write(&sbi->s_writepages_rwsem);
6113 
6114 	if (val)
6115 		filemap_invalidate_unlock(inode->i_mapping);
6116 
6117 	/* Finally we can mark the inode as dirty. */
6118 
6119 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
6120 	if (IS_ERR(handle))
6121 		return PTR_ERR(handle);
6122 
6123 	ext4_fc_mark_ineligible(inode->i_sb,
6124 		EXT4_FC_REASON_JOURNAL_FLAG_CHANGE, handle);
6125 	err = ext4_mark_inode_dirty(handle, inode);
6126 	ext4_handle_sync(handle);
6127 	ext4_journal_stop(handle);
6128 	ext4_std_error(inode->i_sb, err);
6129 
6130 	return err;
6131 }
6132 
ext4_bh_unmapped(handle_t * handle,struct inode * inode,struct buffer_head * bh)6133 static int ext4_bh_unmapped(handle_t *handle, struct inode *inode,
6134 			    struct buffer_head *bh)
6135 {
6136 	return !buffer_mapped(bh);
6137 }
6138 
ext4_page_mkwrite(struct vm_fault * vmf)6139 vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)
6140 {
6141 	struct vm_area_struct *vma = vmf->vma;
6142 	struct page *page = vmf->page;
6143 	loff_t size;
6144 	unsigned long len;
6145 	int err;
6146 	vm_fault_t ret;
6147 	struct file *file = vma->vm_file;
6148 	struct inode *inode = file_inode(file);
6149 	struct address_space *mapping = inode->i_mapping;
6150 	handle_t *handle;
6151 	get_block_t *get_block;
6152 	int retries = 0;
6153 
6154 	if (unlikely(IS_IMMUTABLE(inode)))
6155 		return VM_FAULT_SIGBUS;
6156 
6157 	sb_start_pagefault(inode->i_sb);
6158 	file_update_time(vma->vm_file);
6159 
6160 	filemap_invalidate_lock_shared(mapping);
6161 
6162 	err = ext4_convert_inline_data(inode);
6163 	if (err)
6164 		goto out_ret;
6165 
6166 	/*
6167 	 * On data journalling we skip straight to the transaction handle:
6168 	 * there's no delalloc; page truncated will be checked later; the
6169 	 * early return w/ all buffers mapped (calculates size/len) can't
6170 	 * be used; and there's no dioread_nolock, so only ext4_get_block.
6171 	 */
6172 	if (ext4_should_journal_data(inode))
6173 		goto retry_alloc;
6174 
6175 	/* Delalloc case is easy... */
6176 	if (test_opt(inode->i_sb, DELALLOC) &&
6177 	    !ext4_nonda_switch(inode->i_sb)) {
6178 		do {
6179 			err = block_page_mkwrite(vma, vmf,
6180 						   ext4_da_get_block_prep);
6181 		} while (err == -ENOSPC &&
6182 		       ext4_should_retry_alloc(inode->i_sb, &retries));
6183 		goto out_ret;
6184 	}
6185 
6186 	lock_page(page);
6187 	size = i_size_read(inode);
6188 	/* Page got truncated from under us? */
6189 	if (page->mapping != mapping || page_offset(page) > size) {
6190 		unlock_page(page);
6191 		ret = VM_FAULT_NOPAGE;
6192 		goto out;
6193 	}
6194 
6195 	if (page->index == size >> PAGE_SHIFT)
6196 		len = size & ~PAGE_MASK;
6197 	else
6198 		len = PAGE_SIZE;
6199 	/*
6200 	 * Return if we have all the buffers mapped. This avoids the need to do
6201 	 * journal_start/journal_stop which can block and take a long time
6202 	 *
6203 	 * This cannot be done for data journalling, as we have to add the
6204 	 * inode to the transaction's list to writeprotect pages on commit.
6205 	 */
6206 	if (page_has_buffers(page)) {
6207 		if (!ext4_walk_page_buffers(NULL, inode, page_buffers(page),
6208 					    0, len, NULL,
6209 					    ext4_bh_unmapped)) {
6210 			/* Wait so that we don't change page under IO */
6211 			wait_for_stable_page(page);
6212 			ret = VM_FAULT_LOCKED;
6213 			goto out;
6214 		}
6215 	}
6216 	unlock_page(page);
6217 	/* OK, we need to fill the hole... */
6218 	if (ext4_should_dioread_nolock(inode))
6219 		get_block = ext4_get_block_unwritten;
6220 	else
6221 		get_block = ext4_get_block;
6222 retry_alloc:
6223 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
6224 				    ext4_writepage_trans_blocks(inode));
6225 	if (IS_ERR(handle)) {
6226 		ret = VM_FAULT_SIGBUS;
6227 		goto out;
6228 	}
6229 	/*
6230 	 * Data journalling can't use block_page_mkwrite() because it
6231 	 * will set_buffer_dirty() before do_journal_get_write_access()
6232 	 * thus might hit warning messages for dirty metadata buffers.
6233 	 */
6234 	if (!ext4_should_journal_data(inode)) {
6235 		err = block_page_mkwrite(vma, vmf, get_block);
6236 	} else {
6237 		lock_page(page);
6238 		size = i_size_read(inode);
6239 		/* Page got truncated from under us? */
6240 		if (page->mapping != mapping || page_offset(page) > size) {
6241 			ret = VM_FAULT_NOPAGE;
6242 			goto out_error;
6243 		}
6244 
6245 		if (page->index == size >> PAGE_SHIFT)
6246 			len = size & ~PAGE_MASK;
6247 		else
6248 			len = PAGE_SIZE;
6249 
6250 		err = __block_write_begin(page, 0, len, ext4_get_block);
6251 		if (!err) {
6252 			ret = VM_FAULT_SIGBUS;
6253 			if (ext4_walk_page_buffers(handle, inode,
6254 					page_buffers(page), 0, len, NULL,
6255 					do_journal_get_write_access))
6256 				goto out_error;
6257 			if (ext4_walk_page_buffers(handle, inode,
6258 					page_buffers(page), 0, len, NULL,
6259 					write_end_fn))
6260 				goto out_error;
6261 			if (ext4_jbd2_inode_add_write(handle, inode,
6262 						      page_offset(page), len))
6263 				goto out_error;
6264 			ext4_set_inode_state(inode, EXT4_STATE_JDATA);
6265 		} else {
6266 			unlock_page(page);
6267 		}
6268 	}
6269 	ext4_journal_stop(handle);
6270 	if (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
6271 		goto retry_alloc;
6272 out_ret:
6273 	ret = block_page_mkwrite_return(err);
6274 out:
6275 	filemap_invalidate_unlock_shared(mapping);
6276 	sb_end_pagefault(inode->i_sb);
6277 	return ret;
6278 out_error:
6279 	unlock_page(page);
6280 	ext4_journal_stop(handle);
6281 	goto out;
6282 }
6283