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