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