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