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