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