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