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