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