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