xref: /openbmc/linux/fs/ext4/inode.c (revision a80f7fcf18672ae4971a6b713b58c0d389aa99fe)
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_SB(sb)->s_mount_flags & 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 		     sbi->s_mount_flags & 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 atomic_read(&EXT4_SB(inode->i_sb)->s_fc_subtid) <
3316 				EXT4_I(inode)->i_fc_committed_subtid;
3317 		return true;
3318 	}
3319 
3320 	/* Any metadata buffers to write? */
3321 	if (!list_empty(&inode->i_mapping->private_list))
3322 		return true;
3323 	return inode->i_state & I_DIRTY_DATASYNC;
3324 }
3325 
3326 static void ext4_set_iomap(struct inode *inode, struct iomap *iomap,
3327 			   struct ext4_map_blocks *map, loff_t offset,
3328 			   loff_t length)
3329 {
3330 	u8 blkbits = inode->i_blkbits;
3331 
3332 	/*
3333 	 * Writes that span EOF might trigger an I/O size update on completion,
3334 	 * so consider them to be dirty for the purpose of O_DSYNC, even if
3335 	 * there is no other metadata changes being made or are pending.
3336 	 */
3337 	iomap->flags = 0;
3338 	if (ext4_inode_datasync_dirty(inode) ||
3339 	    offset + length > i_size_read(inode))
3340 		iomap->flags |= IOMAP_F_DIRTY;
3341 
3342 	if (map->m_flags & EXT4_MAP_NEW)
3343 		iomap->flags |= IOMAP_F_NEW;
3344 
3345 	iomap->bdev = inode->i_sb->s_bdev;
3346 	iomap->dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
3347 	iomap->offset = (u64) map->m_lblk << blkbits;
3348 	iomap->length = (u64) map->m_len << blkbits;
3349 
3350 	if ((map->m_flags & EXT4_MAP_MAPPED) &&
3351 	    !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3352 		iomap->flags |= IOMAP_F_MERGED;
3353 
3354 	/*
3355 	 * Flags passed to ext4_map_blocks() for direct I/O writes can result
3356 	 * in m_flags having both EXT4_MAP_MAPPED and EXT4_MAP_UNWRITTEN bits
3357 	 * set. In order for any allocated unwritten extents to be converted
3358 	 * into written extents correctly within the ->end_io() handler, we
3359 	 * need to ensure that the iomap->type is set appropriately. Hence, the
3360 	 * reason why we need to check whether the EXT4_MAP_UNWRITTEN bit has
3361 	 * been set first.
3362 	 */
3363 	if (map->m_flags & EXT4_MAP_UNWRITTEN) {
3364 		iomap->type = IOMAP_UNWRITTEN;
3365 		iomap->addr = (u64) map->m_pblk << blkbits;
3366 	} else if (map->m_flags & EXT4_MAP_MAPPED) {
3367 		iomap->type = IOMAP_MAPPED;
3368 		iomap->addr = (u64) map->m_pblk << blkbits;
3369 	} else {
3370 		iomap->type = IOMAP_HOLE;
3371 		iomap->addr = IOMAP_NULL_ADDR;
3372 	}
3373 }
3374 
3375 static int ext4_iomap_alloc(struct inode *inode, struct ext4_map_blocks *map,
3376 			    unsigned int flags)
3377 {
3378 	handle_t *handle;
3379 	u8 blkbits = inode->i_blkbits;
3380 	int ret, dio_credits, m_flags = 0, retries = 0;
3381 
3382 	/*
3383 	 * Trim the mapping request to the maximum value that we can map at
3384 	 * once for direct I/O.
3385 	 */
3386 	if (map->m_len > DIO_MAX_BLOCKS)
3387 		map->m_len = DIO_MAX_BLOCKS;
3388 	dio_credits = ext4_chunk_trans_blocks(inode, map->m_len);
3389 
3390 retry:
3391 	/*
3392 	 * Either we allocate blocks and then don't get an unwritten extent, so
3393 	 * in that case we have reserved enough credits. Or, the blocks are
3394 	 * already allocated and unwritten. In that case, the extent conversion
3395 	 * fits into the credits as well.
3396 	 */
3397 	handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
3398 	if (IS_ERR(handle))
3399 		return PTR_ERR(handle);
3400 
3401 	/*
3402 	 * DAX and direct I/O are the only two operations that are currently
3403 	 * supported with IOMAP_WRITE.
3404 	 */
3405 	WARN_ON(!IS_DAX(inode) && !(flags & IOMAP_DIRECT));
3406 	if (IS_DAX(inode))
3407 		m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
3408 	/*
3409 	 * We use i_size instead of i_disksize here because delalloc writeback
3410 	 * can complete at any point during the I/O and subsequently push the
3411 	 * i_disksize out to i_size. This could be beyond where direct I/O is
3412 	 * happening and thus expose allocated blocks to direct I/O reads.
3413 	 */
3414 	else if ((map->m_lblk * (1 << blkbits)) >= i_size_read(inode))
3415 		m_flags = EXT4_GET_BLOCKS_CREATE;
3416 	else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3417 		m_flags = EXT4_GET_BLOCKS_IO_CREATE_EXT;
3418 
3419 	ret = ext4_map_blocks(handle, inode, map, m_flags);
3420 
3421 	/*
3422 	 * We cannot fill holes in indirect tree based inodes as that could
3423 	 * expose stale data in the case of a crash. Use the magic error code
3424 	 * to fallback to buffered I/O.
3425 	 */
3426 	if (!m_flags && !ret)
3427 		ret = -ENOTBLK;
3428 
3429 	ext4_journal_stop(handle);
3430 	if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3431 		goto retry;
3432 
3433 	return ret;
3434 }
3435 
3436 
3437 static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3438 		unsigned flags, struct iomap *iomap, struct iomap *srcmap)
3439 {
3440 	int ret;
3441 	struct ext4_map_blocks map;
3442 	u8 blkbits = inode->i_blkbits;
3443 
3444 	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3445 		return -EINVAL;
3446 
3447 	if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3448 		return -ERANGE;
3449 
3450 	/*
3451 	 * Calculate the first and last logical blocks respectively.
3452 	 */
3453 	map.m_lblk = offset >> blkbits;
3454 	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3455 			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3456 
3457 	if (flags & IOMAP_WRITE) {
3458 		/*
3459 		 * We check here if the blocks are already allocated, then we
3460 		 * don't need to start a journal txn and we can directly return
3461 		 * the mapping information. This could boost performance
3462 		 * especially in multi-threaded overwrite requests.
3463 		 */
3464 		if (offset + length <= i_size_read(inode)) {
3465 			ret = ext4_map_blocks(NULL, inode, &map, 0);
3466 			if (ret > 0 && (map.m_flags & EXT4_MAP_MAPPED))
3467 				goto out;
3468 		}
3469 		ret = ext4_iomap_alloc(inode, &map, flags);
3470 	} else {
3471 		ret = ext4_map_blocks(NULL, inode, &map, 0);
3472 	}
3473 
3474 	if (ret < 0)
3475 		return ret;
3476 out:
3477 	ext4_set_iomap(inode, iomap, &map, offset, length);
3478 
3479 	return 0;
3480 }
3481 
3482 static int ext4_iomap_overwrite_begin(struct inode *inode, loff_t offset,
3483 		loff_t length, unsigned flags, struct iomap *iomap,
3484 		struct iomap *srcmap)
3485 {
3486 	int ret;
3487 
3488 	/*
3489 	 * Even for writes we don't need to allocate blocks, so just pretend
3490 	 * we are reading to save overhead of starting a transaction.
3491 	 */
3492 	flags &= ~IOMAP_WRITE;
3493 	ret = ext4_iomap_begin(inode, offset, length, flags, iomap, srcmap);
3494 	WARN_ON_ONCE(iomap->type != IOMAP_MAPPED);
3495 	return ret;
3496 }
3497 
3498 static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3499 			  ssize_t written, unsigned flags, struct iomap *iomap)
3500 {
3501 	/*
3502 	 * Check to see whether an error occurred while writing out the data to
3503 	 * the allocated blocks. If so, return the magic error code so that we
3504 	 * fallback to buffered I/O and attempt to complete the remainder of
3505 	 * the I/O. Any blocks that may have been allocated in preparation for
3506 	 * the direct I/O will be reused during buffered I/O.
3507 	 */
3508 	if (flags & (IOMAP_WRITE | IOMAP_DIRECT) && written == 0)
3509 		return -ENOTBLK;
3510 
3511 	return 0;
3512 }
3513 
3514 const struct iomap_ops ext4_iomap_ops = {
3515 	.iomap_begin		= ext4_iomap_begin,
3516 	.iomap_end		= ext4_iomap_end,
3517 };
3518 
3519 const struct iomap_ops ext4_iomap_overwrite_ops = {
3520 	.iomap_begin		= ext4_iomap_overwrite_begin,
3521 	.iomap_end		= ext4_iomap_end,
3522 };
3523 
3524 static bool ext4_iomap_is_delalloc(struct inode *inode,
3525 				   struct ext4_map_blocks *map)
3526 {
3527 	struct extent_status es;
3528 	ext4_lblk_t offset = 0, end = map->m_lblk + map->m_len - 1;
3529 
3530 	ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
3531 				  map->m_lblk, end, &es);
3532 
3533 	if (!es.es_len || es.es_lblk > end)
3534 		return false;
3535 
3536 	if (es.es_lblk > map->m_lblk) {
3537 		map->m_len = es.es_lblk - map->m_lblk;
3538 		return false;
3539 	}
3540 
3541 	offset = map->m_lblk - es.es_lblk;
3542 	map->m_len = es.es_len - offset;
3543 
3544 	return true;
3545 }
3546 
3547 static int ext4_iomap_begin_report(struct inode *inode, loff_t offset,
3548 				   loff_t length, unsigned int flags,
3549 				   struct iomap *iomap, struct iomap *srcmap)
3550 {
3551 	int ret;
3552 	bool delalloc = false;
3553 	struct ext4_map_blocks map;
3554 	u8 blkbits = inode->i_blkbits;
3555 
3556 	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3557 		return -EINVAL;
3558 
3559 	if (ext4_has_inline_data(inode)) {
3560 		ret = ext4_inline_data_iomap(inode, iomap);
3561 		if (ret != -EAGAIN) {
3562 			if (ret == 0 && offset >= iomap->length)
3563 				ret = -ENOENT;
3564 			return ret;
3565 		}
3566 	}
3567 
3568 	/*
3569 	 * Calculate the first and last logical block respectively.
3570 	 */
3571 	map.m_lblk = offset >> blkbits;
3572 	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3573 			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3574 
3575 	/*
3576 	 * Fiemap callers may call for offset beyond s_bitmap_maxbytes.
3577 	 * So handle it here itself instead of querying ext4_map_blocks().
3578 	 * Since ext4_map_blocks() will warn about it and will return
3579 	 * -EIO error.
3580 	 */
3581 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
3582 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3583 
3584 		if (offset >= sbi->s_bitmap_maxbytes) {
3585 			map.m_flags = 0;
3586 			goto set_iomap;
3587 		}
3588 	}
3589 
3590 	ret = ext4_map_blocks(NULL, inode, &map, 0);
3591 	if (ret < 0)
3592 		return ret;
3593 	if (ret == 0)
3594 		delalloc = ext4_iomap_is_delalloc(inode, &map);
3595 
3596 set_iomap:
3597 	ext4_set_iomap(inode, iomap, &map, offset, length);
3598 	if (delalloc && iomap->type == IOMAP_HOLE)
3599 		iomap->type = IOMAP_DELALLOC;
3600 
3601 	return 0;
3602 }
3603 
3604 const struct iomap_ops ext4_iomap_report_ops = {
3605 	.iomap_begin = ext4_iomap_begin_report,
3606 };
3607 
3608 /*
3609  * Pages can be marked dirty completely asynchronously from ext4's journalling
3610  * activity.  By filemap_sync_pte(), try_to_unmap_one(), etc.  We cannot do
3611  * much here because ->set_page_dirty is called under VFS locks.  The page is
3612  * not necessarily locked.
3613  *
3614  * We cannot just dirty the page and leave attached buffers clean, because the
3615  * buffers' dirty state is "definitive".  We cannot just set the buffers dirty
3616  * or jbddirty because all the journalling code will explode.
3617  *
3618  * So what we do is to mark the page "pending dirty" and next time writepage
3619  * is called, propagate that into the buffers appropriately.
3620  */
3621 static int ext4_journalled_set_page_dirty(struct page *page)
3622 {
3623 	SetPageChecked(page);
3624 	return __set_page_dirty_nobuffers(page);
3625 }
3626 
3627 static int ext4_set_page_dirty(struct page *page)
3628 {
3629 	WARN_ON_ONCE(!PageLocked(page) && !PageDirty(page));
3630 	WARN_ON_ONCE(!page_has_buffers(page));
3631 	return __set_page_dirty_buffers(page);
3632 }
3633 
3634 static int ext4_iomap_swap_activate(struct swap_info_struct *sis,
3635 				    struct file *file, sector_t *span)
3636 {
3637 	return iomap_swapfile_activate(sis, file, span,
3638 				       &ext4_iomap_report_ops);
3639 }
3640 
3641 static const struct address_space_operations ext4_aops = {
3642 	.readpage		= ext4_readpage,
3643 	.readahead		= ext4_readahead,
3644 	.writepage		= ext4_writepage,
3645 	.writepages		= ext4_writepages,
3646 	.write_begin		= ext4_write_begin,
3647 	.write_end		= ext4_write_end,
3648 	.set_page_dirty		= ext4_set_page_dirty,
3649 	.bmap			= ext4_bmap,
3650 	.invalidatepage		= ext4_invalidatepage,
3651 	.releasepage		= ext4_releasepage,
3652 	.direct_IO		= noop_direct_IO,
3653 	.migratepage		= buffer_migrate_page,
3654 	.is_partially_uptodate  = block_is_partially_uptodate,
3655 	.error_remove_page	= generic_error_remove_page,
3656 	.swap_activate		= ext4_iomap_swap_activate,
3657 };
3658 
3659 static const struct address_space_operations ext4_journalled_aops = {
3660 	.readpage		= ext4_readpage,
3661 	.readahead		= ext4_readahead,
3662 	.writepage		= ext4_writepage,
3663 	.writepages		= ext4_writepages,
3664 	.write_begin		= ext4_write_begin,
3665 	.write_end		= ext4_journalled_write_end,
3666 	.set_page_dirty		= ext4_journalled_set_page_dirty,
3667 	.bmap			= ext4_bmap,
3668 	.invalidatepage		= ext4_journalled_invalidatepage,
3669 	.releasepage		= ext4_releasepage,
3670 	.direct_IO		= noop_direct_IO,
3671 	.is_partially_uptodate  = block_is_partially_uptodate,
3672 	.error_remove_page	= generic_error_remove_page,
3673 	.swap_activate		= ext4_iomap_swap_activate,
3674 };
3675 
3676 static const struct address_space_operations ext4_da_aops = {
3677 	.readpage		= ext4_readpage,
3678 	.readahead		= ext4_readahead,
3679 	.writepage		= ext4_writepage,
3680 	.writepages		= ext4_writepages,
3681 	.write_begin		= ext4_da_write_begin,
3682 	.write_end		= ext4_da_write_end,
3683 	.set_page_dirty		= ext4_set_page_dirty,
3684 	.bmap			= ext4_bmap,
3685 	.invalidatepage		= ext4_invalidatepage,
3686 	.releasepage		= ext4_releasepage,
3687 	.direct_IO		= noop_direct_IO,
3688 	.migratepage		= buffer_migrate_page,
3689 	.is_partially_uptodate  = block_is_partially_uptodate,
3690 	.error_remove_page	= generic_error_remove_page,
3691 	.swap_activate		= ext4_iomap_swap_activate,
3692 };
3693 
3694 static const struct address_space_operations ext4_dax_aops = {
3695 	.writepages		= ext4_dax_writepages,
3696 	.direct_IO		= noop_direct_IO,
3697 	.set_page_dirty		= noop_set_page_dirty,
3698 	.bmap			= ext4_bmap,
3699 	.invalidatepage		= noop_invalidatepage,
3700 	.swap_activate		= ext4_iomap_swap_activate,
3701 };
3702 
3703 void ext4_set_aops(struct inode *inode)
3704 {
3705 	switch (ext4_inode_journal_mode(inode)) {
3706 	case EXT4_INODE_ORDERED_DATA_MODE:
3707 	case EXT4_INODE_WRITEBACK_DATA_MODE:
3708 		break;
3709 	case EXT4_INODE_JOURNAL_DATA_MODE:
3710 		inode->i_mapping->a_ops = &ext4_journalled_aops;
3711 		return;
3712 	default:
3713 		BUG();
3714 	}
3715 	if (IS_DAX(inode))
3716 		inode->i_mapping->a_ops = &ext4_dax_aops;
3717 	else if (test_opt(inode->i_sb, DELALLOC))
3718 		inode->i_mapping->a_ops = &ext4_da_aops;
3719 	else
3720 		inode->i_mapping->a_ops = &ext4_aops;
3721 }
3722 
3723 static int __ext4_block_zero_page_range(handle_t *handle,
3724 		struct address_space *mapping, loff_t from, loff_t length)
3725 {
3726 	ext4_fsblk_t index = from >> PAGE_SHIFT;
3727 	unsigned offset = from & (PAGE_SIZE-1);
3728 	unsigned blocksize, pos;
3729 	ext4_lblk_t iblock;
3730 	struct inode *inode = mapping->host;
3731 	struct buffer_head *bh;
3732 	struct page *page;
3733 	int err = 0;
3734 
3735 	page = find_or_create_page(mapping, from >> PAGE_SHIFT,
3736 				   mapping_gfp_constraint(mapping, ~__GFP_FS));
3737 	if (!page)
3738 		return -ENOMEM;
3739 
3740 	blocksize = inode->i_sb->s_blocksize;
3741 
3742 	iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
3743 
3744 	if (!page_has_buffers(page))
3745 		create_empty_buffers(page, blocksize, 0);
3746 
3747 	/* Find the buffer that contains "offset" */
3748 	bh = page_buffers(page);
3749 	pos = blocksize;
3750 	while (offset >= pos) {
3751 		bh = bh->b_this_page;
3752 		iblock++;
3753 		pos += blocksize;
3754 	}
3755 	if (buffer_freed(bh)) {
3756 		BUFFER_TRACE(bh, "freed: skip");
3757 		goto unlock;
3758 	}
3759 	if (!buffer_mapped(bh)) {
3760 		BUFFER_TRACE(bh, "unmapped");
3761 		ext4_get_block(inode, iblock, bh, 0);
3762 		/* unmapped? It's a hole - nothing to do */
3763 		if (!buffer_mapped(bh)) {
3764 			BUFFER_TRACE(bh, "still unmapped");
3765 			goto unlock;
3766 		}
3767 	}
3768 
3769 	/* Ok, it's mapped. Make sure it's up-to-date */
3770 	if (PageUptodate(page))
3771 		set_buffer_uptodate(bh);
3772 
3773 	if (!buffer_uptodate(bh)) {
3774 		err = ext4_read_bh_lock(bh, 0, true);
3775 		if (err)
3776 			goto unlock;
3777 		if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
3778 			/* We expect the key to be set. */
3779 			BUG_ON(!fscrypt_has_encryption_key(inode));
3780 			err = fscrypt_decrypt_pagecache_blocks(page, blocksize,
3781 							       bh_offset(bh));
3782 			if (err) {
3783 				clear_buffer_uptodate(bh);
3784 				goto unlock;
3785 			}
3786 		}
3787 	}
3788 	if (ext4_should_journal_data(inode)) {
3789 		BUFFER_TRACE(bh, "get write access");
3790 		err = ext4_journal_get_write_access(handle, bh);
3791 		if (err)
3792 			goto unlock;
3793 	}
3794 	zero_user(page, offset, length);
3795 	BUFFER_TRACE(bh, "zeroed end of block");
3796 
3797 	if (ext4_should_journal_data(inode)) {
3798 		err = ext4_handle_dirty_metadata(handle, inode, bh);
3799 	} else {
3800 		err = 0;
3801 		mark_buffer_dirty(bh);
3802 		if (ext4_should_order_data(inode))
3803 			err = ext4_jbd2_inode_add_write(handle, inode, from,
3804 					length);
3805 	}
3806 
3807 unlock:
3808 	unlock_page(page);
3809 	put_page(page);
3810 	return err;
3811 }
3812 
3813 /*
3814  * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3815  * starting from file offset 'from'.  The range to be zero'd must
3816  * be contained with in one block.  If the specified range exceeds
3817  * the end of the block it will be shortened to end of the block
3818  * that cooresponds to 'from'
3819  */
3820 static int ext4_block_zero_page_range(handle_t *handle,
3821 		struct address_space *mapping, loff_t from, loff_t length)
3822 {
3823 	struct inode *inode = mapping->host;
3824 	unsigned offset = from & (PAGE_SIZE-1);
3825 	unsigned blocksize = inode->i_sb->s_blocksize;
3826 	unsigned max = blocksize - (offset & (blocksize - 1));
3827 
3828 	/*
3829 	 * correct length if it does not fall between
3830 	 * 'from' and the end of the block
3831 	 */
3832 	if (length > max || length < 0)
3833 		length = max;
3834 
3835 	if (IS_DAX(inode)) {
3836 		return iomap_zero_range(inode, from, length, NULL,
3837 					&ext4_iomap_ops);
3838 	}
3839 	return __ext4_block_zero_page_range(handle, mapping, from, length);
3840 }
3841 
3842 /*
3843  * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3844  * up to the end of the block which corresponds to `from'.
3845  * This required during truncate. We need to physically zero the tail end
3846  * of that block so it doesn't yield old data if the file is later grown.
3847  */
3848 static int ext4_block_truncate_page(handle_t *handle,
3849 		struct address_space *mapping, loff_t from)
3850 {
3851 	unsigned offset = from & (PAGE_SIZE-1);
3852 	unsigned length;
3853 	unsigned blocksize;
3854 	struct inode *inode = mapping->host;
3855 
3856 	/* If we are processing an encrypted inode during orphan list handling */
3857 	if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode))
3858 		return 0;
3859 
3860 	blocksize = inode->i_sb->s_blocksize;
3861 	length = blocksize - (offset & (blocksize - 1));
3862 
3863 	return ext4_block_zero_page_range(handle, mapping, from, length);
3864 }
3865 
3866 int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3867 			     loff_t lstart, loff_t length)
3868 {
3869 	struct super_block *sb = inode->i_sb;
3870 	struct address_space *mapping = inode->i_mapping;
3871 	unsigned partial_start, partial_end;
3872 	ext4_fsblk_t start, end;
3873 	loff_t byte_end = (lstart + length - 1);
3874 	int err = 0;
3875 
3876 	partial_start = lstart & (sb->s_blocksize - 1);
3877 	partial_end = byte_end & (sb->s_blocksize - 1);
3878 
3879 	start = lstart >> sb->s_blocksize_bits;
3880 	end = byte_end >> sb->s_blocksize_bits;
3881 
3882 	/* Handle partial zero within the single block */
3883 	if (start == end &&
3884 	    (partial_start || (partial_end != sb->s_blocksize - 1))) {
3885 		err = ext4_block_zero_page_range(handle, mapping,
3886 						 lstart, length);
3887 		return err;
3888 	}
3889 	/* Handle partial zero out on the start of the range */
3890 	if (partial_start) {
3891 		err = ext4_block_zero_page_range(handle, mapping,
3892 						 lstart, sb->s_blocksize);
3893 		if (err)
3894 			return err;
3895 	}
3896 	/* Handle partial zero out on the end of the range */
3897 	if (partial_end != sb->s_blocksize - 1)
3898 		err = ext4_block_zero_page_range(handle, mapping,
3899 						 byte_end - partial_end,
3900 						 partial_end + 1);
3901 	return err;
3902 }
3903 
3904 int ext4_can_truncate(struct inode *inode)
3905 {
3906 	if (S_ISREG(inode->i_mode))
3907 		return 1;
3908 	if (S_ISDIR(inode->i_mode))
3909 		return 1;
3910 	if (S_ISLNK(inode->i_mode))
3911 		return !ext4_inode_is_fast_symlink(inode);
3912 	return 0;
3913 }
3914 
3915 /*
3916  * We have to make sure i_disksize gets properly updated before we truncate
3917  * page cache due to hole punching or zero range. Otherwise i_disksize update
3918  * can get lost as it may have been postponed to submission of writeback but
3919  * that will never happen after we truncate page cache.
3920  */
3921 int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
3922 				      loff_t len)
3923 {
3924 	handle_t *handle;
3925 	int ret;
3926 
3927 	loff_t size = i_size_read(inode);
3928 
3929 	WARN_ON(!inode_is_locked(inode));
3930 	if (offset > size || offset + len < size)
3931 		return 0;
3932 
3933 	if (EXT4_I(inode)->i_disksize >= size)
3934 		return 0;
3935 
3936 	handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
3937 	if (IS_ERR(handle))
3938 		return PTR_ERR(handle);
3939 	ext4_update_i_disksize(inode, size);
3940 	ret = ext4_mark_inode_dirty(handle, inode);
3941 	ext4_journal_stop(handle);
3942 
3943 	return ret;
3944 }
3945 
3946 static void ext4_wait_dax_page(struct ext4_inode_info *ei)
3947 {
3948 	up_write(&ei->i_mmap_sem);
3949 	schedule();
3950 	down_write(&ei->i_mmap_sem);
3951 }
3952 
3953 int ext4_break_layouts(struct inode *inode)
3954 {
3955 	struct ext4_inode_info *ei = EXT4_I(inode);
3956 	struct page *page;
3957 	int error;
3958 
3959 	if (WARN_ON_ONCE(!rwsem_is_locked(&ei->i_mmap_sem)))
3960 		return -EINVAL;
3961 
3962 	do {
3963 		page = dax_layout_busy_page(inode->i_mapping);
3964 		if (!page)
3965 			return 0;
3966 
3967 		error = ___wait_var_event(&page->_refcount,
3968 				atomic_read(&page->_refcount) == 1,
3969 				TASK_INTERRUPTIBLE, 0, 0,
3970 				ext4_wait_dax_page(ei));
3971 	} while (error == 0);
3972 
3973 	return error;
3974 }
3975 
3976 /*
3977  * ext4_punch_hole: punches a hole in a file by releasing the blocks
3978  * associated with the given offset and length
3979  *
3980  * @inode:  File inode
3981  * @offset: The offset where the hole will begin
3982  * @len:    The length of the hole
3983  *
3984  * Returns: 0 on success or negative on failure
3985  */
3986 
3987 int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length)
3988 {
3989 	struct super_block *sb = inode->i_sb;
3990 	ext4_lblk_t first_block, stop_block;
3991 	struct address_space *mapping = inode->i_mapping;
3992 	loff_t first_block_offset, last_block_offset;
3993 	handle_t *handle;
3994 	unsigned int credits;
3995 	int ret = 0, ret2 = 0;
3996 
3997 	trace_ext4_punch_hole(inode, offset, length, 0);
3998 
3999 	ext4_clear_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
4000 	if (ext4_has_inline_data(inode)) {
4001 		down_write(&EXT4_I(inode)->i_mmap_sem);
4002 		ret = ext4_convert_inline_data(inode);
4003 		up_write(&EXT4_I(inode)->i_mmap_sem);
4004 		if (ret)
4005 			return ret;
4006 	}
4007 
4008 	/*
4009 	 * Write out all dirty pages to avoid race conditions
4010 	 * Then release them.
4011 	 */
4012 	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
4013 		ret = filemap_write_and_wait_range(mapping, offset,
4014 						   offset + length - 1);
4015 		if (ret)
4016 			return ret;
4017 	}
4018 
4019 	inode_lock(inode);
4020 
4021 	/* No need to punch hole beyond i_size */
4022 	if (offset >= inode->i_size)
4023 		goto out_mutex;
4024 
4025 	/*
4026 	 * If the hole extends beyond i_size, set the hole
4027 	 * to end after the page that contains i_size
4028 	 */
4029 	if (offset + length > inode->i_size) {
4030 		length = inode->i_size +
4031 		   PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
4032 		   offset;
4033 	}
4034 
4035 	if (offset & (sb->s_blocksize - 1) ||
4036 	    (offset + length) & (sb->s_blocksize - 1)) {
4037 		/*
4038 		 * Attach jinode to inode for jbd2 if we do any zeroing of
4039 		 * partial block
4040 		 */
4041 		ret = ext4_inode_attach_jinode(inode);
4042 		if (ret < 0)
4043 			goto out_mutex;
4044 
4045 	}
4046 
4047 	/* Wait all existing dio workers, newcomers will block on i_mutex */
4048 	inode_dio_wait(inode);
4049 
4050 	/*
4051 	 * Prevent page faults from reinstantiating pages we have released from
4052 	 * page cache.
4053 	 */
4054 	down_write(&EXT4_I(inode)->i_mmap_sem);
4055 
4056 	ret = ext4_break_layouts(inode);
4057 	if (ret)
4058 		goto out_dio;
4059 
4060 	first_block_offset = round_up(offset, sb->s_blocksize);
4061 	last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
4062 
4063 	/* Now release the pages and zero block aligned part of pages*/
4064 	if (last_block_offset > first_block_offset) {
4065 		ret = ext4_update_disksize_before_punch(inode, offset, length);
4066 		if (ret)
4067 			goto out_dio;
4068 		truncate_pagecache_range(inode, first_block_offset,
4069 					 last_block_offset);
4070 	}
4071 
4072 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4073 		credits = ext4_writepage_trans_blocks(inode);
4074 	else
4075 		credits = ext4_blocks_for_truncate(inode);
4076 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4077 	if (IS_ERR(handle)) {
4078 		ret = PTR_ERR(handle);
4079 		ext4_std_error(sb, ret);
4080 		goto out_dio;
4081 	}
4082 
4083 	ret = ext4_zero_partial_blocks(handle, inode, offset,
4084 				       length);
4085 	if (ret)
4086 		goto out_stop;
4087 
4088 	first_block = (offset + sb->s_blocksize - 1) >>
4089 		EXT4_BLOCK_SIZE_BITS(sb);
4090 	stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
4091 
4092 	/* If there are blocks to remove, do it */
4093 	if (stop_block > first_block) {
4094 
4095 		down_write(&EXT4_I(inode)->i_data_sem);
4096 		ext4_discard_preallocations(inode, 0);
4097 
4098 		ret = ext4_es_remove_extent(inode, first_block,
4099 					    stop_block - first_block);
4100 		if (ret) {
4101 			up_write(&EXT4_I(inode)->i_data_sem);
4102 			goto out_stop;
4103 		}
4104 
4105 		if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4106 			ret = ext4_ext_remove_space(inode, first_block,
4107 						    stop_block - 1);
4108 		else
4109 			ret = ext4_ind_remove_space(handle, inode, first_block,
4110 						    stop_block);
4111 
4112 		up_write(&EXT4_I(inode)->i_data_sem);
4113 	}
4114 	ext4_fc_track_range(handle, inode, first_block, stop_block);
4115 	if (IS_SYNC(inode))
4116 		ext4_handle_sync(handle);
4117 
4118 	inode->i_mtime = inode->i_ctime = current_time(inode);
4119 	ret2 = ext4_mark_inode_dirty(handle, inode);
4120 	if (unlikely(ret2))
4121 		ret = ret2;
4122 	if (ret >= 0)
4123 		ext4_update_inode_fsync_trans(handle, inode, 1);
4124 out_stop:
4125 	ext4_journal_stop(handle);
4126 out_dio:
4127 	up_write(&EXT4_I(inode)->i_mmap_sem);
4128 out_mutex:
4129 	inode_unlock(inode);
4130 	return ret;
4131 }
4132 
4133 int ext4_inode_attach_jinode(struct inode *inode)
4134 {
4135 	struct ext4_inode_info *ei = EXT4_I(inode);
4136 	struct jbd2_inode *jinode;
4137 
4138 	if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4139 		return 0;
4140 
4141 	jinode = jbd2_alloc_inode(GFP_KERNEL);
4142 	spin_lock(&inode->i_lock);
4143 	if (!ei->jinode) {
4144 		if (!jinode) {
4145 			spin_unlock(&inode->i_lock);
4146 			return -ENOMEM;
4147 		}
4148 		ei->jinode = jinode;
4149 		jbd2_journal_init_jbd_inode(ei->jinode, inode);
4150 		jinode = NULL;
4151 	}
4152 	spin_unlock(&inode->i_lock);
4153 	if (unlikely(jinode != NULL))
4154 		jbd2_free_inode(jinode);
4155 	return 0;
4156 }
4157 
4158 /*
4159  * ext4_truncate()
4160  *
4161  * We block out ext4_get_block() block instantiations across the entire
4162  * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4163  * simultaneously on behalf of the same inode.
4164  *
4165  * As we work through the truncate and commit bits of it to the journal there
4166  * is one core, guiding principle: the file's tree must always be consistent on
4167  * disk.  We must be able to restart the truncate after a crash.
4168  *
4169  * The file's tree may be transiently inconsistent in memory (although it
4170  * probably isn't), but whenever we close off and commit a journal transaction,
4171  * the contents of (the filesystem + the journal) must be consistent and
4172  * restartable.  It's pretty simple, really: bottom up, right to left (although
4173  * left-to-right works OK too).
4174  *
4175  * Note that at recovery time, journal replay occurs *before* the restart of
4176  * truncate against the orphan inode list.
4177  *
4178  * The committed inode has the new, desired i_size (which is the same as
4179  * i_disksize in this case).  After a crash, ext4_orphan_cleanup() will see
4180  * that this inode's truncate did not complete and it will again call
4181  * ext4_truncate() to have another go.  So there will be instantiated blocks
4182  * to the right of the truncation point in a crashed ext4 filesystem.  But
4183  * that's fine - as long as they are linked from the inode, the post-crash
4184  * ext4_truncate() run will find them and release them.
4185  */
4186 int ext4_truncate(struct inode *inode)
4187 {
4188 	struct ext4_inode_info *ei = EXT4_I(inode);
4189 	unsigned int credits;
4190 	int err = 0, err2;
4191 	handle_t *handle;
4192 	struct address_space *mapping = inode->i_mapping;
4193 
4194 	/*
4195 	 * There is a possibility that we're either freeing the inode
4196 	 * or it's a completely new inode. In those cases we might not
4197 	 * have i_mutex locked because it's not necessary.
4198 	 */
4199 	if (!(inode->i_state & (I_NEW|I_FREEING)))
4200 		WARN_ON(!inode_is_locked(inode));
4201 	trace_ext4_truncate_enter(inode);
4202 
4203 	if (!ext4_can_truncate(inode))
4204 		goto out_trace;
4205 
4206 	if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
4207 		ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
4208 
4209 	if (ext4_has_inline_data(inode)) {
4210 		int has_inline = 1;
4211 
4212 		err = ext4_inline_data_truncate(inode, &has_inline);
4213 		if (err || has_inline)
4214 			goto out_trace;
4215 	}
4216 
4217 	/* If we zero-out tail of the page, we have to create jinode for jbd2 */
4218 	if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4219 		if (ext4_inode_attach_jinode(inode) < 0)
4220 			goto out_trace;
4221 	}
4222 
4223 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4224 		credits = ext4_writepage_trans_blocks(inode);
4225 	else
4226 		credits = ext4_blocks_for_truncate(inode);
4227 
4228 	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4229 	if (IS_ERR(handle)) {
4230 		err = PTR_ERR(handle);
4231 		goto out_trace;
4232 	}
4233 
4234 	if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4235 		ext4_block_truncate_page(handle, mapping, inode->i_size);
4236 
4237 	/*
4238 	 * We add the inode to the orphan list, so that if this
4239 	 * truncate spans multiple transactions, and we crash, we will
4240 	 * resume the truncate when the filesystem recovers.  It also
4241 	 * marks the inode dirty, to catch the new size.
4242 	 *
4243 	 * Implication: the file must always be in a sane, consistent
4244 	 * truncatable state while each transaction commits.
4245 	 */
4246 	err = ext4_orphan_add(handle, inode);
4247 	if (err)
4248 		goto out_stop;
4249 
4250 	down_write(&EXT4_I(inode)->i_data_sem);
4251 
4252 	ext4_discard_preallocations(inode, 0);
4253 
4254 	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4255 		err = ext4_ext_truncate(handle, inode);
4256 	else
4257 		ext4_ind_truncate(handle, inode);
4258 
4259 	up_write(&ei->i_data_sem);
4260 	if (err)
4261 		goto out_stop;
4262 
4263 	if (IS_SYNC(inode))
4264 		ext4_handle_sync(handle);
4265 
4266 out_stop:
4267 	/*
4268 	 * If this was a simple ftruncate() and the file will remain alive,
4269 	 * then we need to clear up the orphan record which we created above.
4270 	 * However, if this was a real unlink then we were called by
4271 	 * ext4_evict_inode(), and we allow that function to clean up the
4272 	 * orphan info for us.
4273 	 */
4274 	if (inode->i_nlink)
4275 		ext4_orphan_del(handle, inode);
4276 
4277 	inode->i_mtime = inode->i_ctime = current_time(inode);
4278 	err2 = ext4_mark_inode_dirty(handle, inode);
4279 	if (unlikely(err2 && !err))
4280 		err = err2;
4281 	ext4_journal_stop(handle);
4282 
4283 out_trace:
4284 	trace_ext4_truncate_exit(inode);
4285 	return err;
4286 }
4287 
4288 /*
4289  * ext4_get_inode_loc returns with an extra refcount against the inode's
4290  * underlying buffer_head on success. If 'in_mem' is true, we have all
4291  * data in memory that is needed to recreate the on-disk version of this
4292  * inode.
4293  */
4294 static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino,
4295 				struct ext4_iloc *iloc, int in_mem,
4296 				ext4_fsblk_t *ret_block)
4297 {
4298 	struct ext4_group_desc	*gdp;
4299 	struct buffer_head	*bh;
4300 	ext4_fsblk_t		block;
4301 	struct blk_plug		plug;
4302 	int			inodes_per_block, inode_offset;
4303 
4304 	iloc->bh = NULL;
4305 	if (ino < EXT4_ROOT_INO ||
4306 	    ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
4307 		return -EFSCORRUPTED;
4308 
4309 	iloc->block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
4310 	gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4311 	if (!gdp)
4312 		return -EIO;
4313 
4314 	/*
4315 	 * Figure out the offset within the block group inode table
4316 	 */
4317 	inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4318 	inode_offset = ((ino - 1) %
4319 			EXT4_INODES_PER_GROUP(sb));
4320 	block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4321 	iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4322 
4323 	bh = sb_getblk(sb, block);
4324 	if (unlikely(!bh))
4325 		return -ENOMEM;
4326 	if (ext4_simulate_fail(sb, EXT4_SIM_INODE_EIO))
4327 		goto simulate_eio;
4328 	if (!buffer_uptodate(bh)) {
4329 		lock_buffer(bh);
4330 
4331 		if (ext4_buffer_uptodate(bh)) {
4332 			/* someone brought it uptodate while we waited */
4333 			unlock_buffer(bh);
4334 			goto has_buffer;
4335 		}
4336 
4337 		/*
4338 		 * If we have all information of the inode in memory and this
4339 		 * is the only valid inode in the block, we need not read the
4340 		 * block.
4341 		 */
4342 		if (in_mem) {
4343 			struct buffer_head *bitmap_bh;
4344 			int i, start;
4345 
4346 			start = inode_offset & ~(inodes_per_block - 1);
4347 
4348 			/* Is the inode bitmap in cache? */
4349 			bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4350 			if (unlikely(!bitmap_bh))
4351 				goto make_io;
4352 
4353 			/*
4354 			 * If the inode bitmap isn't in cache then the
4355 			 * optimisation may end up performing two reads instead
4356 			 * of one, so skip it.
4357 			 */
4358 			if (!buffer_uptodate(bitmap_bh)) {
4359 				brelse(bitmap_bh);
4360 				goto make_io;
4361 			}
4362 			for (i = start; i < start + inodes_per_block; i++) {
4363 				if (i == inode_offset)
4364 					continue;
4365 				if (ext4_test_bit(i, bitmap_bh->b_data))
4366 					break;
4367 			}
4368 			brelse(bitmap_bh);
4369 			if (i == start + inodes_per_block) {
4370 				/* all other inodes are free, so skip I/O */
4371 				memset(bh->b_data, 0, bh->b_size);
4372 				set_buffer_uptodate(bh);
4373 				unlock_buffer(bh);
4374 				goto has_buffer;
4375 			}
4376 		}
4377 
4378 make_io:
4379 		/*
4380 		 * If we need to do any I/O, try to pre-readahead extra
4381 		 * blocks from the inode table.
4382 		 */
4383 		blk_start_plug(&plug);
4384 		if (EXT4_SB(sb)->s_inode_readahead_blks) {
4385 			ext4_fsblk_t b, end, table;
4386 			unsigned num;
4387 			__u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4388 
4389 			table = ext4_inode_table(sb, gdp);
4390 			/* s_inode_readahead_blks is always a power of 2 */
4391 			b = block & ~((ext4_fsblk_t) ra_blks - 1);
4392 			if (table > b)
4393 				b = table;
4394 			end = b + ra_blks;
4395 			num = EXT4_INODES_PER_GROUP(sb);
4396 			if (ext4_has_group_desc_csum(sb))
4397 				num -= ext4_itable_unused_count(sb, gdp);
4398 			table += num / inodes_per_block;
4399 			if (end > table)
4400 				end = table;
4401 			while (b <= end)
4402 				ext4_sb_breadahead_unmovable(sb, b++);
4403 		}
4404 
4405 		/*
4406 		 * There are other valid inodes in the buffer, this inode
4407 		 * has in-inode xattrs, or we don't have this inode in memory.
4408 		 * Read the block from disk.
4409 		 */
4410 		trace_ext4_load_inode(sb, ino);
4411 		ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO, NULL);
4412 		blk_finish_plug(&plug);
4413 		wait_on_buffer(bh);
4414 		if (!buffer_uptodate(bh)) {
4415 		simulate_eio:
4416 			if (ret_block)
4417 				*ret_block = block;
4418 			brelse(bh);
4419 			return -EIO;
4420 		}
4421 	}
4422 has_buffer:
4423 	iloc->bh = bh;
4424 	return 0;
4425 }
4426 
4427 static int __ext4_get_inode_loc_noinmem(struct inode *inode,
4428 					struct ext4_iloc *iloc)
4429 {
4430 	ext4_fsblk_t err_blk;
4431 	int ret;
4432 
4433 	ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, iloc, 0,
4434 					&err_blk);
4435 
4436 	if (ret == -EIO)
4437 		ext4_error_inode_block(inode, err_blk, EIO,
4438 					"unable to read itable block");
4439 
4440 	return ret;
4441 }
4442 
4443 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4444 {
4445 	ext4_fsblk_t err_blk;
4446 	int ret;
4447 
4448 	/* We have all inode data except xattrs in memory here. */
4449 	ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, iloc,
4450 		!ext4_test_inode_state(inode, EXT4_STATE_XATTR), &err_blk);
4451 
4452 	if (ret == -EIO)
4453 		ext4_error_inode_block(inode, err_blk, EIO,
4454 					"unable to read itable block");
4455 
4456 	return ret;
4457 }
4458 
4459 
4460 int ext4_get_fc_inode_loc(struct super_block *sb, unsigned long ino,
4461 			  struct ext4_iloc *iloc)
4462 {
4463 	return __ext4_get_inode_loc(sb, ino, iloc, 0, NULL);
4464 }
4465 
4466 static bool ext4_should_enable_dax(struct inode *inode)
4467 {
4468 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4469 
4470 	if (test_opt2(inode->i_sb, DAX_NEVER))
4471 		return false;
4472 	if (!S_ISREG(inode->i_mode))
4473 		return false;
4474 	if (ext4_should_journal_data(inode))
4475 		return false;
4476 	if (ext4_has_inline_data(inode))
4477 		return false;
4478 	if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT))
4479 		return false;
4480 	if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY))
4481 		return false;
4482 	if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags))
4483 		return false;
4484 	if (test_opt(inode->i_sb, DAX_ALWAYS))
4485 		return true;
4486 
4487 	return ext4_test_inode_flag(inode, EXT4_INODE_DAX);
4488 }
4489 
4490 void ext4_set_inode_flags(struct inode *inode, bool init)
4491 {
4492 	unsigned int flags = EXT4_I(inode)->i_flags;
4493 	unsigned int new_fl = 0;
4494 
4495 	WARN_ON_ONCE(IS_DAX(inode) && init);
4496 
4497 	if (flags & EXT4_SYNC_FL)
4498 		new_fl |= S_SYNC;
4499 	if (flags & EXT4_APPEND_FL)
4500 		new_fl |= S_APPEND;
4501 	if (flags & EXT4_IMMUTABLE_FL)
4502 		new_fl |= S_IMMUTABLE;
4503 	if (flags & EXT4_NOATIME_FL)
4504 		new_fl |= S_NOATIME;
4505 	if (flags & EXT4_DIRSYNC_FL)
4506 		new_fl |= S_DIRSYNC;
4507 
4508 	/* Because of the way inode_set_flags() works we must preserve S_DAX
4509 	 * here if already set. */
4510 	new_fl |= (inode->i_flags & S_DAX);
4511 	if (init && ext4_should_enable_dax(inode))
4512 		new_fl |= S_DAX;
4513 
4514 	if (flags & EXT4_ENCRYPT_FL)
4515 		new_fl |= S_ENCRYPTED;
4516 	if (flags & EXT4_CASEFOLD_FL)
4517 		new_fl |= S_CASEFOLD;
4518 	if (flags & EXT4_VERITY_FL)
4519 		new_fl |= S_VERITY;
4520 	inode_set_flags(inode, new_fl,
4521 			S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX|
4522 			S_ENCRYPTED|S_CASEFOLD|S_VERITY);
4523 }
4524 
4525 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4526 				  struct ext4_inode_info *ei)
4527 {
4528 	blkcnt_t i_blocks ;
4529 	struct inode *inode = &(ei->vfs_inode);
4530 	struct super_block *sb = inode->i_sb;
4531 
4532 	if (ext4_has_feature_huge_file(sb)) {
4533 		/* we are using combined 48 bit field */
4534 		i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4535 					le32_to_cpu(raw_inode->i_blocks_lo);
4536 		if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
4537 			/* i_blocks represent file system block size */
4538 			return i_blocks  << (inode->i_blkbits - 9);
4539 		} else {
4540 			return i_blocks;
4541 		}
4542 	} else {
4543 		return le32_to_cpu(raw_inode->i_blocks_lo);
4544 	}
4545 }
4546 
4547 static inline int ext4_iget_extra_inode(struct inode *inode,
4548 					 struct ext4_inode *raw_inode,
4549 					 struct ext4_inode_info *ei)
4550 {
4551 	__le32 *magic = (void *)raw_inode +
4552 			EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4553 
4554 	if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize + sizeof(__le32) <=
4555 	    EXT4_INODE_SIZE(inode->i_sb) &&
4556 	    *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4557 		ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4558 		return ext4_find_inline_data_nolock(inode);
4559 	} else
4560 		EXT4_I(inode)->i_inline_off = 0;
4561 	return 0;
4562 }
4563 
4564 int ext4_get_projid(struct inode *inode, kprojid_t *projid)
4565 {
4566 	if (!ext4_has_feature_project(inode->i_sb))
4567 		return -EOPNOTSUPP;
4568 	*projid = EXT4_I(inode)->i_projid;
4569 	return 0;
4570 }
4571 
4572 /*
4573  * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of
4574  * refcount in i_version, so use raw values if inode has EXT4_EA_INODE_FL flag
4575  * set.
4576  */
4577 static inline void ext4_inode_set_iversion_queried(struct inode *inode, u64 val)
4578 {
4579 	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4580 		inode_set_iversion_raw(inode, val);
4581 	else
4582 		inode_set_iversion_queried(inode, val);
4583 }
4584 static inline u64 ext4_inode_peek_iversion(const struct inode *inode)
4585 {
4586 	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4587 		return inode_peek_iversion_raw(inode);
4588 	else
4589 		return inode_peek_iversion(inode);
4590 }
4591 
4592 struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
4593 			  ext4_iget_flags flags, const char *function,
4594 			  unsigned int line)
4595 {
4596 	struct ext4_iloc iloc;
4597 	struct ext4_inode *raw_inode;
4598 	struct ext4_inode_info *ei;
4599 	struct inode *inode;
4600 	journal_t *journal = EXT4_SB(sb)->s_journal;
4601 	long ret;
4602 	loff_t size;
4603 	int block;
4604 	uid_t i_uid;
4605 	gid_t i_gid;
4606 	projid_t i_projid;
4607 
4608 	if ((!(flags & EXT4_IGET_SPECIAL) &&
4609 	     (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)) ||
4610 	    (ino < EXT4_ROOT_INO) ||
4611 	    (ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))) {
4612 		if (flags & EXT4_IGET_HANDLE)
4613 			return ERR_PTR(-ESTALE);
4614 		__ext4_error(sb, function, line, EFSCORRUPTED, 0,
4615 			     "inode #%lu: comm %s: iget: illegal inode #",
4616 			     ino, current->comm);
4617 		return ERR_PTR(-EFSCORRUPTED);
4618 	}
4619 
4620 	inode = iget_locked(sb, ino);
4621 	if (!inode)
4622 		return ERR_PTR(-ENOMEM);
4623 	if (!(inode->i_state & I_NEW))
4624 		return inode;
4625 
4626 	ei = EXT4_I(inode);
4627 	iloc.bh = NULL;
4628 
4629 	ret = __ext4_get_inode_loc_noinmem(inode, &iloc);
4630 	if (ret < 0)
4631 		goto bad_inode;
4632 	raw_inode = ext4_raw_inode(&iloc);
4633 
4634 	if ((ino == EXT4_ROOT_INO) && (raw_inode->i_links_count == 0)) {
4635 		ext4_error_inode(inode, function, line, 0,
4636 				 "iget: root inode unallocated");
4637 		ret = -EFSCORRUPTED;
4638 		goto bad_inode;
4639 	}
4640 
4641 	if ((flags & EXT4_IGET_HANDLE) &&
4642 	    (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
4643 		ret = -ESTALE;
4644 		goto bad_inode;
4645 	}
4646 
4647 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4648 		ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4649 		if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4650 			EXT4_INODE_SIZE(inode->i_sb) ||
4651 		    (ei->i_extra_isize & 3)) {
4652 			ext4_error_inode(inode, function, line, 0,
4653 					 "iget: bad extra_isize %u "
4654 					 "(inode size %u)",
4655 					 ei->i_extra_isize,
4656 					 EXT4_INODE_SIZE(inode->i_sb));
4657 			ret = -EFSCORRUPTED;
4658 			goto bad_inode;
4659 		}
4660 	} else
4661 		ei->i_extra_isize = 0;
4662 
4663 	/* Precompute checksum seed for inode metadata */
4664 	if (ext4_has_metadata_csum(sb)) {
4665 		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4666 		__u32 csum;
4667 		__le32 inum = cpu_to_le32(inode->i_ino);
4668 		__le32 gen = raw_inode->i_generation;
4669 		csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4670 				   sizeof(inum));
4671 		ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4672 					      sizeof(gen));
4673 	}
4674 
4675 	if ((!ext4_inode_csum_verify(inode, raw_inode, ei) ||
4676 	    ext4_simulate_fail(sb, EXT4_SIM_INODE_CRC)) &&
4677 	     (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY))) {
4678 		ext4_error_inode_err(inode, function, line, 0,
4679 				EFSBADCRC, "iget: checksum invalid");
4680 		ret = -EFSBADCRC;
4681 		goto bad_inode;
4682 	}
4683 
4684 	inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4685 	i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4686 	i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4687 	if (ext4_has_feature_project(sb) &&
4688 	    EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4689 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4690 		i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
4691 	else
4692 		i_projid = EXT4_DEF_PROJID;
4693 
4694 	if (!(test_opt(inode->i_sb, NO_UID32))) {
4695 		i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4696 		i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4697 	}
4698 	i_uid_write(inode, i_uid);
4699 	i_gid_write(inode, i_gid);
4700 	ei->i_projid = make_kprojid(&init_user_ns, i_projid);
4701 	set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4702 
4703 	ext4_clear_state_flags(ei);	/* Only relevant on 32-bit archs */
4704 	ei->i_inline_off = 0;
4705 	ei->i_dir_start_lookup = 0;
4706 	ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4707 	/* We now have enough fields to check if the inode was active or not.
4708 	 * This is needed because nfsd might try to access dead inodes
4709 	 * the test is that same one that e2fsck uses
4710 	 * NeilBrown 1999oct15
4711 	 */
4712 	if (inode->i_nlink == 0) {
4713 		if ((inode->i_mode == 0 ||
4714 		     !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4715 		    ino != EXT4_BOOT_LOADER_INO) {
4716 			/* this inode is deleted */
4717 			ret = -ESTALE;
4718 			goto bad_inode;
4719 		}
4720 		/* The only unlinked inodes we let through here have
4721 		 * valid i_mode and are being read by the orphan
4722 		 * recovery code: that's fine, we're about to complete
4723 		 * the process of deleting those.
4724 		 * OR it is the EXT4_BOOT_LOADER_INO which is
4725 		 * not initialized on a new filesystem. */
4726 	}
4727 	ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4728 	ext4_set_inode_flags(inode, true);
4729 	inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4730 	ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4731 	if (ext4_has_feature_64bit(sb))
4732 		ei->i_file_acl |=
4733 			((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4734 	inode->i_size = ext4_isize(sb, raw_inode);
4735 	if ((size = i_size_read(inode)) < 0) {
4736 		ext4_error_inode(inode, function, line, 0,
4737 				 "iget: bad i_size value: %lld", size);
4738 		ret = -EFSCORRUPTED;
4739 		goto bad_inode;
4740 	}
4741 	/*
4742 	 * If dir_index is not enabled but there's dir with INDEX flag set,
4743 	 * we'd normally treat htree data as empty space. But with metadata
4744 	 * checksumming that corrupts checksums so forbid that.
4745 	 */
4746 	if (!ext4_has_feature_dir_index(sb) && ext4_has_metadata_csum(sb) &&
4747 	    ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
4748 		ext4_error_inode(inode, function, line, 0,
4749 			 "iget: Dir with htree data on filesystem without dir_index feature.");
4750 		ret = -EFSCORRUPTED;
4751 		goto bad_inode;
4752 	}
4753 	ei->i_disksize = inode->i_size;
4754 #ifdef CONFIG_QUOTA
4755 	ei->i_reserved_quota = 0;
4756 #endif
4757 	inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4758 	ei->i_block_group = iloc.block_group;
4759 	ei->i_last_alloc_group = ~0;
4760 	/*
4761 	 * NOTE! The in-memory inode i_data array is in little-endian order
4762 	 * even on big-endian machines: we do NOT byteswap the block numbers!
4763 	 */
4764 	for (block = 0; block < EXT4_N_BLOCKS; block++)
4765 		ei->i_data[block] = raw_inode->i_block[block];
4766 	INIT_LIST_HEAD(&ei->i_orphan);
4767 	ext4_fc_init_inode(&ei->vfs_inode);
4768 
4769 	/*
4770 	 * Set transaction id's of transactions that have to be committed
4771 	 * to finish f[data]sync. We set them to currently running transaction
4772 	 * as we cannot be sure that the inode or some of its metadata isn't
4773 	 * part of the transaction - the inode could have been reclaimed and
4774 	 * now it is reread from disk.
4775 	 */
4776 	if (journal) {
4777 		transaction_t *transaction;
4778 		tid_t tid;
4779 
4780 		read_lock(&journal->j_state_lock);
4781 		if (journal->j_running_transaction)
4782 			transaction = journal->j_running_transaction;
4783 		else
4784 			transaction = journal->j_committing_transaction;
4785 		if (transaction)
4786 			tid = transaction->t_tid;
4787 		else
4788 			tid = journal->j_commit_sequence;
4789 		read_unlock(&journal->j_state_lock);
4790 		ei->i_sync_tid = tid;
4791 		ei->i_datasync_tid = tid;
4792 	}
4793 
4794 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4795 		if (ei->i_extra_isize == 0) {
4796 			/* The extra space is currently unused. Use it. */
4797 			BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
4798 			ei->i_extra_isize = sizeof(struct ext4_inode) -
4799 					    EXT4_GOOD_OLD_INODE_SIZE;
4800 		} else {
4801 			ret = ext4_iget_extra_inode(inode, raw_inode, ei);
4802 			if (ret)
4803 				goto bad_inode;
4804 		}
4805 	}
4806 
4807 	EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4808 	EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4809 	EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4810 	EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4811 
4812 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4813 		u64 ivers = le32_to_cpu(raw_inode->i_disk_version);
4814 
4815 		if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4816 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4817 				ivers |=
4818 		    (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4819 		}
4820 		ext4_inode_set_iversion_queried(inode, ivers);
4821 	}
4822 
4823 	ret = 0;
4824 	if (ei->i_file_acl &&
4825 	    !ext4_inode_block_valid(inode, ei->i_file_acl, 1)) {
4826 		ext4_error_inode(inode, function, line, 0,
4827 				 "iget: bad extended attribute block %llu",
4828 				 ei->i_file_acl);
4829 		ret = -EFSCORRUPTED;
4830 		goto bad_inode;
4831 	} else if (!ext4_has_inline_data(inode)) {
4832 		/* validate the block references in the inode */
4833 		if (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY) &&
4834 			(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4835 			(S_ISLNK(inode->i_mode) &&
4836 			!ext4_inode_is_fast_symlink(inode)))) {
4837 			if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4838 				ret = ext4_ext_check_inode(inode);
4839 			else
4840 				ret = ext4_ind_check_inode(inode);
4841 		}
4842 	}
4843 	if (ret)
4844 		goto bad_inode;
4845 
4846 	if (S_ISREG(inode->i_mode)) {
4847 		inode->i_op = &ext4_file_inode_operations;
4848 		inode->i_fop = &ext4_file_operations;
4849 		ext4_set_aops(inode);
4850 	} else if (S_ISDIR(inode->i_mode)) {
4851 		inode->i_op = &ext4_dir_inode_operations;
4852 		inode->i_fop = &ext4_dir_operations;
4853 	} else if (S_ISLNK(inode->i_mode)) {
4854 		/* VFS does not allow setting these so must be corruption */
4855 		if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
4856 			ext4_error_inode(inode, function, line, 0,
4857 					 "iget: immutable or append flags "
4858 					 "not allowed on symlinks");
4859 			ret = -EFSCORRUPTED;
4860 			goto bad_inode;
4861 		}
4862 		if (IS_ENCRYPTED(inode)) {
4863 			inode->i_op = &ext4_encrypted_symlink_inode_operations;
4864 			ext4_set_aops(inode);
4865 		} else if (ext4_inode_is_fast_symlink(inode)) {
4866 			inode->i_link = (char *)ei->i_data;
4867 			inode->i_op = &ext4_fast_symlink_inode_operations;
4868 			nd_terminate_link(ei->i_data, inode->i_size,
4869 				sizeof(ei->i_data) - 1);
4870 		} else {
4871 			inode->i_op = &ext4_symlink_inode_operations;
4872 			ext4_set_aops(inode);
4873 		}
4874 		inode_nohighmem(inode);
4875 	} else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4876 	      S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4877 		inode->i_op = &ext4_special_inode_operations;
4878 		if (raw_inode->i_block[0])
4879 			init_special_inode(inode, inode->i_mode,
4880 			   old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4881 		else
4882 			init_special_inode(inode, inode->i_mode,
4883 			   new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4884 	} else if (ino == EXT4_BOOT_LOADER_INO) {
4885 		make_bad_inode(inode);
4886 	} else {
4887 		ret = -EFSCORRUPTED;
4888 		ext4_error_inode(inode, function, line, 0,
4889 				 "iget: bogus i_mode (%o)", inode->i_mode);
4890 		goto bad_inode;
4891 	}
4892 	if (IS_CASEFOLDED(inode) && !ext4_has_feature_casefold(inode->i_sb))
4893 		ext4_error_inode(inode, function, line, 0,
4894 				 "casefold flag without casefold feature");
4895 	brelse(iloc.bh);
4896 
4897 	unlock_new_inode(inode);
4898 	return inode;
4899 
4900 bad_inode:
4901 	brelse(iloc.bh);
4902 	iget_failed(inode);
4903 	return ERR_PTR(ret);
4904 }
4905 
4906 static int ext4_inode_blocks_set(handle_t *handle,
4907 				struct ext4_inode *raw_inode,
4908 				struct ext4_inode_info *ei)
4909 {
4910 	struct inode *inode = &(ei->vfs_inode);
4911 	u64 i_blocks = READ_ONCE(inode->i_blocks);
4912 	struct super_block *sb = inode->i_sb;
4913 
4914 	if (i_blocks <= ~0U) {
4915 		/*
4916 		 * i_blocks can be represented in a 32 bit variable
4917 		 * as multiple of 512 bytes
4918 		 */
4919 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
4920 		raw_inode->i_blocks_high = 0;
4921 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4922 		return 0;
4923 	}
4924 	if (!ext4_has_feature_huge_file(sb))
4925 		return -EFBIG;
4926 
4927 	if (i_blocks <= 0xffffffffffffULL) {
4928 		/*
4929 		 * i_blocks can be represented in a 48 bit variable
4930 		 * as multiple of 512 bytes
4931 		 */
4932 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
4933 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4934 		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4935 	} else {
4936 		ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4937 		/* i_block is stored in file system block size */
4938 		i_blocks = i_blocks >> (inode->i_blkbits - 9);
4939 		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
4940 		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4941 	}
4942 	return 0;
4943 }
4944 
4945 static void __ext4_update_other_inode_time(struct super_block *sb,
4946 					   unsigned long orig_ino,
4947 					   unsigned long ino,
4948 					   struct ext4_inode *raw_inode)
4949 {
4950 	struct inode *inode;
4951 
4952 	inode = find_inode_by_ino_rcu(sb, ino);
4953 	if (!inode)
4954 		return;
4955 
4956 	if ((inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
4957 			       I_DIRTY_INODE)) ||
4958 	    ((inode->i_state & I_DIRTY_TIME) == 0))
4959 		return;
4960 
4961 	spin_lock(&inode->i_lock);
4962 	if (((inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
4963 				I_DIRTY_INODE)) == 0) &&
4964 	    (inode->i_state & I_DIRTY_TIME)) {
4965 		struct ext4_inode_info	*ei = EXT4_I(inode);
4966 
4967 		inode->i_state &= ~I_DIRTY_TIME;
4968 		spin_unlock(&inode->i_lock);
4969 
4970 		spin_lock(&ei->i_raw_lock);
4971 		EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4972 		EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4973 		EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4974 		ext4_inode_csum_set(inode, raw_inode, ei);
4975 		spin_unlock(&ei->i_raw_lock);
4976 		trace_ext4_other_inode_update_time(inode, orig_ino);
4977 		return;
4978 	}
4979 	spin_unlock(&inode->i_lock);
4980 }
4981 
4982 /*
4983  * Opportunistically update the other time fields for other inodes in
4984  * the same inode table block.
4985  */
4986 static void ext4_update_other_inodes_time(struct super_block *sb,
4987 					  unsigned long orig_ino, char *buf)
4988 {
4989 	unsigned long ino;
4990 	int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4991 	int inode_size = EXT4_INODE_SIZE(sb);
4992 
4993 	/*
4994 	 * Calculate the first inode in the inode table block.  Inode
4995 	 * numbers are one-based.  That is, the first inode in a block
4996 	 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
4997 	 */
4998 	ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
4999 	rcu_read_lock();
5000 	for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
5001 		if (ino == orig_ino)
5002 			continue;
5003 		__ext4_update_other_inode_time(sb, orig_ino, ino,
5004 					       (struct ext4_inode *)buf);
5005 	}
5006 	rcu_read_unlock();
5007 }
5008 
5009 /*
5010  * Post the struct inode info into an on-disk inode location in the
5011  * buffer-cache.  This gobbles the caller's reference to the
5012  * buffer_head in the inode location struct.
5013  *
5014  * The caller must have write access to iloc->bh.
5015  */
5016 static int ext4_do_update_inode(handle_t *handle,
5017 				struct inode *inode,
5018 				struct ext4_iloc *iloc)
5019 {
5020 	struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5021 	struct ext4_inode_info *ei = EXT4_I(inode);
5022 	struct buffer_head *bh = iloc->bh;
5023 	struct super_block *sb = inode->i_sb;
5024 	int err = 0, rc, block;
5025 	int need_datasync = 0, set_large_file = 0;
5026 	uid_t i_uid;
5027 	gid_t i_gid;
5028 	projid_t i_projid;
5029 
5030 	spin_lock(&ei->i_raw_lock);
5031 
5032 	/* For fields not tracked in the in-memory inode,
5033 	 * initialise them to zero for new inodes. */
5034 	if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5035 		memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5036 
5037 	err = ext4_inode_blocks_set(handle, raw_inode, ei);
5038 	if (err) {
5039 		spin_unlock(&ei->i_raw_lock);
5040 		goto out_brelse;
5041 	}
5042 
5043 	raw_inode->i_mode = cpu_to_le16(inode->i_mode);
5044 	i_uid = i_uid_read(inode);
5045 	i_gid = i_gid_read(inode);
5046 	i_projid = from_kprojid(&init_user_ns, ei->i_projid);
5047 	if (!(test_opt(inode->i_sb, NO_UID32))) {
5048 		raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
5049 		raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
5050 /*
5051  * Fix up interoperability with old kernels. Otherwise, old inodes get
5052  * re-used with the upper 16 bits of the uid/gid intact
5053  */
5054 		if (ei->i_dtime && list_empty(&ei->i_orphan)) {
5055 			raw_inode->i_uid_high = 0;
5056 			raw_inode->i_gid_high = 0;
5057 		} else {
5058 			raw_inode->i_uid_high =
5059 				cpu_to_le16(high_16_bits(i_uid));
5060 			raw_inode->i_gid_high =
5061 				cpu_to_le16(high_16_bits(i_gid));
5062 		}
5063 	} else {
5064 		raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
5065 		raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
5066 		raw_inode->i_uid_high = 0;
5067 		raw_inode->i_gid_high = 0;
5068 	}
5069 	raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
5070 
5071 	EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
5072 	EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
5073 	EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
5074 	EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
5075 
5076 	raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
5077 	raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
5078 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
5079 		raw_inode->i_file_acl_high =
5080 			cpu_to_le16(ei->i_file_acl >> 32);
5081 	raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
5082 	if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode)) {
5083 		ext4_isize_set(raw_inode, ei->i_disksize);
5084 		need_datasync = 1;
5085 	}
5086 	if (ei->i_disksize > 0x7fffffffULL) {
5087 		if (!ext4_has_feature_large_file(sb) ||
5088 				EXT4_SB(sb)->s_es->s_rev_level ==
5089 		    cpu_to_le32(EXT4_GOOD_OLD_REV))
5090 			set_large_file = 1;
5091 	}
5092 	raw_inode->i_generation = cpu_to_le32(inode->i_generation);
5093 	if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
5094 		if (old_valid_dev(inode->i_rdev)) {
5095 			raw_inode->i_block[0] =
5096 				cpu_to_le32(old_encode_dev(inode->i_rdev));
5097 			raw_inode->i_block[1] = 0;
5098 		} else {
5099 			raw_inode->i_block[0] = 0;
5100 			raw_inode->i_block[1] =
5101 				cpu_to_le32(new_encode_dev(inode->i_rdev));
5102 			raw_inode->i_block[2] = 0;
5103 		}
5104 	} else if (!ext4_has_inline_data(inode)) {
5105 		for (block = 0; block < EXT4_N_BLOCKS; block++)
5106 			raw_inode->i_block[block] = ei->i_data[block];
5107 	}
5108 
5109 	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
5110 		u64 ivers = ext4_inode_peek_iversion(inode);
5111 
5112 		raw_inode->i_disk_version = cpu_to_le32(ivers);
5113 		if (ei->i_extra_isize) {
5114 			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
5115 				raw_inode->i_version_hi =
5116 					cpu_to_le32(ivers >> 32);
5117 			raw_inode->i_extra_isize =
5118 				cpu_to_le16(ei->i_extra_isize);
5119 		}
5120 	}
5121 
5122 	BUG_ON(!ext4_has_feature_project(inode->i_sb) &&
5123 	       i_projid != EXT4_DEF_PROJID);
5124 
5125 	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
5126 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
5127 		raw_inode->i_projid = cpu_to_le32(i_projid);
5128 
5129 	ext4_inode_csum_set(inode, raw_inode, ei);
5130 	spin_unlock(&ei->i_raw_lock);
5131 	if (inode->i_sb->s_flags & SB_LAZYTIME)
5132 		ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5133 					      bh->b_data);
5134 
5135 	BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
5136 	rc = ext4_handle_dirty_metadata(handle, NULL, bh);
5137 	if (!err)
5138 		err = rc;
5139 	ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5140 	if (set_large_file) {
5141 		BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
5142 		err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh);
5143 		if (err)
5144 			goto out_brelse;
5145 		ext4_set_feature_large_file(sb);
5146 		ext4_handle_sync(handle);
5147 		err = ext4_handle_dirty_super(handle, sb);
5148 	}
5149 	ext4_update_inode_fsync_trans(handle, inode, need_datasync);
5150 out_brelse:
5151 	brelse(bh);
5152 	ext4_std_error(inode->i_sb, err);
5153 	return err;
5154 }
5155 
5156 /*
5157  * ext4_write_inode()
5158  *
5159  * We are called from a few places:
5160  *
5161  * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
5162  *   Here, there will be no transaction running. We wait for any running
5163  *   transaction to commit.
5164  *
5165  * - Within flush work (sys_sync(), kupdate and such).
5166  *   We wait on commit, if told to.
5167  *
5168  * - Within iput_final() -> write_inode_now()
5169  *   We wait on commit, if told to.
5170  *
5171  * In all cases it is actually safe for us to return without doing anything,
5172  * because the inode has been copied into a raw inode buffer in
5173  * ext4_mark_inode_dirty().  This is a correctness thing for WB_SYNC_ALL
5174  * writeback.
5175  *
5176  * Note that we are absolutely dependent upon all inode dirtiers doing the
5177  * right thing: they *must* call mark_inode_dirty() after dirtying info in
5178  * which we are interested.
5179  *
5180  * It would be a bug for them to not do this.  The code:
5181  *
5182  *	mark_inode_dirty(inode)
5183  *	stuff();
5184  *	inode->i_size = expr;
5185  *
5186  * is in error because write_inode() could occur while `stuff()' is running,
5187  * and the new i_size will be lost.  Plus the inode will no longer be on the
5188  * superblock's dirty inode list.
5189  */
5190 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5191 {
5192 	int err;
5193 
5194 	if (WARN_ON_ONCE(current->flags & PF_MEMALLOC) ||
5195 	    sb_rdonly(inode->i_sb))
5196 		return 0;
5197 
5198 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5199 		return -EIO;
5200 
5201 	if (EXT4_SB(inode->i_sb)->s_journal) {
5202 		if (ext4_journal_current_handle()) {
5203 			jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
5204 			dump_stack();
5205 			return -EIO;
5206 		}
5207 
5208 		/*
5209 		 * No need to force transaction in WB_SYNC_NONE mode. Also
5210 		 * ext4_sync_fs() will force the commit after everything is
5211 		 * written.
5212 		 */
5213 		if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
5214 			return 0;
5215 
5216 		err = ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal,
5217 						EXT4_I(inode)->i_sync_tid);
5218 	} else {
5219 		struct ext4_iloc iloc;
5220 
5221 		err = __ext4_get_inode_loc_noinmem(inode, &iloc);
5222 		if (err)
5223 			return err;
5224 		/*
5225 		 * sync(2) will flush the whole buffer cache. No need to do
5226 		 * it here separately for each inode.
5227 		 */
5228 		if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
5229 			sync_dirty_buffer(iloc.bh);
5230 		if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
5231 			ext4_error_inode_block(inode, iloc.bh->b_blocknr, EIO,
5232 					       "IO error syncing inode");
5233 			err = -EIO;
5234 		}
5235 		brelse(iloc.bh);
5236 	}
5237 	return err;
5238 }
5239 
5240 /*
5241  * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
5242  * buffers that are attached to a page stradding i_size and are undergoing
5243  * commit. In that case we have to wait for commit to finish and try again.
5244  */
5245 static void ext4_wait_for_tail_page_commit(struct inode *inode)
5246 {
5247 	struct page *page;
5248 	unsigned offset;
5249 	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
5250 	tid_t commit_tid = 0;
5251 	int ret;
5252 
5253 	offset = inode->i_size & (PAGE_SIZE - 1);
5254 	/*
5255 	 * If the page is fully truncated, we don't need to wait for any commit
5256 	 * (and we even should not as __ext4_journalled_invalidatepage() may
5257 	 * strip all buffers from the page but keep the page dirty which can then
5258 	 * confuse e.g. concurrent ext4_writepage() seeing dirty page without
5259 	 * buffers). Also we don't need to wait for any commit if all buffers in
5260 	 * the page remain valid. This is most beneficial for the common case of
5261 	 * blocksize == PAGESIZE.
5262 	 */
5263 	if (!offset || offset > (PAGE_SIZE - i_blocksize(inode)))
5264 		return;
5265 	while (1) {
5266 		page = find_lock_page(inode->i_mapping,
5267 				      inode->i_size >> PAGE_SHIFT);
5268 		if (!page)
5269 			return;
5270 		ret = __ext4_journalled_invalidatepage(page, offset,
5271 						PAGE_SIZE - offset);
5272 		unlock_page(page);
5273 		put_page(page);
5274 		if (ret != -EBUSY)
5275 			return;
5276 		commit_tid = 0;
5277 		read_lock(&journal->j_state_lock);
5278 		if (journal->j_committing_transaction)
5279 			commit_tid = journal->j_committing_transaction->t_tid;
5280 		read_unlock(&journal->j_state_lock);
5281 		if (commit_tid)
5282 			jbd2_log_wait_commit(journal, commit_tid);
5283 	}
5284 }
5285 
5286 /*
5287  * ext4_setattr()
5288  *
5289  * Called from notify_change.
5290  *
5291  * We want to trap VFS attempts to truncate the file as soon as
5292  * possible.  In particular, we want to make sure that when the VFS
5293  * shrinks i_size, we put the inode on the orphan list and modify
5294  * i_disksize immediately, so that during the subsequent flushing of
5295  * dirty pages and freeing of disk blocks, we can guarantee that any
5296  * commit will leave the blocks being flushed in an unused state on
5297  * disk.  (On recovery, the inode will get truncated and the blocks will
5298  * be freed, so we have a strong guarantee that no future commit will
5299  * leave these blocks visible to the user.)
5300  *
5301  * Another thing we have to assure is that if we are in ordered mode
5302  * and inode is still attached to the committing transaction, we must
5303  * we start writeout of all the dirty pages which are being truncated.
5304  * This way we are sure that all the data written in the previous
5305  * transaction are already on disk (truncate waits for pages under
5306  * writeback).
5307  *
5308  * Called with inode->i_mutex down.
5309  */
5310 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
5311 {
5312 	struct inode *inode = d_inode(dentry);
5313 	int error, rc = 0;
5314 	int orphan = 0;
5315 	const unsigned int ia_valid = attr->ia_valid;
5316 
5317 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5318 		return -EIO;
5319 
5320 	if (unlikely(IS_IMMUTABLE(inode)))
5321 		return -EPERM;
5322 
5323 	if (unlikely(IS_APPEND(inode) &&
5324 		     (ia_valid & (ATTR_MODE | ATTR_UID |
5325 				  ATTR_GID | ATTR_TIMES_SET))))
5326 		return -EPERM;
5327 
5328 	error = setattr_prepare(dentry, attr);
5329 	if (error)
5330 		return error;
5331 
5332 	error = fscrypt_prepare_setattr(dentry, attr);
5333 	if (error)
5334 		return error;
5335 
5336 	error = fsverity_prepare_setattr(dentry, attr);
5337 	if (error)
5338 		return error;
5339 
5340 	if (is_quota_modification(inode, attr)) {
5341 		error = dquot_initialize(inode);
5342 		if (error)
5343 			return error;
5344 	}
5345 	ext4_fc_start_update(inode);
5346 	if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
5347 	    (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
5348 		handle_t *handle;
5349 
5350 		/* (user+group)*(old+new) structure, inode write (sb,
5351 		 * inode block, ? - but truncate inode update has it) */
5352 		handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
5353 			(EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5354 			 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
5355 		if (IS_ERR(handle)) {
5356 			error = PTR_ERR(handle);
5357 			goto err_out;
5358 		}
5359 
5360 		/* dquot_transfer() calls back ext4_get_inode_usage() which
5361 		 * counts xattr inode references.
5362 		 */
5363 		down_read(&EXT4_I(inode)->xattr_sem);
5364 		error = dquot_transfer(inode, attr);
5365 		up_read(&EXT4_I(inode)->xattr_sem);
5366 
5367 		if (error) {
5368 			ext4_journal_stop(handle);
5369 			ext4_fc_stop_update(inode);
5370 			return error;
5371 		}
5372 		/* Update corresponding info in inode so that everything is in
5373 		 * one transaction */
5374 		if (attr->ia_valid & ATTR_UID)
5375 			inode->i_uid = attr->ia_uid;
5376 		if (attr->ia_valid & ATTR_GID)
5377 			inode->i_gid = attr->ia_gid;
5378 		error = ext4_mark_inode_dirty(handle, inode);
5379 		ext4_journal_stop(handle);
5380 		if (unlikely(error))
5381 			return error;
5382 	}
5383 
5384 	if (attr->ia_valid & ATTR_SIZE) {
5385 		handle_t *handle;
5386 		loff_t oldsize = inode->i_size;
5387 		int shrink = (attr->ia_size < inode->i_size);
5388 
5389 		if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5390 			struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5391 
5392 			if (attr->ia_size > sbi->s_bitmap_maxbytes) {
5393 				ext4_fc_stop_update(inode);
5394 				return -EFBIG;
5395 			}
5396 		}
5397 		if (!S_ISREG(inode->i_mode)) {
5398 			ext4_fc_stop_update(inode);
5399 			return -EINVAL;
5400 		}
5401 
5402 		if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
5403 			inode_inc_iversion(inode);
5404 
5405 		if (shrink) {
5406 			if (ext4_should_order_data(inode)) {
5407 				error = ext4_begin_ordered_truncate(inode,
5408 							    attr->ia_size);
5409 				if (error)
5410 					goto err_out;
5411 			}
5412 			/*
5413 			 * Blocks are going to be removed from the inode. Wait
5414 			 * for dio in flight.
5415 			 */
5416 			inode_dio_wait(inode);
5417 		}
5418 
5419 		down_write(&EXT4_I(inode)->i_mmap_sem);
5420 
5421 		rc = ext4_break_layouts(inode);
5422 		if (rc) {
5423 			up_write(&EXT4_I(inode)->i_mmap_sem);
5424 			goto err_out;
5425 		}
5426 
5427 		if (attr->ia_size != inode->i_size) {
5428 			handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5429 			if (IS_ERR(handle)) {
5430 				error = PTR_ERR(handle);
5431 				goto out_mmap_sem;
5432 			}
5433 			if (ext4_handle_valid(handle) && shrink) {
5434 				error = ext4_orphan_add(handle, inode);
5435 				orphan = 1;
5436 			}
5437 			/*
5438 			 * Update c/mtime on truncate up, ext4_truncate() will
5439 			 * update c/mtime in shrink case below
5440 			 */
5441 			if (!shrink) {
5442 				inode->i_mtime = current_time(inode);
5443 				inode->i_ctime = inode->i_mtime;
5444 			}
5445 
5446 			if (shrink)
5447 				ext4_fc_track_range(handle, inode,
5448 					(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5449 					inode->i_sb->s_blocksize_bits,
5450 					(oldsize > 0 ? oldsize - 1 : 0) >>
5451 					inode->i_sb->s_blocksize_bits);
5452 			else
5453 				ext4_fc_track_range(
5454 					handle, inode,
5455 					(oldsize > 0 ? oldsize - 1 : oldsize) >>
5456 					inode->i_sb->s_blocksize_bits,
5457 					(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5458 					inode->i_sb->s_blocksize_bits);
5459 
5460 			down_write(&EXT4_I(inode)->i_data_sem);
5461 			EXT4_I(inode)->i_disksize = attr->ia_size;
5462 			rc = ext4_mark_inode_dirty(handle, inode);
5463 			if (!error)
5464 				error = rc;
5465 			/*
5466 			 * We have to update i_size under i_data_sem together
5467 			 * with i_disksize to avoid races with writeback code
5468 			 * running ext4_wb_update_i_disksize().
5469 			 */
5470 			if (!error)
5471 				i_size_write(inode, attr->ia_size);
5472 			up_write(&EXT4_I(inode)->i_data_sem);
5473 			ext4_journal_stop(handle);
5474 			if (error)
5475 				goto out_mmap_sem;
5476 			if (!shrink) {
5477 				pagecache_isize_extended(inode, oldsize,
5478 							 inode->i_size);
5479 			} else if (ext4_should_journal_data(inode)) {
5480 				ext4_wait_for_tail_page_commit(inode);
5481 			}
5482 		}
5483 
5484 		/*
5485 		 * Truncate pagecache after we've waited for commit
5486 		 * in data=journal mode to make pages freeable.
5487 		 */
5488 		truncate_pagecache(inode, inode->i_size);
5489 		/*
5490 		 * Call ext4_truncate() even if i_size didn't change to
5491 		 * truncate possible preallocated blocks.
5492 		 */
5493 		if (attr->ia_size <= oldsize) {
5494 			rc = ext4_truncate(inode);
5495 			if (rc)
5496 				error = rc;
5497 		}
5498 out_mmap_sem:
5499 		up_write(&EXT4_I(inode)->i_mmap_sem);
5500 	}
5501 
5502 	if (!error) {
5503 		setattr_copy(inode, attr);
5504 		mark_inode_dirty(inode);
5505 	}
5506 
5507 	/*
5508 	 * If the call to ext4_truncate failed to get a transaction handle at
5509 	 * all, we need to clean up the in-core orphan list manually.
5510 	 */
5511 	if (orphan && inode->i_nlink)
5512 		ext4_orphan_del(NULL, inode);
5513 
5514 	if (!error && (ia_valid & ATTR_MODE))
5515 		rc = posix_acl_chmod(inode, inode->i_mode);
5516 
5517 err_out:
5518 	if  (error)
5519 		ext4_std_error(inode->i_sb, error);
5520 	if (!error)
5521 		error = rc;
5522 	ext4_fc_stop_update(inode);
5523 	return error;
5524 }
5525 
5526 int ext4_getattr(const struct path *path, struct kstat *stat,
5527 		 u32 request_mask, unsigned int query_flags)
5528 {
5529 	struct inode *inode = d_inode(path->dentry);
5530 	struct ext4_inode *raw_inode;
5531 	struct ext4_inode_info *ei = EXT4_I(inode);
5532 	unsigned int flags;
5533 
5534 	if ((request_mask & STATX_BTIME) &&
5535 	    EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
5536 		stat->result_mask |= STATX_BTIME;
5537 		stat->btime.tv_sec = ei->i_crtime.tv_sec;
5538 		stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
5539 	}
5540 
5541 	flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
5542 	if (flags & EXT4_APPEND_FL)
5543 		stat->attributes |= STATX_ATTR_APPEND;
5544 	if (flags & EXT4_COMPR_FL)
5545 		stat->attributes |= STATX_ATTR_COMPRESSED;
5546 	if (flags & EXT4_ENCRYPT_FL)
5547 		stat->attributes |= STATX_ATTR_ENCRYPTED;
5548 	if (flags & EXT4_IMMUTABLE_FL)
5549 		stat->attributes |= STATX_ATTR_IMMUTABLE;
5550 	if (flags & EXT4_NODUMP_FL)
5551 		stat->attributes |= STATX_ATTR_NODUMP;
5552 	if (flags & EXT4_VERITY_FL)
5553 		stat->attributes |= STATX_ATTR_VERITY;
5554 
5555 	stat->attributes_mask |= (STATX_ATTR_APPEND |
5556 				  STATX_ATTR_COMPRESSED |
5557 				  STATX_ATTR_ENCRYPTED |
5558 				  STATX_ATTR_IMMUTABLE |
5559 				  STATX_ATTR_NODUMP |
5560 				  STATX_ATTR_VERITY);
5561 
5562 	generic_fillattr(inode, stat);
5563 	return 0;
5564 }
5565 
5566 int ext4_file_getattr(const struct path *path, struct kstat *stat,
5567 		      u32 request_mask, unsigned int query_flags)
5568 {
5569 	struct inode *inode = d_inode(path->dentry);
5570 	u64 delalloc_blocks;
5571 
5572 	ext4_getattr(path, stat, request_mask, query_flags);
5573 
5574 	/*
5575 	 * If there is inline data in the inode, the inode will normally not
5576 	 * have data blocks allocated (it may have an external xattr block).
5577 	 * Report at least one sector for such files, so tools like tar, rsync,
5578 	 * others don't incorrectly think the file is completely sparse.
5579 	 */
5580 	if (unlikely(ext4_has_inline_data(inode)))
5581 		stat->blocks += (stat->size + 511) >> 9;
5582 
5583 	/*
5584 	 * We can't update i_blocks if the block allocation is delayed
5585 	 * otherwise in the case of system crash before the real block
5586 	 * allocation is done, we will have i_blocks inconsistent with
5587 	 * on-disk file blocks.
5588 	 * We always keep i_blocks updated together with real
5589 	 * allocation. But to not confuse with user, stat
5590 	 * will return the blocks that include the delayed allocation
5591 	 * blocks for this file.
5592 	 */
5593 	delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
5594 				   EXT4_I(inode)->i_reserved_data_blocks);
5595 	stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
5596 	return 0;
5597 }
5598 
5599 static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5600 				   int pextents)
5601 {
5602 	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5603 		return ext4_ind_trans_blocks(inode, lblocks);
5604 	return ext4_ext_index_trans_blocks(inode, pextents);
5605 }
5606 
5607 /*
5608  * Account for index blocks, block groups bitmaps and block group
5609  * descriptor blocks if modify datablocks and index blocks
5610  * worse case, the indexs blocks spread over different block groups
5611  *
5612  * If datablocks are discontiguous, they are possible to spread over
5613  * different block groups too. If they are contiguous, with flexbg,
5614  * they could still across block group boundary.
5615  *
5616  * Also account for superblock, inode, quota and xattr blocks
5617  */
5618 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5619 				  int pextents)
5620 {
5621 	ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
5622 	int gdpblocks;
5623 	int idxblocks;
5624 	int ret = 0;
5625 
5626 	/*
5627 	 * How many index blocks need to touch to map @lblocks logical blocks
5628 	 * to @pextents physical extents?
5629 	 */
5630 	idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5631 
5632 	ret = idxblocks;
5633 
5634 	/*
5635 	 * Now let's see how many group bitmaps and group descriptors need
5636 	 * to account
5637 	 */
5638 	groups = idxblocks + pextents;
5639 	gdpblocks = groups;
5640 	if (groups > ngroups)
5641 		groups = ngroups;
5642 	if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5643 		gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5644 
5645 	/* bitmaps and block group descriptor blocks */
5646 	ret += groups + gdpblocks;
5647 
5648 	/* Blocks for super block, inode, quota and xattr blocks */
5649 	ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5650 
5651 	return ret;
5652 }
5653 
5654 /*
5655  * Calculate the total number of credits to reserve to fit
5656  * the modification of a single pages into a single transaction,
5657  * which may include multiple chunks of block allocations.
5658  *
5659  * This could be called via ext4_write_begin()
5660  *
5661  * We need to consider the worse case, when
5662  * one new block per extent.
5663  */
5664 int ext4_writepage_trans_blocks(struct inode *inode)
5665 {
5666 	int bpp = ext4_journal_blocks_per_page(inode);
5667 	int ret;
5668 
5669 	ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5670 
5671 	/* Account for data blocks for journalled mode */
5672 	if (ext4_should_journal_data(inode))
5673 		ret += bpp;
5674 	return ret;
5675 }
5676 
5677 /*
5678  * Calculate the journal credits for a chunk of data modification.
5679  *
5680  * This is called from DIO, fallocate or whoever calling
5681  * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5682  *
5683  * journal buffers for data blocks are not included here, as DIO
5684  * and fallocate do no need to journal data buffers.
5685  */
5686 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5687 {
5688 	return ext4_meta_trans_blocks(inode, nrblocks, 1);
5689 }
5690 
5691 /*
5692  * The caller must have previously called ext4_reserve_inode_write().
5693  * Give this, we know that the caller already has write access to iloc->bh.
5694  */
5695 int ext4_mark_iloc_dirty(handle_t *handle,
5696 			 struct inode *inode, struct ext4_iloc *iloc)
5697 {
5698 	int err = 0;
5699 
5700 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
5701 		put_bh(iloc->bh);
5702 		return -EIO;
5703 	}
5704 	ext4_fc_track_inode(handle, inode);
5705 
5706 	if (IS_I_VERSION(inode))
5707 		inode_inc_iversion(inode);
5708 
5709 	/* the do_update_inode consumes one bh->b_count */
5710 	get_bh(iloc->bh);
5711 
5712 	/* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5713 	err = ext4_do_update_inode(handle, inode, iloc);
5714 	put_bh(iloc->bh);
5715 	return err;
5716 }
5717 
5718 /*
5719  * On success, We end up with an outstanding reference count against
5720  * iloc->bh.  This _must_ be cleaned up later.
5721  */
5722 
5723 int
5724 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5725 			 struct ext4_iloc *iloc)
5726 {
5727 	int err;
5728 
5729 	if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5730 		return -EIO;
5731 
5732 	err = ext4_get_inode_loc(inode, iloc);
5733 	if (!err) {
5734 		BUFFER_TRACE(iloc->bh, "get_write_access");
5735 		err = ext4_journal_get_write_access(handle, iloc->bh);
5736 		if (err) {
5737 			brelse(iloc->bh);
5738 			iloc->bh = NULL;
5739 		}
5740 	}
5741 	ext4_std_error(inode->i_sb, err);
5742 	return err;
5743 }
5744 
5745 static int __ext4_expand_extra_isize(struct inode *inode,
5746 				     unsigned int new_extra_isize,
5747 				     struct ext4_iloc *iloc,
5748 				     handle_t *handle, int *no_expand)
5749 {
5750 	struct ext4_inode *raw_inode;
5751 	struct ext4_xattr_ibody_header *header;
5752 	unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
5753 	struct ext4_inode_info *ei = EXT4_I(inode);
5754 	int error;
5755 
5756 	/* this was checked at iget time, but double check for good measure */
5757 	if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
5758 	    (ei->i_extra_isize & 3)) {
5759 		EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
5760 				 ei->i_extra_isize,
5761 				 EXT4_INODE_SIZE(inode->i_sb));
5762 		return -EFSCORRUPTED;
5763 	}
5764 	if ((new_extra_isize < ei->i_extra_isize) ||
5765 	    (new_extra_isize < 4) ||
5766 	    (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
5767 		return -EINVAL;	/* Should never happen */
5768 
5769 	raw_inode = ext4_raw_inode(iloc);
5770 
5771 	header = IHDR(inode, raw_inode);
5772 
5773 	/* No extended attributes present */
5774 	if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5775 	    header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5776 		memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
5777 		       EXT4_I(inode)->i_extra_isize, 0,
5778 		       new_extra_isize - EXT4_I(inode)->i_extra_isize);
5779 		EXT4_I(inode)->i_extra_isize = new_extra_isize;
5780 		return 0;
5781 	}
5782 
5783 	/* try to expand with EAs present */
5784 	error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
5785 					   raw_inode, handle);
5786 	if (error) {
5787 		/*
5788 		 * Inode size expansion failed; don't try again
5789 		 */
5790 		*no_expand = 1;
5791 	}
5792 
5793 	return error;
5794 }
5795 
5796 /*
5797  * Expand an inode by new_extra_isize bytes.
5798  * Returns 0 on success or negative error number on failure.
5799  */
5800 static int ext4_try_to_expand_extra_isize(struct inode *inode,
5801 					  unsigned int new_extra_isize,
5802 					  struct ext4_iloc iloc,
5803 					  handle_t *handle)
5804 {
5805 	int no_expand;
5806 	int error;
5807 
5808 	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
5809 		return -EOVERFLOW;
5810 
5811 	/*
5812 	 * In nojournal mode, we can immediately attempt to expand
5813 	 * the inode.  When journaled, we first need to obtain extra
5814 	 * buffer credits since we may write into the EA block
5815 	 * with this same handle. If journal_extend fails, then it will
5816 	 * only result in a minor loss of functionality for that inode.
5817 	 * If this is felt to be critical, then e2fsck should be run to
5818 	 * force a large enough s_min_extra_isize.
5819 	 */
5820 	if (ext4_journal_extend(handle,
5821 				EXT4_DATA_TRANS_BLOCKS(inode->i_sb), 0) != 0)
5822 		return -ENOSPC;
5823 
5824 	if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
5825 		return -EBUSY;
5826 
5827 	error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
5828 					  handle, &no_expand);
5829 	ext4_write_unlock_xattr(inode, &no_expand);
5830 
5831 	return error;
5832 }
5833 
5834 int ext4_expand_extra_isize(struct inode *inode,
5835 			    unsigned int new_extra_isize,
5836 			    struct ext4_iloc *iloc)
5837 {
5838 	handle_t *handle;
5839 	int no_expand;
5840 	int error, rc;
5841 
5842 	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5843 		brelse(iloc->bh);
5844 		return -EOVERFLOW;
5845 	}
5846 
5847 	handle = ext4_journal_start(inode, EXT4_HT_INODE,
5848 				    EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
5849 	if (IS_ERR(handle)) {
5850 		error = PTR_ERR(handle);
5851 		brelse(iloc->bh);
5852 		return error;
5853 	}
5854 
5855 	ext4_write_lock_xattr(inode, &no_expand);
5856 
5857 	BUFFER_TRACE(iloc->bh, "get_write_access");
5858 	error = ext4_journal_get_write_access(handle, iloc->bh);
5859 	if (error) {
5860 		brelse(iloc->bh);
5861 		goto out_unlock;
5862 	}
5863 
5864 	error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
5865 					  handle, &no_expand);
5866 
5867 	rc = ext4_mark_iloc_dirty(handle, inode, iloc);
5868 	if (!error)
5869 		error = rc;
5870 
5871 out_unlock:
5872 	ext4_write_unlock_xattr(inode, &no_expand);
5873 	ext4_journal_stop(handle);
5874 	return error;
5875 }
5876 
5877 /*
5878  * What we do here is to mark the in-core inode as clean with respect to inode
5879  * dirtiness (it may still be data-dirty).
5880  * This means that the in-core inode may be reaped by prune_icache
5881  * without having to perform any I/O.  This is a very good thing,
5882  * because *any* task may call prune_icache - even ones which
5883  * have a transaction open against a different journal.
5884  *
5885  * Is this cheating?  Not really.  Sure, we haven't written the
5886  * inode out, but prune_icache isn't a user-visible syncing function.
5887  * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5888  * we start and wait on commits.
5889  */
5890 int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode,
5891 				const char *func, unsigned int line)
5892 {
5893 	struct ext4_iloc iloc;
5894 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5895 	int err;
5896 
5897 	might_sleep();
5898 	trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5899 	err = ext4_reserve_inode_write(handle, inode, &iloc);
5900 	if (err)
5901 		goto out;
5902 
5903 	if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
5904 		ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
5905 					       iloc, handle);
5906 
5907 	err = ext4_mark_iloc_dirty(handle, inode, &iloc);
5908 out:
5909 	if (unlikely(err))
5910 		ext4_error_inode_err(inode, func, line, 0, err,
5911 					"mark_inode_dirty error");
5912 	return err;
5913 }
5914 
5915 /*
5916  * ext4_dirty_inode() is called from __mark_inode_dirty()
5917  *
5918  * We're really interested in the case where a file is being extended.
5919  * i_size has been changed by generic_commit_write() and we thus need
5920  * to include the updated inode in the current transaction.
5921  *
5922  * Also, dquot_alloc_block() will always dirty the inode when blocks
5923  * are allocated to the file.
5924  *
5925  * If the inode is marked synchronous, we don't honour that here - doing
5926  * so would cause a commit on atime updates, which we don't bother doing.
5927  * We handle synchronous inodes at the highest possible level.
5928  *
5929  * If only the I_DIRTY_TIME flag is set, we can skip everything.  If
5930  * I_DIRTY_TIME and I_DIRTY_SYNC is set, the only inode fields we need
5931  * to copy into the on-disk inode structure are the timestamp files.
5932  */
5933 void ext4_dirty_inode(struct inode *inode, int flags)
5934 {
5935 	handle_t *handle;
5936 
5937 	if (flags == I_DIRTY_TIME)
5938 		return;
5939 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
5940 	if (IS_ERR(handle))
5941 		goto out;
5942 
5943 	ext4_mark_inode_dirty(handle, inode);
5944 
5945 	ext4_journal_stop(handle);
5946 out:
5947 	return;
5948 }
5949 
5950 int ext4_change_inode_journal_flag(struct inode *inode, int val)
5951 {
5952 	journal_t *journal;
5953 	handle_t *handle;
5954 	int err;
5955 	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5956 
5957 	/*
5958 	 * We have to be very careful here: changing a data block's
5959 	 * journaling status dynamically is dangerous.  If we write a
5960 	 * data block to the journal, change the status and then delete
5961 	 * that block, we risk forgetting to revoke the old log record
5962 	 * from the journal and so a subsequent replay can corrupt data.
5963 	 * So, first we make sure that the journal is empty and that
5964 	 * nobody is changing anything.
5965 	 */
5966 
5967 	journal = EXT4_JOURNAL(inode);
5968 	if (!journal)
5969 		return 0;
5970 	if (is_journal_aborted(journal))
5971 		return -EROFS;
5972 
5973 	/* Wait for all existing dio workers */
5974 	inode_dio_wait(inode);
5975 
5976 	/*
5977 	 * Before flushing the journal and switching inode's aops, we have
5978 	 * to flush all dirty data the inode has. There can be outstanding
5979 	 * delayed allocations, there can be unwritten extents created by
5980 	 * fallocate or buffered writes in dioread_nolock mode covered by
5981 	 * dirty data which can be converted only after flushing the dirty
5982 	 * data (and journalled aops don't know how to handle these cases).
5983 	 */
5984 	if (val) {
5985 		down_write(&EXT4_I(inode)->i_mmap_sem);
5986 		err = filemap_write_and_wait(inode->i_mapping);
5987 		if (err < 0) {
5988 			up_write(&EXT4_I(inode)->i_mmap_sem);
5989 			return err;
5990 		}
5991 	}
5992 
5993 	percpu_down_write(&sbi->s_writepages_rwsem);
5994 	jbd2_journal_lock_updates(journal);
5995 
5996 	/*
5997 	 * OK, there are no updates running now, and all cached data is
5998 	 * synced to disk.  We are now in a completely consistent state
5999 	 * which doesn't have anything in the journal, and we know that
6000 	 * no filesystem updates are running, so it is safe to modify
6001 	 * the inode's in-core data-journaling state flag now.
6002 	 */
6003 
6004 	if (val)
6005 		ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6006 	else {
6007 		err = jbd2_journal_flush(journal);
6008 		if (err < 0) {
6009 			jbd2_journal_unlock_updates(journal);
6010 			percpu_up_write(&sbi->s_writepages_rwsem);
6011 			return err;
6012 		}
6013 		ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6014 	}
6015 	ext4_set_aops(inode);
6016 
6017 	jbd2_journal_unlock_updates(journal);
6018 	percpu_up_write(&sbi->s_writepages_rwsem);
6019 
6020 	if (val)
6021 		up_write(&EXT4_I(inode)->i_mmap_sem);
6022 
6023 	/* Finally we can mark the inode as dirty. */
6024 
6025 	handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
6026 	if (IS_ERR(handle))
6027 		return PTR_ERR(handle);
6028 
6029 	ext4_fc_mark_ineligible(inode->i_sb,
6030 		EXT4_FC_REASON_JOURNAL_FLAG_CHANGE);
6031 	err = ext4_mark_inode_dirty(handle, inode);
6032 	ext4_handle_sync(handle);
6033 	ext4_journal_stop(handle);
6034 	ext4_std_error(inode->i_sb, err);
6035 
6036 	return err;
6037 }
6038 
6039 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
6040 {
6041 	return !buffer_mapped(bh);
6042 }
6043 
6044 vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)
6045 {
6046 	struct vm_area_struct *vma = vmf->vma;
6047 	struct page *page = vmf->page;
6048 	loff_t size;
6049 	unsigned long len;
6050 	int err;
6051 	vm_fault_t ret;
6052 	struct file *file = vma->vm_file;
6053 	struct inode *inode = file_inode(file);
6054 	struct address_space *mapping = inode->i_mapping;
6055 	handle_t *handle;
6056 	get_block_t *get_block;
6057 	int retries = 0;
6058 
6059 	if (unlikely(IS_IMMUTABLE(inode)))
6060 		return VM_FAULT_SIGBUS;
6061 
6062 	sb_start_pagefault(inode->i_sb);
6063 	file_update_time(vma->vm_file);
6064 
6065 	down_read(&EXT4_I(inode)->i_mmap_sem);
6066 
6067 	err = ext4_convert_inline_data(inode);
6068 	if (err)
6069 		goto out_ret;
6070 
6071 	/*
6072 	 * On data journalling we skip straight to the transaction handle:
6073 	 * there's no delalloc; page truncated will be checked later; the
6074 	 * early return w/ all buffers mapped (calculates size/len) can't
6075 	 * be used; and there's no dioread_nolock, so only ext4_get_block.
6076 	 */
6077 	if (ext4_should_journal_data(inode))
6078 		goto retry_alloc;
6079 
6080 	/* Delalloc case is easy... */
6081 	if (test_opt(inode->i_sb, DELALLOC) &&
6082 	    !ext4_nonda_switch(inode->i_sb)) {
6083 		do {
6084 			err = block_page_mkwrite(vma, vmf,
6085 						   ext4_da_get_block_prep);
6086 		} while (err == -ENOSPC &&
6087 		       ext4_should_retry_alloc(inode->i_sb, &retries));
6088 		goto out_ret;
6089 	}
6090 
6091 	lock_page(page);
6092 	size = i_size_read(inode);
6093 	/* Page got truncated from under us? */
6094 	if (page->mapping != mapping || page_offset(page) > size) {
6095 		unlock_page(page);
6096 		ret = VM_FAULT_NOPAGE;
6097 		goto out;
6098 	}
6099 
6100 	if (page->index == size >> PAGE_SHIFT)
6101 		len = size & ~PAGE_MASK;
6102 	else
6103 		len = PAGE_SIZE;
6104 	/*
6105 	 * Return if we have all the buffers mapped. This avoids the need to do
6106 	 * journal_start/journal_stop which can block and take a long time
6107 	 *
6108 	 * This cannot be done for data journalling, as we have to add the
6109 	 * inode to the transaction's list to writeprotect pages on commit.
6110 	 */
6111 	if (page_has_buffers(page)) {
6112 		if (!ext4_walk_page_buffers(NULL, page_buffers(page),
6113 					    0, len, NULL,
6114 					    ext4_bh_unmapped)) {
6115 			/* Wait so that we don't change page under IO */
6116 			wait_for_stable_page(page);
6117 			ret = VM_FAULT_LOCKED;
6118 			goto out;
6119 		}
6120 	}
6121 	unlock_page(page);
6122 	/* OK, we need to fill the hole... */
6123 	if (ext4_should_dioread_nolock(inode))
6124 		get_block = ext4_get_block_unwritten;
6125 	else
6126 		get_block = ext4_get_block;
6127 retry_alloc:
6128 	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
6129 				    ext4_writepage_trans_blocks(inode));
6130 	if (IS_ERR(handle)) {
6131 		ret = VM_FAULT_SIGBUS;
6132 		goto out;
6133 	}
6134 	/*
6135 	 * Data journalling can't use block_page_mkwrite() because it
6136 	 * will set_buffer_dirty() before do_journal_get_write_access()
6137 	 * thus might hit warning messages for dirty metadata buffers.
6138 	 */
6139 	if (!ext4_should_journal_data(inode)) {
6140 		err = block_page_mkwrite(vma, vmf, get_block);
6141 	} else {
6142 		lock_page(page);
6143 		size = i_size_read(inode);
6144 		/* Page got truncated from under us? */
6145 		if (page->mapping != mapping || page_offset(page) > size) {
6146 			ret = VM_FAULT_NOPAGE;
6147 			goto out_error;
6148 		}
6149 
6150 		if (page->index == size >> PAGE_SHIFT)
6151 			len = size & ~PAGE_MASK;
6152 		else
6153 			len = PAGE_SIZE;
6154 
6155 		err = __block_write_begin(page, 0, len, ext4_get_block);
6156 		if (!err) {
6157 			ret = VM_FAULT_SIGBUS;
6158 			if (ext4_walk_page_buffers(handle, page_buffers(page),
6159 					0, len, NULL, do_journal_get_write_access))
6160 				goto out_error;
6161 			if (ext4_walk_page_buffers(handle, page_buffers(page),
6162 					0, len, NULL, write_end_fn))
6163 				goto out_error;
6164 			if (ext4_jbd2_inode_add_write(handle, inode,
6165 						      page_offset(page), len))
6166 				goto out_error;
6167 			ext4_set_inode_state(inode, EXT4_STATE_JDATA);
6168 		} else {
6169 			unlock_page(page);
6170 		}
6171 	}
6172 	ext4_journal_stop(handle);
6173 	if (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
6174 		goto retry_alloc;
6175 out_ret:
6176 	ret = block_page_mkwrite_return(err);
6177 out:
6178 	up_read(&EXT4_I(inode)->i_mmap_sem);
6179 	sb_end_pagefault(inode->i_sb);
6180 	return ret;
6181 out_error:
6182 	unlock_page(page);
6183 	ext4_journal_stop(handle);
6184 	goto out;
6185 }
6186 
6187 vm_fault_t ext4_filemap_fault(struct vm_fault *vmf)
6188 {
6189 	struct inode *inode = file_inode(vmf->vma->vm_file);
6190 	vm_fault_t ret;
6191 
6192 	down_read(&EXT4_I(inode)->i_mmap_sem);
6193 	ret = filemap_fault(vmf);
6194 	up_read(&EXT4_I(inode)->i_mmap_sem);
6195 
6196 	return ret;
6197 }
6198