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