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