ext4: fix NULL pointer dereference in ext4_mark_inode_dirty()
[linux/fpc-iii.git] / fs / ext4 / inode.c
blobc9d21642ca799598847596665d676687b6feb5d5
1 /*
2 * linux/fs/ext4/inode.c
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)
9 * from
11 * linux/fs/minix/inode.c
13 * Copyright (C) 1991, 1992 Linus Torvalds
15 * 64-bit file support on 64-bit platforms by Jakub Jelinek
16 * (jj@sunsite.ms.mff.cuni.cz)
18 * Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
21 #include <linux/fs.h>
22 #include <linux/time.h>
23 #include <linux/jbd2.h>
24 #include <linux/highuid.h>
25 #include <linux/pagemap.h>
26 #include <linux/quotaops.h>
27 #include <linux/string.h>
28 #include <linux/buffer_head.h>
29 #include <linux/writeback.h>
30 #include <linux/pagevec.h>
31 #include <linux/mpage.h>
32 #include <linux/namei.h>
33 #include <linux/uio.h>
34 #include <linux/bio.h>
35 #include <linux/workqueue.h>
36 #include <linux/kernel.h>
37 #include <linux/printk.h>
38 #include <linux/slab.h>
39 #include <linux/ratelimit.h>
40 #include <linux/aio.h>
41 #include <linux/bitops.h>
43 #include "ext4_jbd2.h"
44 #include "xattr.h"
45 #include "acl.h"
46 #include "truncate.h"
48 #include <trace/events/ext4.h>
50 #define MPAGE_DA_EXTENT_TAIL 0x01
52 static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
53 struct ext4_inode_info *ei)
55 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
56 __u16 csum_lo;
57 __u16 csum_hi = 0;
58 __u32 csum;
60 csum_lo = le16_to_cpu(raw->i_checksum_lo);
61 raw->i_checksum_lo = 0;
62 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
63 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
64 csum_hi = le16_to_cpu(raw->i_checksum_hi);
65 raw->i_checksum_hi = 0;
68 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw,
69 EXT4_INODE_SIZE(inode->i_sb));
71 raw->i_checksum_lo = cpu_to_le16(csum_lo);
72 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
73 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
74 raw->i_checksum_hi = cpu_to_le16(csum_hi);
76 return csum;
79 static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
80 struct ext4_inode_info *ei)
82 __u32 provided, calculated;
84 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
85 cpu_to_le32(EXT4_OS_LINUX) ||
86 !ext4_has_metadata_csum(inode->i_sb))
87 return 1;
89 provided = le16_to_cpu(raw->i_checksum_lo);
90 calculated = ext4_inode_csum(inode, raw, ei);
91 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
92 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
93 provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
94 else
95 calculated &= 0xFFFF;
97 return provided == calculated;
100 static void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
101 struct ext4_inode_info *ei)
103 __u32 csum;
105 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
106 cpu_to_le32(EXT4_OS_LINUX) ||
107 !ext4_has_metadata_csum(inode->i_sb))
108 return;
110 csum = ext4_inode_csum(inode, raw, ei);
111 raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
112 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
113 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
114 raw->i_checksum_hi = cpu_to_le16(csum >> 16);
117 static inline int ext4_begin_ordered_truncate(struct inode *inode,
118 loff_t new_size)
120 trace_ext4_begin_ordered_truncate(inode, new_size);
122 * If jinode is zero, then we never opened the file for
123 * writing, so there's no need to call
124 * jbd2_journal_begin_ordered_truncate() since there's no
125 * outstanding writes we need to flush.
127 if (!EXT4_I(inode)->jinode)
128 return 0;
129 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
130 EXT4_I(inode)->jinode,
131 new_size);
134 static void ext4_invalidatepage(struct page *page, unsigned int offset,
135 unsigned int length);
136 static int __ext4_journalled_writepage(struct page *page, unsigned int len);
137 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
138 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
139 int pextents);
142 * Test whether an inode is a fast symlink.
144 static int ext4_inode_is_fast_symlink(struct inode *inode)
146 int ea_blocks = EXT4_I(inode)->i_file_acl ?
147 EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
149 if (ext4_has_inline_data(inode))
150 return 0;
152 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
156 * Restart the transaction associated with *handle. This does a commit,
157 * so before we call here everything must be consistently dirtied against
158 * this transaction.
160 int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
161 int nblocks)
163 int ret;
166 * Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
167 * moment, get_block can be called only for blocks inside i_size since
168 * page cache has been already dropped and writes are blocked by
169 * i_mutex. So we can safely drop the i_data_sem here.
171 BUG_ON(EXT4_JOURNAL(inode) == NULL);
172 jbd_debug(2, "restarting handle %p\n", handle);
173 up_write(&EXT4_I(inode)->i_data_sem);
174 ret = ext4_journal_restart(handle, nblocks);
175 down_write(&EXT4_I(inode)->i_data_sem);
176 ext4_discard_preallocations(inode);
178 return ret;
182 * Called at the last iput() if i_nlink is zero.
184 void ext4_evict_inode(struct inode *inode)
186 handle_t *handle;
187 int err;
189 trace_ext4_evict_inode(inode);
191 if (inode->i_nlink) {
193 * When journalling data dirty buffers are tracked only in the
194 * journal. So although mm thinks everything is clean and
195 * ready for reaping the inode might still have some pages to
196 * write in the running transaction or waiting to be
197 * checkpointed. Thus calling jbd2_journal_invalidatepage()
198 * (via truncate_inode_pages()) to discard these buffers can
199 * cause data loss. Also even if we did not discard these
200 * buffers, we would have no way to find them after the inode
201 * is reaped and thus user could see stale data if he tries to
202 * read them before the transaction is checkpointed. So be
203 * careful and force everything to disk here... We use
204 * ei->i_datasync_tid to store the newest transaction
205 * containing inode's data.
207 * Note that directories do not have this problem because they
208 * don't use page cache.
210 if (ext4_should_journal_data(inode) &&
211 (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode)) &&
212 inode->i_ino != EXT4_JOURNAL_INO) {
213 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
214 tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
216 jbd2_complete_transaction(journal, commit_tid);
217 filemap_write_and_wait(&inode->i_data);
219 truncate_inode_pages_final(&inode->i_data);
221 WARN_ON(atomic_read(&EXT4_I(inode)->i_ioend_count));
222 goto no_delete;
225 if (is_bad_inode(inode))
226 goto no_delete;
227 dquot_initialize(inode);
229 if (ext4_should_order_data(inode))
230 ext4_begin_ordered_truncate(inode, 0);
231 truncate_inode_pages_final(&inode->i_data);
233 WARN_ON(atomic_read(&EXT4_I(inode)->i_ioend_count));
236 * Protect us against freezing - iput() caller didn't have to have any
237 * protection against it
239 sb_start_intwrite(inode->i_sb);
240 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
241 ext4_blocks_for_truncate(inode)+3);
242 if (IS_ERR(handle)) {
243 ext4_std_error(inode->i_sb, PTR_ERR(handle));
245 * If we're going to skip the normal cleanup, we still need to
246 * make sure that the in-core orphan linked list is properly
247 * cleaned up.
249 ext4_orphan_del(NULL, inode);
250 sb_end_intwrite(inode->i_sb);
251 goto no_delete;
254 if (IS_SYNC(inode))
255 ext4_handle_sync(handle);
256 inode->i_size = 0;
257 err = ext4_mark_inode_dirty(handle, inode);
258 if (err) {
259 ext4_warning(inode->i_sb,
260 "couldn't mark inode dirty (err %d)", err);
261 goto stop_handle;
263 if (inode->i_blocks)
264 ext4_truncate(inode);
267 * ext4_ext_truncate() doesn't reserve any slop when it
268 * restarts journal transactions; therefore there may not be
269 * enough credits left in the handle to remove the inode from
270 * the orphan list and set the dtime field.
272 if (!ext4_handle_has_enough_credits(handle, 3)) {
273 err = ext4_journal_extend(handle, 3);
274 if (err > 0)
275 err = ext4_journal_restart(handle, 3);
276 if (err != 0) {
277 ext4_warning(inode->i_sb,
278 "couldn't extend journal (err %d)", err);
279 stop_handle:
280 ext4_journal_stop(handle);
281 ext4_orphan_del(NULL, inode);
282 sb_end_intwrite(inode->i_sb);
283 goto no_delete;
288 * Kill off the orphan record which ext4_truncate created.
289 * AKPM: I think this can be inside the above `if'.
290 * Note that ext4_orphan_del() has to be able to cope with the
291 * deletion of a non-existent orphan - this is because we don't
292 * know if ext4_truncate() actually created an orphan record.
293 * (Well, we could do this if we need to, but heck - it works)
295 ext4_orphan_del(handle, inode);
296 EXT4_I(inode)->i_dtime = get_seconds();
299 * One subtle ordering requirement: if anything has gone wrong
300 * (transaction abort, IO errors, whatever), then we can still
301 * do these next steps (the fs will already have been marked as
302 * having errors), but we can't free the inode if the mark_dirty
303 * fails.
305 if (ext4_mark_inode_dirty(handle, inode))
306 /* If that failed, just do the required in-core inode clear. */
307 ext4_clear_inode(inode);
308 else
309 ext4_free_inode(handle, inode);
310 ext4_journal_stop(handle);
311 sb_end_intwrite(inode->i_sb);
312 return;
313 no_delete:
314 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
317 #ifdef CONFIG_QUOTA
318 qsize_t *ext4_get_reserved_space(struct inode *inode)
320 return &EXT4_I(inode)->i_reserved_quota;
322 #endif
325 * Calculate the number of metadata blocks need to reserve
326 * to allocate a block located at @lblock
328 static int ext4_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
330 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
331 return ext4_ext_calc_metadata_amount(inode, lblock);
333 return ext4_ind_calc_metadata_amount(inode, lblock);
337 * Called with i_data_sem down, which is important since we can call
338 * ext4_discard_preallocations() from here.
340 void ext4_da_update_reserve_space(struct inode *inode,
341 int used, int quota_claim)
343 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
344 struct ext4_inode_info *ei = EXT4_I(inode);
346 spin_lock(&ei->i_block_reservation_lock);
347 trace_ext4_da_update_reserve_space(inode, used, quota_claim);
348 if (unlikely(used > ei->i_reserved_data_blocks)) {
349 ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
350 "with only %d reserved data blocks",
351 __func__, inode->i_ino, used,
352 ei->i_reserved_data_blocks);
353 WARN_ON(1);
354 used = ei->i_reserved_data_blocks;
357 if (unlikely(ei->i_allocated_meta_blocks > ei->i_reserved_meta_blocks)) {
358 ext4_warning(inode->i_sb, "ino %lu, allocated %d "
359 "with only %d reserved metadata blocks "
360 "(releasing %d blocks with reserved %d data blocks)",
361 inode->i_ino, ei->i_allocated_meta_blocks,
362 ei->i_reserved_meta_blocks, used,
363 ei->i_reserved_data_blocks);
364 WARN_ON(1);
365 ei->i_allocated_meta_blocks = ei->i_reserved_meta_blocks;
368 /* Update per-inode reservations */
369 ei->i_reserved_data_blocks -= used;
370 ei->i_reserved_meta_blocks -= ei->i_allocated_meta_blocks;
371 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
372 used + ei->i_allocated_meta_blocks);
373 ei->i_allocated_meta_blocks = 0;
375 if (ei->i_reserved_data_blocks == 0) {
377 * We can release all of the reserved metadata blocks
378 * only when we have written all of the delayed
379 * allocation blocks.
381 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
382 ei->i_reserved_meta_blocks);
383 ei->i_reserved_meta_blocks = 0;
384 ei->i_da_metadata_calc_len = 0;
386 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
388 /* Update quota subsystem for data blocks */
389 if (quota_claim)
390 dquot_claim_block(inode, EXT4_C2B(sbi, used));
391 else {
393 * We did fallocate with an offset that is already delayed
394 * allocated. So on delayed allocated writeback we should
395 * not re-claim the quota for fallocated blocks.
397 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
401 * If we have done all the pending block allocations and if
402 * there aren't any writers on the inode, we can discard the
403 * inode's preallocations.
405 if ((ei->i_reserved_data_blocks == 0) &&
406 (atomic_read(&inode->i_writecount) == 0))
407 ext4_discard_preallocations(inode);
410 static int __check_block_validity(struct inode *inode, const char *func,
411 unsigned int line,
412 struct ext4_map_blocks *map)
414 if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
415 map->m_len)) {
416 ext4_error_inode(inode, func, line, map->m_pblk,
417 "lblock %lu mapped to illegal pblock "
418 "(length %d)", (unsigned long) map->m_lblk,
419 map->m_len);
420 return -EIO;
422 return 0;
425 #define check_block_validity(inode, map) \
426 __check_block_validity((inode), __func__, __LINE__, (map))
428 #ifdef ES_AGGRESSIVE_TEST
429 static void ext4_map_blocks_es_recheck(handle_t *handle,
430 struct inode *inode,
431 struct ext4_map_blocks *es_map,
432 struct ext4_map_blocks *map,
433 int flags)
435 int retval;
437 map->m_flags = 0;
439 * There is a race window that the result is not the same.
440 * e.g. xfstests #223 when dioread_nolock enables. The reason
441 * is that we lookup a block mapping in extent status tree with
442 * out taking i_data_sem. So at the time the unwritten extent
443 * could be converted.
445 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
446 down_read(&EXT4_I(inode)->i_data_sem);
447 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
448 retval = ext4_ext_map_blocks(handle, inode, map, flags &
449 EXT4_GET_BLOCKS_KEEP_SIZE);
450 } else {
451 retval = ext4_ind_map_blocks(handle, inode, map, flags &
452 EXT4_GET_BLOCKS_KEEP_SIZE);
454 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
455 up_read((&EXT4_I(inode)->i_data_sem));
457 * Clear EXT4_MAP_FROM_CLUSTER and EXT4_MAP_BOUNDARY flag
458 * because it shouldn't be marked in es_map->m_flags.
460 map->m_flags &= ~(EXT4_MAP_FROM_CLUSTER | EXT4_MAP_BOUNDARY);
463 * We don't check m_len because extent will be collpased in status
464 * tree. So the m_len might not equal.
466 if (es_map->m_lblk != map->m_lblk ||
467 es_map->m_flags != map->m_flags ||
468 es_map->m_pblk != map->m_pblk) {
469 printk("ES cache assertion failed for inode: %lu "
470 "es_cached ex [%d/%d/%llu/%x] != "
471 "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
472 inode->i_ino, es_map->m_lblk, es_map->m_len,
473 es_map->m_pblk, es_map->m_flags, map->m_lblk,
474 map->m_len, map->m_pblk, map->m_flags,
475 retval, flags);
478 #endif /* ES_AGGRESSIVE_TEST */
481 * The ext4_map_blocks() function tries to look up the requested blocks,
482 * and returns if the blocks are already mapped.
484 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
485 * and store the allocated blocks in the result buffer head and mark it
486 * mapped.
488 * If file type is extents based, it will call ext4_ext_map_blocks(),
489 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
490 * based files
492 * On success, it returns the number of blocks being mapped or allocated.
493 * if create==0 and the blocks are pre-allocated and unwritten block,
494 * the result buffer head is unmapped. If the create ==1, it will make sure
495 * the buffer head is mapped.
497 * It returns 0 if plain look up failed (blocks have not been allocated), in
498 * that case, buffer head is unmapped
500 * It returns the error in case of allocation failure.
502 int ext4_map_blocks(handle_t *handle, struct inode *inode,
503 struct ext4_map_blocks *map, int flags)
505 struct extent_status es;
506 int retval;
507 int ret = 0;
508 #ifdef ES_AGGRESSIVE_TEST
509 struct ext4_map_blocks orig_map;
511 memcpy(&orig_map, map, sizeof(*map));
512 #endif
514 map->m_flags = 0;
515 ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
516 "logical block %lu\n", inode->i_ino, flags, map->m_len,
517 (unsigned long) map->m_lblk);
520 * ext4_map_blocks returns an int, and m_len is an unsigned int
522 if (unlikely(map->m_len > INT_MAX))
523 map->m_len = INT_MAX;
525 /* We can handle the block number less than EXT_MAX_BLOCKS */
526 if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
527 return -EIO;
529 /* Lookup extent status tree firstly */
530 if (ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
531 ext4_es_lru_add(inode);
532 if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
533 map->m_pblk = ext4_es_pblock(&es) +
534 map->m_lblk - es.es_lblk;
535 map->m_flags |= ext4_es_is_written(&es) ?
536 EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
537 retval = es.es_len - (map->m_lblk - es.es_lblk);
538 if (retval > map->m_len)
539 retval = map->m_len;
540 map->m_len = retval;
541 } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
542 retval = 0;
543 } else {
544 BUG_ON(1);
546 #ifdef ES_AGGRESSIVE_TEST
547 ext4_map_blocks_es_recheck(handle, inode, map,
548 &orig_map, flags);
549 #endif
550 goto found;
554 * Try to see if we can get the block without requesting a new
555 * file system block.
557 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
558 down_read(&EXT4_I(inode)->i_data_sem);
559 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
560 retval = ext4_ext_map_blocks(handle, inode, map, flags &
561 EXT4_GET_BLOCKS_KEEP_SIZE);
562 } else {
563 retval = ext4_ind_map_blocks(handle, inode, map, flags &
564 EXT4_GET_BLOCKS_KEEP_SIZE);
566 if (retval > 0) {
567 unsigned int status;
569 if (unlikely(retval != map->m_len)) {
570 ext4_warning(inode->i_sb,
571 "ES len assertion failed for inode "
572 "%lu: retval %d != map->m_len %d",
573 inode->i_ino, retval, map->m_len);
574 WARN_ON(1);
577 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
578 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
579 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
580 !(status & EXTENT_STATUS_WRITTEN) &&
581 ext4_find_delalloc_range(inode, map->m_lblk,
582 map->m_lblk + map->m_len - 1))
583 status |= EXTENT_STATUS_DELAYED;
584 ret = ext4_es_insert_extent(inode, map->m_lblk,
585 map->m_len, map->m_pblk, status);
586 if (ret < 0)
587 retval = ret;
589 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
590 up_read((&EXT4_I(inode)->i_data_sem));
592 found:
593 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
594 ret = check_block_validity(inode, map);
595 if (ret != 0)
596 return ret;
599 /* If it is only a block(s) look up */
600 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
601 return retval;
604 * Returns if the blocks have already allocated
606 * Note that if blocks have been preallocated
607 * ext4_ext_get_block() returns the create = 0
608 * with buffer head unmapped.
610 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
612 * If we need to convert extent to unwritten
613 * we continue and do the actual work in
614 * ext4_ext_map_blocks()
616 if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
617 return retval;
620 * Here we clear m_flags because after allocating an new extent,
621 * it will be set again.
623 map->m_flags &= ~EXT4_MAP_FLAGS;
626 * New blocks allocate and/or writing to unwritten extent
627 * will possibly result in updating i_data, so we take
628 * the write lock of i_data_sem, and call get_blocks()
629 * with create == 1 flag.
631 down_write(&EXT4_I(inode)->i_data_sem);
634 * if the caller is from delayed allocation writeout path
635 * we have already reserved fs blocks for allocation
636 * let the underlying get_block() function know to
637 * avoid double accounting
639 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
640 ext4_set_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
642 * We need to check for EXT4 here because migrate
643 * could have changed the inode type in between
645 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
646 retval = ext4_ext_map_blocks(handle, inode, map, flags);
647 } else {
648 retval = ext4_ind_map_blocks(handle, inode, map, flags);
650 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
652 * We allocated new blocks which will result in
653 * i_data's format changing. Force the migrate
654 * to fail by clearing migrate flags
656 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
660 * Update reserved blocks/metadata blocks after successful
661 * block allocation which had been deferred till now. We don't
662 * support fallocate for non extent files. So we can update
663 * reserve space here.
665 if ((retval > 0) &&
666 (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
667 ext4_da_update_reserve_space(inode, retval, 1);
669 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
670 ext4_clear_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
672 if (retval > 0) {
673 unsigned int status;
675 if (unlikely(retval != map->m_len)) {
676 ext4_warning(inode->i_sb,
677 "ES len assertion failed for inode "
678 "%lu: retval %d != map->m_len %d",
679 inode->i_ino, retval, map->m_len);
680 WARN_ON(1);
684 * If the extent has been zeroed out, we don't need to update
685 * extent status tree.
687 if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
688 ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
689 if (ext4_es_is_written(&es))
690 goto has_zeroout;
692 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
693 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
694 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
695 !(status & EXTENT_STATUS_WRITTEN) &&
696 ext4_find_delalloc_range(inode, map->m_lblk,
697 map->m_lblk + map->m_len - 1))
698 status |= EXTENT_STATUS_DELAYED;
699 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
700 map->m_pblk, status);
701 if (ret < 0)
702 retval = ret;
705 has_zeroout:
706 up_write((&EXT4_I(inode)->i_data_sem));
707 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
708 ret = check_block_validity(inode, map);
709 if (ret != 0)
710 return ret;
712 return retval;
716 * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
717 * we have to be careful as someone else may be manipulating b_state as well.
719 static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
721 unsigned long old_state;
722 unsigned long new_state;
724 flags &= EXT4_MAP_FLAGS;
726 /* Dummy buffer_head? Set non-atomically. */
727 if (!bh->b_page) {
728 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
729 return;
732 * Someone else may be modifying b_state. Be careful! This is ugly but
733 * once we get rid of using bh as a container for mapping information
734 * to pass to / from get_block functions, this can go away.
736 do {
737 old_state = ACCESS_ONCE(bh->b_state);
738 new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
739 } while (unlikely(
740 cmpxchg(&bh->b_state, old_state, new_state) != old_state));
743 /* Maximum number of blocks we map for direct IO at once. */
744 #define DIO_MAX_BLOCKS 4096
746 static int _ext4_get_block(struct inode *inode, sector_t iblock,
747 struct buffer_head *bh, int flags)
749 handle_t *handle = ext4_journal_current_handle();
750 struct ext4_map_blocks map;
751 int ret = 0, started = 0;
752 int dio_credits;
754 if (ext4_has_inline_data(inode))
755 return -ERANGE;
757 map.m_lblk = iblock;
758 map.m_len = bh->b_size >> inode->i_blkbits;
760 if (flags && !(flags & EXT4_GET_BLOCKS_NO_LOCK) && !handle) {
761 /* Direct IO write... */
762 if (map.m_len > DIO_MAX_BLOCKS)
763 map.m_len = DIO_MAX_BLOCKS;
764 dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
765 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
766 dio_credits);
767 if (IS_ERR(handle)) {
768 ret = PTR_ERR(handle);
769 return ret;
771 started = 1;
774 ret = ext4_map_blocks(handle, inode, &map, flags);
775 if (ret > 0) {
776 ext4_io_end_t *io_end = ext4_inode_aio(inode);
778 map_bh(bh, inode->i_sb, map.m_pblk);
779 ext4_update_bh_state(bh, map.m_flags);
780 if (io_end && io_end->flag & EXT4_IO_END_UNWRITTEN)
781 set_buffer_defer_completion(bh);
782 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
783 ret = 0;
785 if (started)
786 ext4_journal_stop(handle);
787 return ret;
790 int ext4_get_block(struct inode *inode, sector_t iblock,
791 struct buffer_head *bh, int create)
793 return _ext4_get_block(inode, iblock, bh,
794 create ? EXT4_GET_BLOCKS_CREATE : 0);
798 * `handle' can be NULL if create is zero
800 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
801 ext4_lblk_t block, int create, int *errp)
803 struct ext4_map_blocks map;
804 struct buffer_head *bh;
805 int fatal = 0, err;
807 J_ASSERT(handle != NULL || create == 0);
809 map.m_lblk = block;
810 map.m_len = 1;
811 err = ext4_map_blocks(handle, inode, &map,
812 create ? EXT4_GET_BLOCKS_CREATE : 0);
814 /* ensure we send some value back into *errp */
815 *errp = 0;
817 if (create && err == 0)
818 err = -ENOSPC; /* should never happen */
819 if (err < 0)
820 *errp = err;
821 if (err <= 0)
822 return NULL;
824 bh = sb_getblk(inode->i_sb, map.m_pblk);
825 if (unlikely(!bh)) {
826 *errp = -ENOMEM;
827 return NULL;
829 if (map.m_flags & EXT4_MAP_NEW) {
830 J_ASSERT(create != 0);
831 J_ASSERT(handle != NULL);
834 * Now that we do not always journal data, we should
835 * keep in mind whether this should always journal the
836 * new buffer as metadata. For now, regular file
837 * writes use ext4_get_block instead, so it's not a
838 * problem.
840 lock_buffer(bh);
841 BUFFER_TRACE(bh, "call get_create_access");
842 fatal = ext4_journal_get_create_access(handle, bh);
843 if (!fatal && !buffer_uptodate(bh)) {
844 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
845 set_buffer_uptodate(bh);
847 unlock_buffer(bh);
848 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
849 err = ext4_handle_dirty_metadata(handle, inode, bh);
850 if (!fatal)
851 fatal = err;
852 } else {
853 BUFFER_TRACE(bh, "not a new buffer");
855 if (fatal) {
856 *errp = fatal;
857 brelse(bh);
858 bh = NULL;
860 return bh;
863 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
864 ext4_lblk_t block, int create, int *err)
866 struct buffer_head *bh;
868 bh = ext4_getblk(handle, inode, block, create, err);
869 if (!bh)
870 return bh;
871 if (buffer_uptodate(bh))
872 return bh;
873 ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &bh);
874 wait_on_buffer(bh);
875 if (buffer_uptodate(bh))
876 return bh;
877 put_bh(bh);
878 *err = -EIO;
879 return NULL;
882 int ext4_walk_page_buffers(handle_t *handle,
883 struct buffer_head *head,
884 unsigned from,
885 unsigned to,
886 int *partial,
887 int (*fn)(handle_t *handle,
888 struct buffer_head *bh))
890 struct buffer_head *bh;
891 unsigned block_start, block_end;
892 unsigned blocksize = head->b_size;
893 int err, ret = 0;
894 struct buffer_head *next;
896 for (bh = head, block_start = 0;
897 ret == 0 && (bh != head || !block_start);
898 block_start = block_end, bh = next) {
899 next = bh->b_this_page;
900 block_end = block_start + blocksize;
901 if (block_end <= from || block_start >= to) {
902 if (partial && !buffer_uptodate(bh))
903 *partial = 1;
904 continue;
906 err = (*fn)(handle, bh);
907 if (!ret)
908 ret = err;
910 return ret;
914 * To preserve ordering, it is essential that the hole instantiation and
915 * the data write be encapsulated in a single transaction. We cannot
916 * close off a transaction and start a new one between the ext4_get_block()
917 * and the commit_write(). So doing the jbd2_journal_start at the start of
918 * prepare_write() is the right place.
920 * Also, this function can nest inside ext4_writepage(). In that case, we
921 * *know* that ext4_writepage() has generated enough buffer credits to do the
922 * whole page. So we won't block on the journal in that case, which is good,
923 * because the caller may be PF_MEMALLOC.
925 * By accident, ext4 can be reentered when a transaction is open via
926 * quota file writes. If we were to commit the transaction while thus
927 * reentered, there can be a deadlock - we would be holding a quota
928 * lock, and the commit would never complete if another thread had a
929 * transaction open and was blocking on the quota lock - a ranking
930 * violation.
932 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
933 * will _not_ run commit under these circumstances because handle->h_ref
934 * is elevated. We'll still have enough credits for the tiny quotafile
935 * write.
937 int do_journal_get_write_access(handle_t *handle,
938 struct buffer_head *bh)
940 int dirty = buffer_dirty(bh);
941 int ret;
943 if (!buffer_mapped(bh) || buffer_freed(bh))
944 return 0;
946 * __block_write_begin() could have dirtied some buffers. Clean
947 * the dirty bit as jbd2_journal_get_write_access() could complain
948 * otherwise about fs integrity issues. Setting of the dirty bit
949 * by __block_write_begin() isn't a real problem here as we clear
950 * the bit before releasing a page lock and thus writeback cannot
951 * ever write the buffer.
953 if (dirty)
954 clear_buffer_dirty(bh);
955 BUFFER_TRACE(bh, "get write access");
956 ret = ext4_journal_get_write_access(handle, bh);
957 if (!ret && dirty)
958 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
959 return ret;
962 static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
963 struct buffer_head *bh_result, int create);
964 static int ext4_write_begin(struct file *file, struct address_space *mapping,
965 loff_t pos, unsigned len, unsigned flags,
966 struct page **pagep, void **fsdata)
968 struct inode *inode = mapping->host;
969 int ret, needed_blocks;
970 handle_t *handle;
971 int retries = 0;
972 struct page *page;
973 pgoff_t index;
974 unsigned from, to;
976 trace_ext4_write_begin(inode, pos, len, flags);
978 * Reserve one block more for addition to orphan list in case
979 * we allocate blocks but write fails for some reason
981 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
982 index = pos >> PAGE_CACHE_SHIFT;
983 from = pos & (PAGE_CACHE_SIZE - 1);
984 to = from + len;
986 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
987 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
988 flags, pagep);
989 if (ret < 0)
990 return ret;
991 if (ret == 1)
992 return 0;
996 * grab_cache_page_write_begin() can take a long time if the
997 * system is thrashing due to memory pressure, or if the page
998 * is being written back. So grab it first before we start
999 * the transaction handle. This also allows us to allocate
1000 * the page (if needed) without using GFP_NOFS.
1002 retry_grab:
1003 page = grab_cache_page_write_begin(mapping, index, flags);
1004 if (!page)
1005 return -ENOMEM;
1006 unlock_page(page);
1008 retry_journal:
1009 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1010 if (IS_ERR(handle)) {
1011 page_cache_release(page);
1012 return PTR_ERR(handle);
1015 lock_page(page);
1016 if (page->mapping != mapping) {
1017 /* The page got truncated from under us */
1018 unlock_page(page);
1019 page_cache_release(page);
1020 ext4_journal_stop(handle);
1021 goto retry_grab;
1023 /* In case writeback began while the page was unlocked */
1024 wait_for_stable_page(page);
1026 if (ext4_should_dioread_nolock(inode))
1027 ret = __block_write_begin(page, pos, len, ext4_get_block_write);
1028 else
1029 ret = __block_write_begin(page, pos, len, ext4_get_block);
1031 if (!ret && ext4_should_journal_data(inode)) {
1032 ret = ext4_walk_page_buffers(handle, page_buffers(page),
1033 from, to, NULL,
1034 do_journal_get_write_access);
1037 if (ret) {
1038 unlock_page(page);
1040 * __block_write_begin may have instantiated a few blocks
1041 * outside i_size. Trim these off again. Don't need
1042 * i_size_read because we hold i_mutex.
1044 * Add inode to orphan list in case we crash before
1045 * truncate finishes
1047 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1048 ext4_orphan_add(handle, inode);
1050 ext4_journal_stop(handle);
1051 if (pos + len > inode->i_size) {
1052 ext4_truncate_failed_write(inode);
1054 * If truncate failed early the inode might
1055 * still be on the orphan list; we need to
1056 * make sure the inode is removed from the
1057 * orphan list in that case.
1059 if (inode->i_nlink)
1060 ext4_orphan_del(NULL, inode);
1063 if (ret == -ENOSPC &&
1064 ext4_should_retry_alloc(inode->i_sb, &retries))
1065 goto retry_journal;
1066 page_cache_release(page);
1067 return ret;
1069 *pagep = page;
1070 return ret;
1073 /* For write_end() in data=journal mode */
1074 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1076 int ret;
1077 if (!buffer_mapped(bh) || buffer_freed(bh))
1078 return 0;
1079 set_buffer_uptodate(bh);
1080 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1081 clear_buffer_meta(bh);
1082 clear_buffer_prio(bh);
1083 return ret;
1087 * We need to pick up the new inode size which generic_commit_write gave us
1088 * `file' can be NULL - eg, when called from page_symlink().
1090 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1091 * buffers are managed internally.
1093 static int ext4_write_end(struct file *file,
1094 struct address_space *mapping,
1095 loff_t pos, unsigned len, unsigned copied,
1096 struct page *page, void *fsdata)
1098 handle_t *handle = ext4_journal_current_handle();
1099 struct inode *inode = mapping->host;
1100 int ret = 0, ret2;
1101 int i_size_changed = 0;
1103 trace_ext4_write_end(inode, pos, len, copied);
1104 if (ext4_test_inode_state(inode, EXT4_STATE_ORDERED_MODE)) {
1105 ret = ext4_jbd2_file_inode(handle, inode);
1106 if (ret) {
1107 unlock_page(page);
1108 page_cache_release(page);
1109 goto errout;
1113 if (ext4_has_inline_data(inode)) {
1114 ret = ext4_write_inline_data_end(inode, pos, len,
1115 copied, page);
1116 if (ret < 0)
1117 goto errout;
1118 copied = ret;
1119 } else
1120 copied = block_write_end(file, mapping, pos,
1121 len, copied, page, fsdata);
1123 * it's important to update i_size while still holding page lock:
1124 * page writeout could otherwise come in and zero beyond i_size.
1126 i_size_changed = ext4_update_inode_size(inode, pos + copied);
1127 unlock_page(page);
1128 page_cache_release(page);
1131 * Don't mark the inode dirty under page lock. First, it unnecessarily
1132 * makes the holding time of page lock longer. Second, it forces lock
1133 * ordering of page lock and transaction start for journaling
1134 * filesystems.
1136 if (i_size_changed)
1137 ext4_mark_inode_dirty(handle, inode);
1139 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1140 /* if we have allocated more blocks and copied
1141 * less. We will have blocks allocated outside
1142 * inode->i_size. So truncate them
1144 ext4_orphan_add(handle, inode);
1145 errout:
1146 ret2 = ext4_journal_stop(handle);
1147 if (!ret)
1148 ret = ret2;
1150 if (pos + len > inode->i_size) {
1151 ext4_truncate_failed_write(inode);
1153 * If truncate failed early the inode might still be
1154 * on the orphan list; we need to make sure the inode
1155 * is removed from the orphan list in that case.
1157 if (inode->i_nlink)
1158 ext4_orphan_del(NULL, inode);
1161 return ret ? ret : copied;
1164 static int ext4_journalled_write_end(struct file *file,
1165 struct address_space *mapping,
1166 loff_t pos, unsigned len, unsigned copied,
1167 struct page *page, void *fsdata)
1169 handle_t *handle = ext4_journal_current_handle();
1170 struct inode *inode = mapping->host;
1171 int ret = 0, ret2;
1172 int partial = 0;
1173 unsigned from, to;
1174 int size_changed = 0;
1176 trace_ext4_journalled_write_end(inode, pos, len, copied);
1177 from = pos & (PAGE_CACHE_SIZE - 1);
1178 to = from + len;
1180 BUG_ON(!ext4_handle_valid(handle));
1182 if (ext4_has_inline_data(inode))
1183 copied = ext4_write_inline_data_end(inode, pos, len,
1184 copied, page);
1185 else {
1186 if (copied < len) {
1187 if (!PageUptodate(page))
1188 copied = 0;
1189 page_zero_new_buffers(page, from+copied, to);
1192 ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
1193 to, &partial, write_end_fn);
1194 if (!partial)
1195 SetPageUptodate(page);
1197 size_changed = ext4_update_inode_size(inode, pos + copied);
1198 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1199 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1200 unlock_page(page);
1201 page_cache_release(page);
1203 if (size_changed) {
1204 ret2 = ext4_mark_inode_dirty(handle, inode);
1205 if (!ret)
1206 ret = ret2;
1209 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1210 /* if we have allocated more blocks and copied
1211 * less. We will have blocks allocated outside
1212 * inode->i_size. So truncate them
1214 ext4_orphan_add(handle, inode);
1216 ret2 = ext4_journal_stop(handle);
1217 if (!ret)
1218 ret = ret2;
1219 if (pos + len > inode->i_size) {
1220 ext4_truncate_failed_write(inode);
1222 * If truncate failed early the inode might still be
1223 * on the orphan list; we need to make sure the inode
1224 * is removed from the orphan list in that case.
1226 if (inode->i_nlink)
1227 ext4_orphan_del(NULL, inode);
1230 return ret ? ret : copied;
1234 * Reserve a metadata for a single block located at lblock
1236 static int ext4_da_reserve_metadata(struct inode *inode, ext4_lblk_t lblock)
1238 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1239 struct ext4_inode_info *ei = EXT4_I(inode);
1240 unsigned int md_needed;
1241 ext4_lblk_t save_last_lblock;
1242 int save_len;
1245 * recalculate the amount of metadata blocks to reserve
1246 * in order to allocate nrblocks
1247 * worse case is one extent per block
1249 spin_lock(&ei->i_block_reservation_lock);
1251 * ext4_calc_metadata_amount() has side effects, which we have
1252 * to be prepared undo if we fail to claim space.
1254 save_len = ei->i_da_metadata_calc_len;
1255 save_last_lblock = ei->i_da_metadata_calc_last_lblock;
1256 md_needed = EXT4_NUM_B2C(sbi,
1257 ext4_calc_metadata_amount(inode, lblock));
1258 trace_ext4_da_reserve_space(inode, md_needed);
1261 * We do still charge estimated metadata to the sb though;
1262 * we cannot afford to run out of free blocks.
1264 if (ext4_claim_free_clusters(sbi, md_needed, 0)) {
1265 ei->i_da_metadata_calc_len = save_len;
1266 ei->i_da_metadata_calc_last_lblock = save_last_lblock;
1267 spin_unlock(&ei->i_block_reservation_lock);
1268 return -ENOSPC;
1270 ei->i_reserved_meta_blocks += md_needed;
1271 spin_unlock(&ei->i_block_reservation_lock);
1273 return 0; /* success */
1277 * Reserve a single cluster located at lblock
1279 static int ext4_da_reserve_space(struct inode *inode, ext4_lblk_t lblock)
1281 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1282 struct ext4_inode_info *ei = EXT4_I(inode);
1283 unsigned int md_needed;
1284 int ret;
1285 ext4_lblk_t save_last_lblock;
1286 int save_len;
1289 * We will charge metadata quota at writeout time; this saves
1290 * us from metadata over-estimation, though we may go over by
1291 * a small amount in the end. Here we just reserve for data.
1293 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1294 if (ret)
1295 return ret;
1298 * recalculate the amount of metadata blocks to reserve
1299 * in order to allocate nrblocks
1300 * worse case is one extent per block
1302 spin_lock(&ei->i_block_reservation_lock);
1304 * ext4_calc_metadata_amount() has side effects, which we have
1305 * to be prepared undo if we fail to claim space.
1307 save_len = ei->i_da_metadata_calc_len;
1308 save_last_lblock = ei->i_da_metadata_calc_last_lblock;
1309 md_needed = EXT4_NUM_B2C(sbi,
1310 ext4_calc_metadata_amount(inode, lblock));
1311 trace_ext4_da_reserve_space(inode, md_needed);
1314 * We do still charge estimated metadata to the sb though;
1315 * we cannot afford to run out of free blocks.
1317 if (ext4_claim_free_clusters(sbi, md_needed + 1, 0)) {
1318 ei->i_da_metadata_calc_len = save_len;
1319 ei->i_da_metadata_calc_last_lblock = save_last_lblock;
1320 spin_unlock(&ei->i_block_reservation_lock);
1321 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1322 return -ENOSPC;
1324 ei->i_reserved_data_blocks++;
1325 ei->i_reserved_meta_blocks += md_needed;
1326 spin_unlock(&ei->i_block_reservation_lock);
1328 return 0; /* success */
1331 static void ext4_da_release_space(struct inode *inode, int to_free)
1333 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1334 struct ext4_inode_info *ei = EXT4_I(inode);
1336 if (!to_free)
1337 return; /* Nothing to release, exit */
1339 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1341 trace_ext4_da_release_space(inode, to_free);
1342 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1344 * if there aren't enough reserved blocks, then the
1345 * counter is messed up somewhere. Since this
1346 * function is called from invalidate page, it's
1347 * harmless to return without any action.
1349 ext4_warning(inode->i_sb, "ext4_da_release_space: "
1350 "ino %lu, to_free %d with only %d reserved "
1351 "data blocks", inode->i_ino, to_free,
1352 ei->i_reserved_data_blocks);
1353 WARN_ON(1);
1354 to_free = ei->i_reserved_data_blocks;
1356 ei->i_reserved_data_blocks -= to_free;
1358 if (ei->i_reserved_data_blocks == 0) {
1360 * We can release all of the reserved metadata blocks
1361 * only when we have written all of the delayed
1362 * allocation blocks.
1363 * Note that in case of bigalloc, i_reserved_meta_blocks,
1364 * i_reserved_data_blocks, etc. refer to number of clusters.
1366 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
1367 ei->i_reserved_meta_blocks);
1368 ei->i_reserved_meta_blocks = 0;
1369 ei->i_da_metadata_calc_len = 0;
1372 /* update fs dirty data blocks counter */
1373 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1375 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1377 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1380 static void ext4_da_page_release_reservation(struct page *page,
1381 unsigned int offset,
1382 unsigned int length)
1384 int to_release = 0, contiguous_blks = 0;
1385 struct buffer_head *head, *bh;
1386 unsigned int curr_off = 0;
1387 struct inode *inode = page->mapping->host;
1388 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1389 unsigned int stop = offset + length;
1390 int num_clusters;
1391 ext4_fsblk_t lblk;
1393 BUG_ON(stop > PAGE_CACHE_SIZE || stop < length);
1395 head = page_buffers(page);
1396 bh = head;
1397 do {
1398 unsigned int next_off = curr_off + bh->b_size;
1400 if (next_off > stop)
1401 break;
1403 if ((offset <= curr_off) && (buffer_delay(bh))) {
1404 to_release++;
1405 contiguous_blks++;
1406 clear_buffer_delay(bh);
1407 } else if (contiguous_blks) {
1408 lblk = page->index <<
1409 (PAGE_CACHE_SHIFT - inode->i_blkbits);
1410 lblk += (curr_off >> inode->i_blkbits) -
1411 contiguous_blks;
1412 ext4_es_remove_extent(inode, lblk, contiguous_blks);
1413 contiguous_blks = 0;
1415 curr_off = next_off;
1416 } while ((bh = bh->b_this_page) != head);
1418 if (contiguous_blks) {
1419 lblk = page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1420 lblk += (curr_off >> inode->i_blkbits) - contiguous_blks;
1421 ext4_es_remove_extent(inode, lblk, contiguous_blks);
1424 /* If we have released all the blocks belonging to a cluster, then we
1425 * need to release the reserved space for that cluster. */
1426 num_clusters = EXT4_NUM_B2C(sbi, to_release);
1427 while (num_clusters > 0) {
1428 lblk = (page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits)) +
1429 ((num_clusters - 1) << sbi->s_cluster_bits);
1430 if (sbi->s_cluster_ratio == 1 ||
1431 !ext4_find_delalloc_cluster(inode, lblk))
1432 ext4_da_release_space(inode, 1);
1434 num_clusters--;
1439 * Delayed allocation stuff
1442 struct mpage_da_data {
1443 struct inode *inode;
1444 struct writeback_control *wbc;
1446 pgoff_t first_page; /* The first page to write */
1447 pgoff_t next_page; /* Current page to examine */
1448 pgoff_t last_page; /* Last page to examine */
1450 * Extent to map - this can be after first_page because that can be
1451 * fully mapped. We somewhat abuse m_flags to store whether the extent
1452 * is delalloc or unwritten.
1454 struct ext4_map_blocks map;
1455 struct ext4_io_submit io_submit; /* IO submission data */
1458 static void mpage_release_unused_pages(struct mpage_da_data *mpd,
1459 bool invalidate)
1461 int nr_pages, i;
1462 pgoff_t index, end;
1463 struct pagevec pvec;
1464 struct inode *inode = mpd->inode;
1465 struct address_space *mapping = inode->i_mapping;
1467 /* This is necessary when next_page == 0. */
1468 if (mpd->first_page >= mpd->next_page)
1469 return;
1471 index = mpd->first_page;
1472 end = mpd->next_page - 1;
1473 if (invalidate) {
1474 ext4_lblk_t start, last;
1475 start = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1476 last = end << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1477 ext4_es_remove_extent(inode, start, last - start + 1);
1480 pagevec_init(&pvec, 0);
1481 while (index <= end) {
1482 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1483 if (nr_pages == 0)
1484 break;
1485 for (i = 0; i < nr_pages; i++) {
1486 struct page *page = pvec.pages[i];
1487 if (page->index > end)
1488 break;
1489 BUG_ON(!PageLocked(page));
1490 BUG_ON(PageWriteback(page));
1491 if (invalidate) {
1492 block_invalidatepage(page, 0, PAGE_CACHE_SIZE);
1493 ClearPageUptodate(page);
1495 unlock_page(page);
1497 index = pvec.pages[nr_pages - 1]->index + 1;
1498 pagevec_release(&pvec);
1502 static void ext4_print_free_blocks(struct inode *inode)
1504 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1505 struct super_block *sb = inode->i_sb;
1506 struct ext4_inode_info *ei = EXT4_I(inode);
1508 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1509 EXT4_C2B(EXT4_SB(inode->i_sb),
1510 ext4_count_free_clusters(sb)));
1511 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1512 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1513 (long long) EXT4_C2B(EXT4_SB(sb),
1514 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1515 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1516 (long long) EXT4_C2B(EXT4_SB(sb),
1517 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1518 ext4_msg(sb, KERN_CRIT, "Block reservation details");
1519 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1520 ei->i_reserved_data_blocks);
1521 ext4_msg(sb, KERN_CRIT, "i_reserved_meta_blocks=%u",
1522 ei->i_reserved_meta_blocks);
1523 ext4_msg(sb, KERN_CRIT, "i_allocated_meta_blocks=%u",
1524 ei->i_allocated_meta_blocks);
1525 return;
1528 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1530 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1534 * This function is grabs code from the very beginning of
1535 * ext4_map_blocks, but assumes that the caller is from delayed write
1536 * time. This function looks up the requested blocks and sets the
1537 * buffer delay bit under the protection of i_data_sem.
1539 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1540 struct ext4_map_blocks *map,
1541 struct buffer_head *bh)
1543 struct extent_status es;
1544 int retval;
1545 sector_t invalid_block = ~((sector_t) 0xffff);
1546 #ifdef ES_AGGRESSIVE_TEST
1547 struct ext4_map_blocks orig_map;
1549 memcpy(&orig_map, map, sizeof(*map));
1550 #endif
1552 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1553 invalid_block = ~0;
1555 map->m_flags = 0;
1556 ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
1557 "logical block %lu\n", inode->i_ino, map->m_len,
1558 (unsigned long) map->m_lblk);
1560 /* Lookup extent status tree firstly */
1561 if (ext4_es_lookup_extent(inode, iblock, &es)) {
1562 ext4_es_lru_add(inode);
1563 if (ext4_es_is_hole(&es)) {
1564 retval = 0;
1565 down_read(&EXT4_I(inode)->i_data_sem);
1566 goto add_delayed;
1570 * Delayed extent could be allocated by fallocate.
1571 * So we need to check it.
1573 if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1574 map_bh(bh, inode->i_sb, invalid_block);
1575 set_buffer_new(bh);
1576 set_buffer_delay(bh);
1577 return 0;
1580 map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1581 retval = es.es_len - (iblock - es.es_lblk);
1582 if (retval > map->m_len)
1583 retval = map->m_len;
1584 map->m_len = retval;
1585 if (ext4_es_is_written(&es))
1586 map->m_flags |= EXT4_MAP_MAPPED;
1587 else if (ext4_es_is_unwritten(&es))
1588 map->m_flags |= EXT4_MAP_UNWRITTEN;
1589 else
1590 BUG_ON(1);
1592 #ifdef ES_AGGRESSIVE_TEST
1593 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1594 #endif
1595 return retval;
1599 * Try to see if we can get the block without requesting a new
1600 * file system block.
1602 down_read(&EXT4_I(inode)->i_data_sem);
1603 if (ext4_has_inline_data(inode)) {
1605 * We will soon create blocks for this page, and let
1606 * us pretend as if the blocks aren't allocated yet.
1607 * In case of clusters, we have to handle the work
1608 * of mapping from cluster so that the reserved space
1609 * is calculated properly.
1611 if ((EXT4_SB(inode->i_sb)->s_cluster_ratio > 1) &&
1612 ext4_find_delalloc_cluster(inode, map->m_lblk))
1613 map->m_flags |= EXT4_MAP_FROM_CLUSTER;
1614 retval = 0;
1615 } else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1616 retval = ext4_ext_map_blocks(NULL, inode, map,
1617 EXT4_GET_BLOCKS_NO_PUT_HOLE);
1618 else
1619 retval = ext4_ind_map_blocks(NULL, inode, map,
1620 EXT4_GET_BLOCKS_NO_PUT_HOLE);
1622 add_delayed:
1623 if (retval == 0) {
1624 int ret;
1626 * XXX: __block_prepare_write() unmaps passed block,
1627 * is it OK?
1630 * If the block was allocated from previously allocated cluster,
1631 * then we don't need to reserve it again. However we still need
1632 * to reserve metadata for every block we're going to write.
1634 if (!(map->m_flags & EXT4_MAP_FROM_CLUSTER)) {
1635 ret = ext4_da_reserve_space(inode, iblock);
1636 if (ret) {
1637 /* not enough space to reserve */
1638 retval = ret;
1639 goto out_unlock;
1641 } else {
1642 ret = ext4_da_reserve_metadata(inode, iblock);
1643 if (ret) {
1644 /* not enough space to reserve */
1645 retval = ret;
1646 goto out_unlock;
1650 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1651 ~0, EXTENT_STATUS_DELAYED);
1652 if (ret) {
1653 retval = ret;
1654 goto out_unlock;
1657 /* Clear EXT4_MAP_FROM_CLUSTER flag since its purpose is served
1658 * and it should not appear on the bh->b_state.
1660 map->m_flags &= ~EXT4_MAP_FROM_CLUSTER;
1662 map_bh(bh, inode->i_sb, invalid_block);
1663 set_buffer_new(bh);
1664 set_buffer_delay(bh);
1665 } else if (retval > 0) {
1666 int ret;
1667 unsigned int status;
1669 if (unlikely(retval != map->m_len)) {
1670 ext4_warning(inode->i_sb,
1671 "ES len assertion failed for inode "
1672 "%lu: retval %d != map->m_len %d",
1673 inode->i_ino, retval, map->m_len);
1674 WARN_ON(1);
1677 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1678 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1679 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1680 map->m_pblk, status);
1681 if (ret != 0)
1682 retval = ret;
1685 out_unlock:
1686 up_read((&EXT4_I(inode)->i_data_sem));
1688 return retval;
1692 * This is a special get_blocks_t callback which is used by
1693 * ext4_da_write_begin(). It will either return mapped block or
1694 * reserve space for a single block.
1696 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1697 * We also have b_blocknr = -1 and b_bdev initialized properly
1699 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1700 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1701 * initialized properly.
1703 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1704 struct buffer_head *bh, int create)
1706 struct ext4_map_blocks map;
1707 int ret = 0;
1709 BUG_ON(create == 0);
1710 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1712 map.m_lblk = iblock;
1713 map.m_len = 1;
1716 * first, we need to know whether the block is allocated already
1717 * preallocated blocks are unmapped but should treated
1718 * the same as allocated blocks.
1720 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1721 if (ret <= 0)
1722 return ret;
1724 map_bh(bh, inode->i_sb, map.m_pblk);
1725 ext4_update_bh_state(bh, map.m_flags);
1727 if (buffer_unwritten(bh)) {
1728 /* A delayed write to unwritten bh should be marked
1729 * new and mapped. Mapped ensures that we don't do
1730 * get_block multiple times when we write to the same
1731 * offset and new ensures that we do proper zero out
1732 * for partial write.
1734 set_buffer_new(bh);
1735 set_buffer_mapped(bh);
1737 return 0;
1740 static int bget_one(handle_t *handle, struct buffer_head *bh)
1742 get_bh(bh);
1743 return 0;
1746 static int bput_one(handle_t *handle, struct buffer_head *bh)
1748 put_bh(bh);
1749 return 0;
1752 static int __ext4_journalled_writepage(struct page *page,
1753 unsigned int len)
1755 struct address_space *mapping = page->mapping;
1756 struct inode *inode = mapping->host;
1757 struct buffer_head *page_bufs = NULL;
1758 handle_t *handle = NULL;
1759 int ret = 0, err = 0;
1760 int inline_data = ext4_has_inline_data(inode);
1761 struct buffer_head *inode_bh = NULL;
1763 ClearPageChecked(page);
1765 if (inline_data) {
1766 BUG_ON(page->index != 0);
1767 BUG_ON(len > ext4_get_max_inline_size(inode));
1768 inode_bh = ext4_journalled_write_inline_data(inode, len, page);
1769 if (inode_bh == NULL)
1770 goto out;
1771 } else {
1772 page_bufs = page_buffers(page);
1773 if (!page_bufs) {
1774 BUG();
1775 goto out;
1777 ext4_walk_page_buffers(handle, page_bufs, 0, len,
1778 NULL, bget_one);
1781 * We need to release the page lock before we start the
1782 * journal, so grab a reference so the page won't disappear
1783 * out from under us.
1785 get_page(page);
1786 unlock_page(page);
1788 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
1789 ext4_writepage_trans_blocks(inode));
1790 if (IS_ERR(handle)) {
1791 ret = PTR_ERR(handle);
1792 put_page(page);
1793 goto out_no_pagelock;
1795 BUG_ON(!ext4_handle_valid(handle));
1797 lock_page(page);
1798 put_page(page);
1799 if (page->mapping != mapping) {
1800 /* The page got truncated from under us */
1801 ext4_journal_stop(handle);
1802 ret = 0;
1803 goto out;
1806 if (inline_data) {
1807 BUFFER_TRACE(inode_bh, "get write access");
1808 ret = ext4_journal_get_write_access(handle, inode_bh);
1810 err = ext4_handle_dirty_metadata(handle, inode, inode_bh);
1812 } else {
1813 ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1814 do_journal_get_write_access);
1816 err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1817 write_end_fn);
1819 if (ret == 0)
1820 ret = err;
1821 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1822 err = ext4_journal_stop(handle);
1823 if (!ret)
1824 ret = err;
1826 if (!ext4_has_inline_data(inode))
1827 ext4_walk_page_buffers(NULL, page_bufs, 0, len,
1828 NULL, bput_one);
1829 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1830 out:
1831 unlock_page(page);
1832 out_no_pagelock:
1833 brelse(inode_bh);
1834 return ret;
1838 * Note that we don't need to start a transaction unless we're journaling data
1839 * because we should have holes filled from ext4_page_mkwrite(). We even don't
1840 * need to file the inode to the transaction's list in ordered mode because if
1841 * we are writing back data added by write(), the inode is already there and if
1842 * we are writing back data modified via mmap(), no one guarantees in which
1843 * transaction the data will hit the disk. In case we are journaling data, we
1844 * cannot start transaction directly because transaction start ranks above page
1845 * lock so we have to do some magic.
1847 * This function can get called via...
1848 * - ext4_writepages after taking page lock (have journal handle)
1849 * - journal_submit_inode_data_buffers (no journal handle)
1850 * - shrink_page_list via the kswapd/direct reclaim (no journal handle)
1851 * - grab_page_cache when doing write_begin (have journal handle)
1853 * We don't do any block allocation in this function. If we have page with
1854 * multiple blocks we need to write those buffer_heads that are mapped. This
1855 * is important for mmaped based write. So if we do with blocksize 1K
1856 * truncate(f, 1024);
1857 * a = mmap(f, 0, 4096);
1858 * a[0] = 'a';
1859 * truncate(f, 4096);
1860 * we have in the page first buffer_head mapped via page_mkwrite call back
1861 * but other buffer_heads would be unmapped but dirty (dirty done via the
1862 * do_wp_page). So writepage should write the first block. If we modify
1863 * the mmap area beyond 1024 we will again get a page_fault and the
1864 * page_mkwrite callback will do the block allocation and mark the
1865 * buffer_heads mapped.
1867 * We redirty the page if we have any buffer_heads that is either delay or
1868 * unwritten in the page.
1870 * We can get recursively called as show below.
1872 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
1873 * ext4_writepage()
1875 * But since we don't do any block allocation we should not deadlock.
1876 * Page also have the dirty flag cleared so we don't get recurive page_lock.
1878 static int ext4_writepage(struct page *page,
1879 struct writeback_control *wbc)
1881 int ret = 0;
1882 loff_t size;
1883 unsigned int len;
1884 struct buffer_head *page_bufs = NULL;
1885 struct inode *inode = page->mapping->host;
1886 struct ext4_io_submit io_submit;
1887 bool keep_towrite = false;
1889 trace_ext4_writepage(page);
1890 size = i_size_read(inode);
1891 if (page->index == size >> PAGE_CACHE_SHIFT)
1892 len = size & ~PAGE_CACHE_MASK;
1893 else
1894 len = PAGE_CACHE_SIZE;
1896 page_bufs = page_buffers(page);
1898 * We cannot do block allocation or other extent handling in this
1899 * function. If there are buffers needing that, we have to redirty
1900 * the page. But we may reach here when we do a journal commit via
1901 * journal_submit_inode_data_buffers() and in that case we must write
1902 * allocated buffers to achieve data=ordered mode guarantees.
1904 if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
1905 ext4_bh_delay_or_unwritten)) {
1906 redirty_page_for_writepage(wbc, page);
1907 if (current->flags & PF_MEMALLOC) {
1909 * For memory cleaning there's no point in writing only
1910 * some buffers. So just bail out. Warn if we came here
1911 * from direct reclaim.
1913 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
1914 == PF_MEMALLOC);
1915 unlock_page(page);
1916 return 0;
1918 keep_towrite = true;
1921 if (PageChecked(page) && ext4_should_journal_data(inode))
1923 * It's mmapped pagecache. Add buffers and journal it. There
1924 * doesn't seem much point in redirtying the page here.
1926 return __ext4_journalled_writepage(page, len);
1928 ext4_io_submit_init(&io_submit, wbc);
1929 io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
1930 if (!io_submit.io_end) {
1931 redirty_page_for_writepage(wbc, page);
1932 unlock_page(page);
1933 return -ENOMEM;
1935 ret = ext4_bio_write_page(&io_submit, page, len, wbc, keep_towrite);
1936 ext4_io_submit(&io_submit);
1937 /* Drop io_end reference we got from init */
1938 ext4_put_io_end_defer(io_submit.io_end);
1939 return ret;
1942 static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
1944 int len;
1945 loff_t size = i_size_read(mpd->inode);
1946 int err;
1948 BUG_ON(page->index != mpd->first_page);
1949 if (page->index == size >> PAGE_CACHE_SHIFT)
1950 len = size & ~PAGE_CACHE_MASK;
1951 else
1952 len = PAGE_CACHE_SIZE;
1953 clear_page_dirty_for_io(page);
1954 err = ext4_bio_write_page(&mpd->io_submit, page, len, mpd->wbc, false);
1955 if (!err)
1956 mpd->wbc->nr_to_write--;
1957 mpd->first_page++;
1959 return err;
1962 #define BH_FLAGS ((1 << BH_Unwritten) | (1 << BH_Delay))
1965 * mballoc gives us at most this number of blocks...
1966 * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
1967 * The rest of mballoc seems to handle chunks up to full group size.
1969 #define MAX_WRITEPAGES_EXTENT_LEN 2048
1972 * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
1974 * @mpd - extent of blocks
1975 * @lblk - logical number of the block in the file
1976 * @bh - buffer head we want to add to the extent
1978 * The function is used to collect contig. blocks in the same state. If the
1979 * buffer doesn't require mapping for writeback and we haven't started the
1980 * extent of buffers to map yet, the function returns 'true' immediately - the
1981 * caller can write the buffer right away. Otherwise the function returns true
1982 * if the block has been added to the extent, false if the block couldn't be
1983 * added.
1985 static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
1986 struct buffer_head *bh)
1988 struct ext4_map_blocks *map = &mpd->map;
1990 /* Buffer that doesn't need mapping for writeback? */
1991 if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
1992 (!buffer_delay(bh) && !buffer_unwritten(bh))) {
1993 /* So far no extent to map => we write the buffer right away */
1994 if (map->m_len == 0)
1995 return true;
1996 return false;
1999 /* First block in the extent? */
2000 if (map->m_len == 0) {
2001 map->m_lblk = lblk;
2002 map->m_len = 1;
2003 map->m_flags = bh->b_state & BH_FLAGS;
2004 return true;
2007 /* Don't go larger than mballoc is willing to allocate */
2008 if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
2009 return false;
2011 /* Can we merge the block to our big extent? */
2012 if (lblk == map->m_lblk + map->m_len &&
2013 (bh->b_state & BH_FLAGS) == map->m_flags) {
2014 map->m_len++;
2015 return true;
2017 return false;
2021 * mpage_process_page_bufs - submit page buffers for IO or add them to extent
2023 * @mpd - extent of blocks for mapping
2024 * @head - the first buffer in the page
2025 * @bh - buffer we should start processing from
2026 * @lblk - logical number of the block in the file corresponding to @bh
2028 * Walk through page buffers from @bh upto @head (exclusive) and either submit
2029 * the page for IO if all buffers in this page were mapped and there's no
2030 * accumulated extent of buffers to map or add buffers in the page to the
2031 * extent of buffers to map. The function returns 1 if the caller can continue
2032 * by processing the next page, 0 if it should stop adding buffers to the
2033 * extent to map because we cannot extend it anymore. It can also return value
2034 * < 0 in case of error during IO submission.
2036 static int mpage_process_page_bufs(struct mpage_da_data *mpd,
2037 struct buffer_head *head,
2038 struct buffer_head *bh,
2039 ext4_lblk_t lblk)
2041 struct inode *inode = mpd->inode;
2042 int err;
2043 ext4_lblk_t blocks = (i_size_read(inode) + (1 << inode->i_blkbits) - 1)
2044 >> inode->i_blkbits;
2046 do {
2047 BUG_ON(buffer_locked(bh));
2049 if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
2050 /* Found extent to map? */
2051 if (mpd->map.m_len)
2052 return 0;
2053 /* Everything mapped so far and we hit EOF */
2054 break;
2056 } while (lblk++, (bh = bh->b_this_page) != head);
2057 /* So far everything mapped? Submit the page for IO. */
2058 if (mpd->map.m_len == 0) {
2059 err = mpage_submit_page(mpd, head->b_page);
2060 if (err < 0)
2061 return err;
2063 return lblk < blocks;
2067 * mpage_map_buffers - update buffers corresponding to changed extent and
2068 * submit fully mapped pages for IO
2070 * @mpd - description of extent to map, on return next extent to map
2072 * Scan buffers corresponding to changed extent (we expect corresponding pages
2073 * to be already locked) and update buffer state according to new extent state.
2074 * We map delalloc buffers to their physical location, clear unwritten bits,
2075 * and mark buffers as uninit when we perform writes to unwritten extents
2076 * and do extent conversion after IO is finished. If the last page is not fully
2077 * mapped, we update @map to the next extent in the last page that needs
2078 * mapping. Otherwise we submit the page for IO.
2080 static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
2082 struct pagevec pvec;
2083 int nr_pages, i;
2084 struct inode *inode = mpd->inode;
2085 struct buffer_head *head, *bh;
2086 int bpp_bits = PAGE_CACHE_SHIFT - inode->i_blkbits;
2087 pgoff_t start, end;
2088 ext4_lblk_t lblk;
2089 sector_t pblock;
2090 int err;
2092 start = mpd->map.m_lblk >> bpp_bits;
2093 end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
2094 lblk = start << bpp_bits;
2095 pblock = mpd->map.m_pblk;
2097 pagevec_init(&pvec, 0);
2098 while (start <= end) {
2099 nr_pages = pagevec_lookup(&pvec, inode->i_mapping, start,
2100 PAGEVEC_SIZE);
2101 if (nr_pages == 0)
2102 break;
2103 for (i = 0; i < nr_pages; i++) {
2104 struct page *page = pvec.pages[i];
2106 if (page->index > end)
2107 break;
2108 /* Up to 'end' pages must be contiguous */
2109 BUG_ON(page->index != start);
2110 bh = head = page_buffers(page);
2111 do {
2112 if (lblk < mpd->map.m_lblk)
2113 continue;
2114 if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2116 * Buffer after end of mapped extent.
2117 * Find next buffer in the page to map.
2119 mpd->map.m_len = 0;
2120 mpd->map.m_flags = 0;
2122 * FIXME: If dioread_nolock supports
2123 * blocksize < pagesize, we need to make
2124 * sure we add size mapped so far to
2125 * io_end->size as the following call
2126 * can submit the page for IO.
2128 err = mpage_process_page_bufs(mpd, head,
2129 bh, lblk);
2130 pagevec_release(&pvec);
2131 if (err > 0)
2132 err = 0;
2133 return err;
2135 if (buffer_delay(bh)) {
2136 clear_buffer_delay(bh);
2137 bh->b_blocknr = pblock++;
2139 clear_buffer_unwritten(bh);
2140 } while (lblk++, (bh = bh->b_this_page) != head);
2143 * FIXME: This is going to break if dioread_nolock
2144 * supports blocksize < pagesize as we will try to
2145 * convert potentially unmapped parts of inode.
2147 mpd->io_submit.io_end->size += PAGE_CACHE_SIZE;
2148 /* Page fully mapped - let IO run! */
2149 err = mpage_submit_page(mpd, page);
2150 if (err < 0) {
2151 pagevec_release(&pvec);
2152 return err;
2154 start++;
2156 pagevec_release(&pvec);
2158 /* Extent fully mapped and matches with page boundary. We are done. */
2159 mpd->map.m_len = 0;
2160 mpd->map.m_flags = 0;
2161 return 0;
2164 static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2166 struct inode *inode = mpd->inode;
2167 struct ext4_map_blocks *map = &mpd->map;
2168 int get_blocks_flags;
2169 int err, dioread_nolock;
2171 trace_ext4_da_write_pages_extent(inode, map);
2173 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2174 * to convert an unwritten extent to be initialized (in the case
2175 * where we have written into one or more preallocated blocks). It is
2176 * possible that we're going to need more metadata blocks than
2177 * previously reserved. However we must not fail because we're in
2178 * writeback and there is nothing we can do about it so it might result
2179 * in data loss. So use reserved blocks to allocate metadata if
2180 * possible.
2182 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if the blocks
2183 * in question are delalloc blocks. This affects functions in many
2184 * different parts of the allocation call path. This flag exists
2185 * primarily because we don't want to change *many* call functions, so
2186 * ext4_map_blocks() will set the EXT4_STATE_DELALLOC_RESERVED flag
2187 * once the inode's allocation semaphore is taken.
2189 get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2190 EXT4_GET_BLOCKS_METADATA_NOFAIL;
2191 dioread_nolock = ext4_should_dioread_nolock(inode);
2192 if (dioread_nolock)
2193 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2194 if (map->m_flags & (1 << BH_Delay))
2195 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2197 err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2198 if (err < 0)
2199 return err;
2200 if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
2201 if (!mpd->io_submit.io_end->handle &&
2202 ext4_handle_valid(handle)) {
2203 mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2204 handle->h_rsv_handle = NULL;
2206 ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
2209 BUG_ON(map->m_len == 0);
2210 if (map->m_flags & EXT4_MAP_NEW) {
2211 struct block_device *bdev = inode->i_sb->s_bdev;
2212 int i;
2214 for (i = 0; i < map->m_len; i++)
2215 unmap_underlying_metadata(bdev, map->m_pblk + i);
2217 return 0;
2221 * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2222 * mpd->len and submit pages underlying it for IO
2224 * @handle - handle for journal operations
2225 * @mpd - extent to map
2226 * @give_up_on_write - we set this to true iff there is a fatal error and there
2227 * is no hope of writing the data. The caller should discard
2228 * dirty pages to avoid infinite loops.
2230 * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2231 * delayed, blocks are allocated, if it is unwritten, we may need to convert
2232 * them to initialized or split the described range from larger unwritten
2233 * extent. Note that we need not map all the described range since allocation
2234 * can return less blocks or the range is covered by more unwritten extents. We
2235 * cannot map more because we are limited by reserved transaction credits. On
2236 * the other hand we always make sure that the last touched page is fully
2237 * mapped so that it can be written out (and thus forward progress is
2238 * guaranteed). After mapping we submit all mapped pages for IO.
2240 static int mpage_map_and_submit_extent(handle_t *handle,
2241 struct mpage_da_data *mpd,
2242 bool *give_up_on_write)
2244 struct inode *inode = mpd->inode;
2245 struct ext4_map_blocks *map = &mpd->map;
2246 int err;
2247 loff_t disksize;
2248 int progress = 0;
2250 mpd->io_submit.io_end->offset =
2251 ((loff_t)map->m_lblk) << inode->i_blkbits;
2252 do {
2253 err = mpage_map_one_extent(handle, mpd);
2254 if (err < 0) {
2255 struct super_block *sb = inode->i_sb;
2257 if (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)
2258 goto invalidate_dirty_pages;
2260 * Let the uper layers retry transient errors.
2261 * In the case of ENOSPC, if ext4_count_free_blocks()
2262 * is non-zero, a commit should free up blocks.
2264 if ((err == -ENOMEM) ||
2265 (err == -ENOSPC && ext4_count_free_clusters(sb))) {
2266 if (progress)
2267 goto update_disksize;
2268 return err;
2270 ext4_msg(sb, KERN_CRIT,
2271 "Delayed block allocation failed for "
2272 "inode %lu at logical offset %llu with"
2273 " max blocks %u with error %d",
2274 inode->i_ino,
2275 (unsigned long long)map->m_lblk,
2276 (unsigned)map->m_len, -err);
2277 ext4_msg(sb, KERN_CRIT,
2278 "This should not happen!! Data will "
2279 "be lost\n");
2280 if (err == -ENOSPC)
2281 ext4_print_free_blocks(inode);
2282 invalidate_dirty_pages:
2283 *give_up_on_write = true;
2284 return err;
2286 progress = 1;
2288 * Update buffer state, submit mapped pages, and get us new
2289 * extent to map
2291 err = mpage_map_and_submit_buffers(mpd);
2292 if (err < 0)
2293 goto update_disksize;
2294 } while (map->m_len);
2296 update_disksize:
2298 * Update on-disk size after IO is submitted. Races with
2299 * truncate are avoided by checking i_size under i_data_sem.
2301 disksize = ((loff_t)mpd->first_page) << PAGE_CACHE_SHIFT;
2302 if (disksize > EXT4_I(inode)->i_disksize) {
2303 int err2;
2304 loff_t i_size;
2306 down_write(&EXT4_I(inode)->i_data_sem);
2307 i_size = i_size_read(inode);
2308 if (disksize > i_size)
2309 disksize = i_size;
2310 if (disksize > EXT4_I(inode)->i_disksize)
2311 EXT4_I(inode)->i_disksize = disksize;
2312 err2 = ext4_mark_inode_dirty(handle, inode);
2313 up_write(&EXT4_I(inode)->i_data_sem);
2314 if (err2)
2315 ext4_error(inode->i_sb,
2316 "Failed to mark inode %lu dirty",
2317 inode->i_ino);
2318 if (!err)
2319 err = err2;
2321 return err;
2325 * Calculate the total number of credits to reserve for one writepages
2326 * iteration. This is called from ext4_writepages(). We map an extent of
2327 * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2328 * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2329 * bpp - 1 blocks in bpp different extents.
2331 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2333 int bpp = ext4_journal_blocks_per_page(inode);
2335 return ext4_meta_trans_blocks(inode,
2336 MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2340 * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2341 * and underlying extent to map
2343 * @mpd - where to look for pages
2345 * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2346 * IO immediately. When we find a page which isn't mapped we start accumulating
2347 * extent of buffers underlying these pages that needs mapping (formed by
2348 * either delayed or unwritten buffers). We also lock the pages containing
2349 * these buffers. The extent found is returned in @mpd structure (starting at
2350 * mpd->lblk with length mpd->len blocks).
2352 * Note that this function can attach bios to one io_end structure which are
2353 * neither logically nor physically contiguous. Although it may seem as an
2354 * unnecessary complication, it is actually inevitable in blocksize < pagesize
2355 * case as we need to track IO to all buffers underlying a page in one io_end.
2357 static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
2359 struct address_space *mapping = mpd->inode->i_mapping;
2360 struct pagevec pvec;
2361 unsigned int nr_pages;
2362 long left = mpd->wbc->nr_to_write;
2363 pgoff_t index = mpd->first_page;
2364 pgoff_t end = mpd->last_page;
2365 int tag;
2366 int i, err = 0;
2367 int blkbits = mpd->inode->i_blkbits;
2368 ext4_lblk_t lblk;
2369 struct buffer_head *head;
2371 if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
2372 tag = PAGECACHE_TAG_TOWRITE;
2373 else
2374 tag = PAGECACHE_TAG_DIRTY;
2376 pagevec_init(&pvec, 0);
2377 mpd->map.m_len = 0;
2378 mpd->next_page = index;
2379 while (index <= end) {
2380 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
2381 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
2382 if (nr_pages == 0)
2383 goto out;
2385 for (i = 0; i < nr_pages; i++) {
2386 struct page *page = pvec.pages[i];
2389 * At this point, the page may be truncated or
2390 * invalidated (changing page->mapping to NULL), or
2391 * even swizzled back from swapper_space to tmpfs file
2392 * mapping. However, page->index will not change
2393 * because we have a reference on the page.
2395 if (page->index > end)
2396 goto out;
2399 * Accumulated enough dirty pages? This doesn't apply
2400 * to WB_SYNC_ALL mode. For integrity sync we have to
2401 * keep going because someone may be concurrently
2402 * dirtying pages, and we might have synced a lot of
2403 * newly appeared dirty pages, but have not synced all
2404 * of the old dirty pages.
2406 if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2407 goto out;
2409 /* If we can't merge this page, we are done. */
2410 if (mpd->map.m_len > 0 && mpd->next_page != page->index)
2411 goto out;
2413 lock_page(page);
2415 * If the page is no longer dirty, or its mapping no
2416 * longer corresponds to inode we are writing (which
2417 * means it has been truncated or invalidated), or the
2418 * page is already under writeback and we are not doing
2419 * a data integrity writeback, skip the page
2421 if (!PageDirty(page) ||
2422 (PageWriteback(page) &&
2423 (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
2424 unlikely(page->mapping != mapping)) {
2425 unlock_page(page);
2426 continue;
2429 wait_on_page_writeback(page);
2430 BUG_ON(PageWriteback(page));
2432 if (mpd->map.m_len == 0)
2433 mpd->first_page = page->index;
2434 mpd->next_page = page->index + 1;
2435 /* Add all dirty buffers to mpd */
2436 lblk = ((ext4_lblk_t)page->index) <<
2437 (PAGE_CACHE_SHIFT - blkbits);
2438 head = page_buffers(page);
2439 err = mpage_process_page_bufs(mpd, head, head, lblk);
2440 if (err <= 0)
2441 goto out;
2442 err = 0;
2443 left--;
2445 pagevec_release(&pvec);
2446 cond_resched();
2448 return 0;
2449 out:
2450 pagevec_release(&pvec);
2451 return err;
2454 static int __writepage(struct page *page, struct writeback_control *wbc,
2455 void *data)
2457 struct address_space *mapping = data;
2458 int ret = ext4_writepage(page, wbc);
2459 mapping_set_error(mapping, ret);
2460 return ret;
2463 static int ext4_writepages(struct address_space *mapping,
2464 struct writeback_control *wbc)
2466 pgoff_t writeback_index = 0;
2467 long nr_to_write = wbc->nr_to_write;
2468 int range_whole = 0;
2469 int cycled = 1;
2470 handle_t *handle = NULL;
2471 struct mpage_da_data mpd;
2472 struct inode *inode = mapping->host;
2473 int needed_blocks, rsv_blocks = 0, ret = 0;
2474 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2475 bool done;
2476 struct blk_plug plug;
2477 bool give_up_on_write = false;
2479 trace_ext4_writepages(inode, wbc);
2482 * No pages to write? This is mainly a kludge to avoid starting
2483 * a transaction for special inodes like journal inode on last iput()
2484 * because that could violate lock ordering on umount
2486 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2487 goto out_writepages;
2489 if (ext4_should_journal_data(inode)) {
2490 struct blk_plug plug;
2492 blk_start_plug(&plug);
2493 ret = write_cache_pages(mapping, wbc, __writepage, mapping);
2494 blk_finish_plug(&plug);
2495 goto out_writepages;
2499 * If the filesystem has aborted, it is read-only, so return
2500 * right away instead of dumping stack traces later on that
2501 * will obscure the real source of the problem. We test
2502 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2503 * the latter could be true if the filesystem is mounted
2504 * read-only, and in that case, ext4_writepages should
2505 * *never* be called, so if that ever happens, we would want
2506 * the stack trace.
2508 if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED)) {
2509 ret = -EROFS;
2510 goto out_writepages;
2513 if (ext4_should_dioread_nolock(inode)) {
2515 * We may need to convert up to one extent per block in
2516 * the page and we may dirty the inode.
2518 rsv_blocks = 1 + (PAGE_CACHE_SIZE >> inode->i_blkbits);
2522 * If we have inline data and arrive here, it means that
2523 * we will soon create the block for the 1st page, so
2524 * we'd better clear the inline data here.
2526 if (ext4_has_inline_data(inode)) {
2527 /* Just inode will be modified... */
2528 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2529 if (IS_ERR(handle)) {
2530 ret = PTR_ERR(handle);
2531 goto out_writepages;
2533 BUG_ON(ext4_test_inode_state(inode,
2534 EXT4_STATE_MAY_INLINE_DATA));
2535 ext4_destroy_inline_data(handle, inode);
2536 ext4_journal_stop(handle);
2539 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2540 range_whole = 1;
2542 if (wbc->range_cyclic) {
2543 writeback_index = mapping->writeback_index;
2544 if (writeback_index)
2545 cycled = 0;
2546 mpd.first_page = writeback_index;
2547 mpd.last_page = -1;
2548 } else {
2549 mpd.first_page = wbc->range_start >> PAGE_CACHE_SHIFT;
2550 mpd.last_page = wbc->range_end >> PAGE_CACHE_SHIFT;
2553 mpd.inode = inode;
2554 mpd.wbc = wbc;
2555 ext4_io_submit_init(&mpd.io_submit, wbc);
2556 retry:
2557 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2558 tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
2559 done = false;
2560 blk_start_plug(&plug);
2561 while (!done && mpd.first_page <= mpd.last_page) {
2562 /* For each extent of pages we use new io_end */
2563 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2564 if (!mpd.io_submit.io_end) {
2565 ret = -ENOMEM;
2566 break;
2570 * We have two constraints: We find one extent to map and we
2571 * must always write out whole page (makes a difference when
2572 * blocksize < pagesize) so that we don't block on IO when we
2573 * try to write out the rest of the page. Journalled mode is
2574 * not supported by delalloc.
2576 BUG_ON(ext4_should_journal_data(inode));
2577 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2579 /* start a new transaction */
2580 handle = ext4_journal_start_with_reserve(inode,
2581 EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
2582 if (IS_ERR(handle)) {
2583 ret = PTR_ERR(handle);
2584 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2585 "%ld pages, ino %lu; err %d", __func__,
2586 wbc->nr_to_write, inode->i_ino, ret);
2587 /* Release allocated io_end */
2588 ext4_put_io_end(mpd.io_submit.io_end);
2589 break;
2592 trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
2593 ret = mpage_prepare_extent_to_map(&mpd);
2594 if (!ret) {
2595 if (mpd.map.m_len)
2596 ret = mpage_map_and_submit_extent(handle, &mpd,
2597 &give_up_on_write);
2598 else {
2600 * We scanned the whole range (or exhausted
2601 * nr_to_write), submitted what was mapped and
2602 * didn't find anything needing mapping. We are
2603 * done.
2605 done = true;
2608 ext4_journal_stop(handle);
2609 /* Submit prepared bio */
2610 ext4_io_submit(&mpd.io_submit);
2611 /* Unlock pages we didn't use */
2612 mpage_release_unused_pages(&mpd, give_up_on_write);
2613 /* Drop our io_end reference we got from init */
2614 ext4_put_io_end(mpd.io_submit.io_end);
2616 if (ret == -ENOSPC && sbi->s_journal) {
2618 * Commit the transaction which would
2619 * free blocks released in the transaction
2620 * and try again
2622 jbd2_journal_force_commit_nested(sbi->s_journal);
2623 ret = 0;
2624 continue;
2626 /* Fatal error - ENOMEM, EIO... */
2627 if (ret)
2628 break;
2630 blk_finish_plug(&plug);
2631 if (!ret && !cycled && wbc->nr_to_write > 0) {
2632 cycled = 1;
2633 mpd.last_page = writeback_index - 1;
2634 mpd.first_page = 0;
2635 goto retry;
2638 /* Update index */
2639 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2641 * Set the writeback_index so that range_cyclic
2642 * mode will write it back later
2644 mapping->writeback_index = mpd.first_page;
2646 out_writepages:
2647 trace_ext4_writepages_result(inode, wbc, ret,
2648 nr_to_write - wbc->nr_to_write);
2649 return ret;
2652 static int ext4_nonda_switch(struct super_block *sb)
2654 s64 free_clusters, dirty_clusters;
2655 struct ext4_sb_info *sbi = EXT4_SB(sb);
2658 * switch to non delalloc mode if we are running low
2659 * on free block. The free block accounting via percpu
2660 * counters can get slightly wrong with percpu_counter_batch getting
2661 * accumulated on each CPU without updating global counters
2662 * Delalloc need an accurate free block accounting. So switch
2663 * to non delalloc when we are near to error range.
2665 free_clusters =
2666 percpu_counter_read_positive(&sbi->s_freeclusters_counter);
2667 dirty_clusters =
2668 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2670 * Start pushing delalloc when 1/2 of free blocks are dirty.
2672 if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
2673 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2675 if (2 * free_clusters < 3 * dirty_clusters ||
2676 free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
2678 * free block count is less than 150% of dirty blocks
2679 * or free blocks is less than watermark
2681 return 1;
2683 return 0;
2686 /* We always reserve for an inode update; the superblock could be there too */
2687 static int ext4_da_write_credits(struct inode *inode, loff_t pos, unsigned len)
2689 if (likely(EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
2690 EXT4_FEATURE_RO_COMPAT_LARGE_FILE)))
2691 return 1;
2693 if (pos + len <= 0x7fffffffULL)
2694 return 1;
2696 /* We might need to update the superblock to set LARGE_FILE */
2697 return 2;
2700 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2701 loff_t pos, unsigned len, unsigned flags,
2702 struct page **pagep, void **fsdata)
2704 int ret, retries = 0;
2705 struct page *page;
2706 pgoff_t index;
2707 struct inode *inode = mapping->host;
2708 handle_t *handle;
2710 index = pos >> PAGE_CACHE_SHIFT;
2712 if (ext4_nonda_switch(inode->i_sb)) {
2713 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2714 return ext4_write_begin(file, mapping, pos,
2715 len, flags, pagep, fsdata);
2717 *fsdata = (void *)0;
2718 trace_ext4_da_write_begin(inode, pos, len, flags);
2720 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2721 ret = ext4_da_write_inline_data_begin(mapping, inode,
2722 pos, len, flags,
2723 pagep, fsdata);
2724 if (ret < 0)
2725 return ret;
2726 if (ret == 1)
2727 return 0;
2731 * grab_cache_page_write_begin() can take a long time if the
2732 * system is thrashing due to memory pressure, or if the page
2733 * is being written back. So grab it first before we start
2734 * the transaction handle. This also allows us to allocate
2735 * the page (if needed) without using GFP_NOFS.
2737 retry_grab:
2738 page = grab_cache_page_write_begin(mapping, index, flags);
2739 if (!page)
2740 return -ENOMEM;
2741 unlock_page(page);
2744 * With delayed allocation, we don't log the i_disksize update
2745 * if there is delayed block allocation. But we still need
2746 * to journalling the i_disksize update if writes to the end
2747 * of file which has an already mapped buffer.
2749 retry_journal:
2750 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
2751 ext4_da_write_credits(inode, pos, len));
2752 if (IS_ERR(handle)) {
2753 page_cache_release(page);
2754 return PTR_ERR(handle);
2757 lock_page(page);
2758 if (page->mapping != mapping) {
2759 /* The page got truncated from under us */
2760 unlock_page(page);
2761 page_cache_release(page);
2762 ext4_journal_stop(handle);
2763 goto retry_grab;
2765 /* In case writeback began while the page was unlocked */
2766 wait_for_stable_page(page);
2768 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
2769 if (ret < 0) {
2770 unlock_page(page);
2771 ext4_journal_stop(handle);
2773 * block_write_begin may have instantiated a few blocks
2774 * outside i_size. Trim these off again. Don't need
2775 * i_size_read because we hold i_mutex.
2777 if (pos + len > inode->i_size)
2778 ext4_truncate_failed_write(inode);
2780 if (ret == -ENOSPC &&
2781 ext4_should_retry_alloc(inode->i_sb, &retries))
2782 goto retry_journal;
2784 page_cache_release(page);
2785 return ret;
2788 *pagep = page;
2789 return ret;
2793 * Check if we should update i_disksize
2794 * when write to the end of file but not require block allocation
2796 static int ext4_da_should_update_i_disksize(struct page *page,
2797 unsigned long offset)
2799 struct buffer_head *bh;
2800 struct inode *inode = page->mapping->host;
2801 unsigned int idx;
2802 int i;
2804 bh = page_buffers(page);
2805 idx = offset >> inode->i_blkbits;
2807 for (i = 0; i < idx; i++)
2808 bh = bh->b_this_page;
2810 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2811 return 0;
2812 return 1;
2815 static int ext4_da_write_end(struct file *file,
2816 struct address_space *mapping,
2817 loff_t pos, unsigned len, unsigned copied,
2818 struct page *page, void *fsdata)
2820 struct inode *inode = mapping->host;
2821 int ret = 0, ret2;
2822 handle_t *handle = ext4_journal_current_handle();
2823 loff_t new_i_size;
2824 unsigned long start, end;
2825 int write_mode = (int)(unsigned long)fsdata;
2827 if (write_mode == FALL_BACK_TO_NONDELALLOC)
2828 return ext4_write_end(file, mapping, pos,
2829 len, copied, page, fsdata);
2831 trace_ext4_da_write_end(inode, pos, len, copied);
2832 start = pos & (PAGE_CACHE_SIZE - 1);
2833 end = start + copied - 1;
2836 * generic_write_end() will run mark_inode_dirty() if i_size
2837 * changes. So let's piggyback the i_disksize mark_inode_dirty
2838 * into that.
2840 new_i_size = pos + copied;
2841 if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
2842 if (ext4_has_inline_data(inode) ||
2843 ext4_da_should_update_i_disksize(page, end)) {
2844 down_write(&EXT4_I(inode)->i_data_sem);
2845 if (new_i_size > EXT4_I(inode)->i_disksize)
2846 EXT4_I(inode)->i_disksize = new_i_size;
2847 up_write(&EXT4_I(inode)->i_data_sem);
2848 /* We need to mark inode dirty even if
2849 * new_i_size is less that inode->i_size
2850 * bu greater than i_disksize.(hint delalloc)
2852 ext4_mark_inode_dirty(handle, inode);
2856 if (write_mode != CONVERT_INLINE_DATA &&
2857 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
2858 ext4_has_inline_data(inode))
2859 ret2 = ext4_da_write_inline_data_end(inode, pos, len, copied,
2860 page);
2861 else
2862 ret2 = generic_write_end(file, mapping, pos, len, copied,
2863 page, fsdata);
2865 copied = ret2;
2866 if (ret2 < 0)
2867 ret = ret2;
2868 ret2 = ext4_journal_stop(handle);
2869 if (!ret)
2870 ret = ret2;
2872 return ret ? ret : copied;
2875 static void ext4_da_invalidatepage(struct page *page, unsigned int offset,
2876 unsigned int length)
2879 * Drop reserved blocks
2881 BUG_ON(!PageLocked(page));
2882 if (!page_has_buffers(page))
2883 goto out;
2885 ext4_da_page_release_reservation(page, offset, length);
2887 out:
2888 ext4_invalidatepage(page, offset, length);
2890 return;
2894 * Force all delayed allocation blocks to be allocated for a given inode.
2896 int ext4_alloc_da_blocks(struct inode *inode)
2898 trace_ext4_alloc_da_blocks(inode);
2900 if (!EXT4_I(inode)->i_reserved_data_blocks &&
2901 !EXT4_I(inode)->i_reserved_meta_blocks)
2902 return 0;
2905 * We do something simple for now. The filemap_flush() will
2906 * also start triggering a write of the data blocks, which is
2907 * not strictly speaking necessary (and for users of
2908 * laptop_mode, not even desirable). However, to do otherwise
2909 * would require replicating code paths in:
2911 * ext4_writepages() ->
2912 * write_cache_pages() ---> (via passed in callback function)
2913 * __mpage_da_writepage() -->
2914 * mpage_add_bh_to_extent()
2915 * mpage_da_map_blocks()
2917 * The problem is that write_cache_pages(), located in
2918 * mm/page-writeback.c, marks pages clean in preparation for
2919 * doing I/O, which is not desirable if we're not planning on
2920 * doing I/O at all.
2922 * We could call write_cache_pages(), and then redirty all of
2923 * the pages by calling redirty_page_for_writepage() but that
2924 * would be ugly in the extreme. So instead we would need to
2925 * replicate parts of the code in the above functions,
2926 * simplifying them because we wouldn't actually intend to
2927 * write out the pages, but rather only collect contiguous
2928 * logical block extents, call the multi-block allocator, and
2929 * then update the buffer heads with the block allocations.
2931 * For now, though, we'll cheat by calling filemap_flush(),
2932 * which will map the blocks, and start the I/O, but not
2933 * actually wait for the I/O to complete.
2935 return filemap_flush(inode->i_mapping);
2939 * bmap() is special. It gets used by applications such as lilo and by
2940 * the swapper to find the on-disk block of a specific piece of data.
2942 * Naturally, this is dangerous if the block concerned is still in the
2943 * journal. If somebody makes a swapfile on an ext4 data-journaling
2944 * filesystem and enables swap, then they may get a nasty shock when the
2945 * data getting swapped to that swapfile suddenly gets overwritten by
2946 * the original zero's written out previously to the journal and
2947 * awaiting writeback in the kernel's buffer cache.
2949 * So, if we see any bmap calls here on a modified, data-journaled file,
2950 * take extra steps to flush any blocks which might be in the cache.
2952 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
2954 struct inode *inode = mapping->host;
2955 journal_t *journal;
2956 int err;
2959 * We can get here for an inline file via the FIBMAP ioctl
2961 if (ext4_has_inline_data(inode))
2962 return 0;
2964 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
2965 test_opt(inode->i_sb, DELALLOC)) {
2967 * With delalloc we want to sync the file
2968 * so that we can make sure we allocate
2969 * blocks for file
2971 filemap_write_and_wait(mapping);
2974 if (EXT4_JOURNAL(inode) &&
2975 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
2977 * This is a REALLY heavyweight approach, but the use of
2978 * bmap on dirty files is expected to be extremely rare:
2979 * only if we run lilo or swapon on a freshly made file
2980 * do we expect this to happen.
2982 * (bmap requires CAP_SYS_RAWIO so this does not
2983 * represent an unprivileged user DOS attack --- we'd be
2984 * in trouble if mortal users could trigger this path at
2985 * will.)
2987 * NB. EXT4_STATE_JDATA is not set on files other than
2988 * regular files. If somebody wants to bmap a directory
2989 * or symlink and gets confused because the buffer
2990 * hasn't yet been flushed to disk, they deserve
2991 * everything they get.
2994 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
2995 journal = EXT4_JOURNAL(inode);
2996 jbd2_journal_lock_updates(journal);
2997 err = jbd2_journal_flush(journal);
2998 jbd2_journal_unlock_updates(journal);
3000 if (err)
3001 return 0;
3004 return generic_block_bmap(mapping, block, ext4_get_block);
3007 static int ext4_readpage(struct file *file, struct page *page)
3009 int ret = -EAGAIN;
3010 struct inode *inode = page->mapping->host;
3012 trace_ext4_readpage(page);
3014 if (ext4_has_inline_data(inode))
3015 ret = ext4_readpage_inline(inode, page);
3017 if (ret == -EAGAIN)
3018 return mpage_readpage(page, ext4_get_block);
3020 return ret;
3023 static int
3024 ext4_readpages(struct file *file, struct address_space *mapping,
3025 struct list_head *pages, unsigned nr_pages)
3027 struct inode *inode = mapping->host;
3029 /* If the file has inline data, no need to do readpages. */
3030 if (ext4_has_inline_data(inode))
3031 return 0;
3033 return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
3036 static void ext4_invalidatepage(struct page *page, unsigned int offset,
3037 unsigned int length)
3039 trace_ext4_invalidatepage(page, offset, length);
3041 /* No journalling happens on data buffers when this function is used */
3042 WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
3044 block_invalidatepage(page, offset, length);
3047 static int __ext4_journalled_invalidatepage(struct page *page,
3048 unsigned int offset,
3049 unsigned int length)
3051 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3053 trace_ext4_journalled_invalidatepage(page, offset, length);
3056 * If it's a full truncate we just forget about the pending dirtying
3058 if (offset == 0 && length == PAGE_CACHE_SIZE)
3059 ClearPageChecked(page);
3061 return jbd2_journal_invalidatepage(journal, page, offset, length);
3064 /* Wrapper for aops... */
3065 static void ext4_journalled_invalidatepage(struct page *page,
3066 unsigned int offset,
3067 unsigned int length)
3069 WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
3072 static int ext4_releasepage(struct page *page, gfp_t wait)
3074 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3076 trace_ext4_releasepage(page);
3078 /* Page has dirty journalled data -> cannot release */
3079 if (PageChecked(page))
3080 return 0;
3081 if (journal)
3082 return jbd2_journal_try_to_free_buffers(journal, page, wait);
3083 else
3084 return try_to_free_buffers(page);
3088 * ext4_get_block used when preparing for a DIO write or buffer write.
3089 * We allocate an uinitialized extent if blocks haven't been allocated.
3090 * The extent will be converted to initialized after the IO is complete.
3092 int ext4_get_block_write(struct inode *inode, sector_t iblock,
3093 struct buffer_head *bh_result, int create)
3095 ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
3096 inode->i_ino, create);
3097 return _ext4_get_block(inode, iblock, bh_result,
3098 EXT4_GET_BLOCKS_IO_CREATE_EXT);
3101 static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
3102 struct buffer_head *bh_result, int create)
3104 ext4_debug("ext4_get_block_write_nolock: inode %lu, create flag %d\n",
3105 inode->i_ino, create);
3106 return _ext4_get_block(inode, iblock, bh_result,
3107 EXT4_GET_BLOCKS_NO_LOCK);
3110 static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
3111 ssize_t size, void *private)
3113 ext4_io_end_t *io_end = iocb->private;
3115 /* if not async direct IO just return */
3116 if (!io_end)
3117 return;
3119 ext_debug("ext4_end_io_dio(): io_end 0x%p "
3120 "for inode %lu, iocb 0x%p, offset %llu, size %zd\n",
3121 iocb->private, io_end->inode->i_ino, iocb, offset,
3122 size);
3124 iocb->private = NULL;
3125 io_end->offset = offset;
3126 io_end->size = size;
3127 ext4_put_io_end(io_end);
3131 * For ext4 extent files, ext4 will do direct-io write to holes,
3132 * preallocated extents, and those write extend the file, no need to
3133 * fall back to buffered IO.
3135 * For holes, we fallocate those blocks, mark them as unwritten
3136 * If those blocks were preallocated, we mark sure they are split, but
3137 * still keep the range to write as unwritten.
3139 * The unwritten extents will be converted to written when DIO is completed.
3140 * For async direct IO, since the IO may still pending when return, we
3141 * set up an end_io call back function, which will do the conversion
3142 * when async direct IO completed.
3144 * If the O_DIRECT write will extend the file then add this inode to the
3145 * orphan list. So recovery will truncate it back to the original size
3146 * if the machine crashes during the write.
3149 static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
3150 struct iov_iter *iter, loff_t offset)
3152 struct file *file = iocb->ki_filp;
3153 struct inode *inode = file->f_mapping->host;
3154 ssize_t ret;
3155 size_t count = iov_iter_count(iter);
3156 int overwrite = 0;
3157 get_block_t *get_block_func = NULL;
3158 int dio_flags = 0;
3159 loff_t final_size = offset + count;
3160 ext4_io_end_t *io_end = NULL;
3162 /* Use the old path for reads and writes beyond i_size. */
3163 if (rw != WRITE || final_size > inode->i_size)
3164 return ext4_ind_direct_IO(rw, iocb, iter, offset);
3166 BUG_ON(iocb->private == NULL);
3169 * Make all waiters for direct IO properly wait also for extent
3170 * conversion. This also disallows race between truncate() and
3171 * overwrite DIO as i_dio_count needs to be incremented under i_mutex.
3173 if (rw == WRITE)
3174 atomic_inc(&inode->i_dio_count);
3176 /* If we do a overwrite dio, i_mutex locking can be released */
3177 overwrite = *((int *)iocb->private);
3179 if (overwrite) {
3180 down_read(&EXT4_I(inode)->i_data_sem);
3181 mutex_unlock(&inode->i_mutex);
3185 * We could direct write to holes and fallocate.
3187 * Allocated blocks to fill the hole are marked as
3188 * unwritten to prevent parallel buffered read to expose
3189 * the stale data before DIO complete the data IO.
3191 * As to previously fallocated extents, ext4 get_block will
3192 * just simply mark the buffer mapped but still keep the
3193 * extents unwritten.
3195 * For non AIO case, we will convert those unwritten extents
3196 * to written after return back from blockdev_direct_IO.
3198 * For async DIO, the conversion needs to be deferred when the
3199 * IO is completed. The ext4 end_io callback function will be
3200 * called to take care of the conversion work. Here for async
3201 * case, we allocate an io_end structure to hook to the iocb.
3203 iocb->private = NULL;
3204 if (overwrite) {
3205 get_block_func = ext4_get_block_write_nolock;
3206 } else {
3207 ext4_inode_aio_set(inode, NULL);
3208 if (!is_sync_kiocb(iocb)) {
3209 io_end = ext4_init_io_end(inode, GFP_NOFS);
3210 if (!io_end) {
3211 ret = -ENOMEM;
3212 goto retake_lock;
3215 * Grab reference for DIO. Will be dropped in
3216 * ext4_end_io_dio()
3218 iocb->private = ext4_get_io_end(io_end);
3220 * we save the io structure for current async direct
3221 * IO, so that later ext4_map_blocks() could flag the
3222 * io structure whether there is a unwritten extents
3223 * needs to be converted when IO is completed.
3225 ext4_inode_aio_set(inode, io_end);
3227 get_block_func = ext4_get_block_write;
3228 dio_flags = DIO_LOCKING;
3230 ret = __blockdev_direct_IO(rw, iocb, inode,
3231 inode->i_sb->s_bdev, iter,
3232 offset,
3233 get_block_func,
3234 ext4_end_io_dio,
3235 NULL,
3236 dio_flags);
3239 * Put our reference to io_end. This can free the io_end structure e.g.
3240 * in sync IO case or in case of error. It can even perform extent
3241 * conversion if all bios we submitted finished before we got here.
3242 * Note that in that case iocb->private can be already set to NULL
3243 * here.
3245 if (io_end) {
3246 ext4_inode_aio_set(inode, NULL);
3247 ext4_put_io_end(io_end);
3249 * When no IO was submitted ext4_end_io_dio() was not
3250 * called so we have to put iocb's reference.
3252 if (ret <= 0 && ret != -EIOCBQUEUED && iocb->private) {
3253 WARN_ON(iocb->private != io_end);
3254 WARN_ON(io_end->flag & EXT4_IO_END_UNWRITTEN);
3255 ext4_put_io_end(io_end);
3256 iocb->private = NULL;
3259 if (ret > 0 && !overwrite && ext4_test_inode_state(inode,
3260 EXT4_STATE_DIO_UNWRITTEN)) {
3261 int err;
3263 * for non AIO case, since the IO is already
3264 * completed, we could do the conversion right here
3266 err = ext4_convert_unwritten_extents(NULL, inode,
3267 offset, ret);
3268 if (err < 0)
3269 ret = err;
3270 ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3273 retake_lock:
3274 if (rw == WRITE)
3275 inode_dio_done(inode);
3276 /* take i_mutex locking again if we do a ovewrite dio */
3277 if (overwrite) {
3278 up_read(&EXT4_I(inode)->i_data_sem);
3279 mutex_lock(&inode->i_mutex);
3282 return ret;
3285 static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
3286 struct iov_iter *iter, loff_t offset)
3288 struct file *file = iocb->ki_filp;
3289 struct inode *inode = file->f_mapping->host;
3290 size_t count = iov_iter_count(iter);
3291 ssize_t ret;
3294 * If we are doing data journalling we don't support O_DIRECT
3296 if (ext4_should_journal_data(inode))
3297 return 0;
3299 /* Let buffer I/O handle the inline data case. */
3300 if (ext4_has_inline_data(inode))
3301 return 0;
3303 trace_ext4_direct_IO_enter(inode, offset, count, rw);
3304 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3305 ret = ext4_ext_direct_IO(rw, iocb, iter, offset);
3306 else
3307 ret = ext4_ind_direct_IO(rw, iocb, iter, offset);
3308 trace_ext4_direct_IO_exit(inode, offset, count, rw, ret);
3309 return ret;
3313 * Pages can be marked dirty completely asynchronously from ext4's journalling
3314 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3315 * much here because ->set_page_dirty is called under VFS locks. The page is
3316 * not necessarily locked.
3318 * We cannot just dirty the page and leave attached buffers clean, because the
3319 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3320 * or jbddirty because all the journalling code will explode.
3322 * So what we do is to mark the page "pending dirty" and next time writepage
3323 * is called, propagate that into the buffers appropriately.
3325 static int ext4_journalled_set_page_dirty(struct page *page)
3327 SetPageChecked(page);
3328 return __set_page_dirty_nobuffers(page);
3331 static const struct address_space_operations ext4_aops = {
3332 .readpage = ext4_readpage,
3333 .readpages = ext4_readpages,
3334 .writepage = ext4_writepage,
3335 .writepages = ext4_writepages,
3336 .write_begin = ext4_write_begin,
3337 .write_end = ext4_write_end,
3338 .bmap = ext4_bmap,
3339 .invalidatepage = ext4_invalidatepage,
3340 .releasepage = ext4_releasepage,
3341 .direct_IO = ext4_direct_IO,
3342 .migratepage = buffer_migrate_page,
3343 .is_partially_uptodate = block_is_partially_uptodate,
3344 .error_remove_page = generic_error_remove_page,
3347 static const struct address_space_operations ext4_journalled_aops = {
3348 .readpage = ext4_readpage,
3349 .readpages = ext4_readpages,
3350 .writepage = ext4_writepage,
3351 .writepages = ext4_writepages,
3352 .write_begin = ext4_write_begin,
3353 .write_end = ext4_journalled_write_end,
3354 .set_page_dirty = ext4_journalled_set_page_dirty,
3355 .bmap = ext4_bmap,
3356 .invalidatepage = ext4_journalled_invalidatepage,
3357 .releasepage = ext4_releasepage,
3358 .direct_IO = ext4_direct_IO,
3359 .is_partially_uptodate = block_is_partially_uptodate,
3360 .error_remove_page = generic_error_remove_page,
3363 static const struct address_space_operations ext4_da_aops = {
3364 .readpage = ext4_readpage,
3365 .readpages = ext4_readpages,
3366 .writepage = ext4_writepage,
3367 .writepages = ext4_writepages,
3368 .write_begin = ext4_da_write_begin,
3369 .write_end = ext4_da_write_end,
3370 .bmap = ext4_bmap,
3371 .invalidatepage = ext4_da_invalidatepage,
3372 .releasepage = ext4_releasepage,
3373 .direct_IO = ext4_direct_IO,
3374 .migratepage = buffer_migrate_page,
3375 .is_partially_uptodate = block_is_partially_uptodate,
3376 .error_remove_page = generic_error_remove_page,
3379 void ext4_set_aops(struct inode *inode)
3381 switch (ext4_inode_journal_mode(inode)) {
3382 case EXT4_INODE_ORDERED_DATA_MODE:
3383 ext4_set_inode_state(inode, EXT4_STATE_ORDERED_MODE);
3384 break;
3385 case EXT4_INODE_WRITEBACK_DATA_MODE:
3386 ext4_clear_inode_state(inode, EXT4_STATE_ORDERED_MODE);
3387 break;
3388 case EXT4_INODE_JOURNAL_DATA_MODE:
3389 inode->i_mapping->a_ops = &ext4_journalled_aops;
3390 return;
3391 default:
3392 BUG();
3394 if (test_opt(inode->i_sb, DELALLOC))
3395 inode->i_mapping->a_ops = &ext4_da_aops;
3396 else
3397 inode->i_mapping->a_ops = &ext4_aops;
3401 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3402 * starting from file offset 'from'. The range to be zero'd must
3403 * be contained with in one block. If the specified range exceeds
3404 * the end of the block it will be shortened to end of the block
3405 * that cooresponds to 'from'
3407 static int ext4_block_zero_page_range(handle_t *handle,
3408 struct address_space *mapping, loff_t from, loff_t length)
3410 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3411 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3412 unsigned blocksize, max, pos;
3413 ext4_lblk_t iblock;
3414 struct inode *inode = mapping->host;
3415 struct buffer_head *bh;
3416 struct page *page;
3417 int err = 0;
3419 page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3420 mapping_gfp_mask(mapping) & ~__GFP_FS);
3421 if (!page)
3422 return -ENOMEM;
3424 blocksize = inode->i_sb->s_blocksize;
3425 max = blocksize - (offset & (blocksize - 1));
3428 * correct length if it does not fall between
3429 * 'from' and the end of the block
3431 if (length > max || length < 0)
3432 length = max;
3434 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3436 if (!page_has_buffers(page))
3437 create_empty_buffers(page, blocksize, 0);
3439 /* Find the buffer that contains "offset" */
3440 bh = page_buffers(page);
3441 pos = blocksize;
3442 while (offset >= pos) {
3443 bh = bh->b_this_page;
3444 iblock++;
3445 pos += blocksize;
3447 if (buffer_freed(bh)) {
3448 BUFFER_TRACE(bh, "freed: skip");
3449 goto unlock;
3451 if (!buffer_mapped(bh)) {
3452 BUFFER_TRACE(bh, "unmapped");
3453 ext4_get_block(inode, iblock, bh, 0);
3454 /* unmapped? It's a hole - nothing to do */
3455 if (!buffer_mapped(bh)) {
3456 BUFFER_TRACE(bh, "still unmapped");
3457 goto unlock;
3461 /* Ok, it's mapped. Make sure it's up-to-date */
3462 if (PageUptodate(page))
3463 set_buffer_uptodate(bh);
3465 if (!buffer_uptodate(bh)) {
3466 err = -EIO;
3467 ll_rw_block(READ, 1, &bh);
3468 wait_on_buffer(bh);
3469 /* Uhhuh. Read error. Complain and punt. */
3470 if (!buffer_uptodate(bh))
3471 goto unlock;
3473 if (ext4_should_journal_data(inode)) {
3474 BUFFER_TRACE(bh, "get write access");
3475 err = ext4_journal_get_write_access(handle, bh);
3476 if (err)
3477 goto unlock;
3479 zero_user(page, offset, length);
3480 BUFFER_TRACE(bh, "zeroed end of block");
3482 if (ext4_should_journal_data(inode)) {
3483 err = ext4_handle_dirty_metadata(handle, inode, bh);
3484 } else {
3485 err = 0;
3486 mark_buffer_dirty(bh);
3487 if (ext4_test_inode_state(inode, EXT4_STATE_ORDERED_MODE))
3488 err = ext4_jbd2_file_inode(handle, inode);
3491 unlock:
3492 unlock_page(page);
3493 page_cache_release(page);
3494 return err;
3498 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3499 * up to the end of the block which corresponds to `from'.
3500 * This required during truncate. We need to physically zero the tail end
3501 * of that block so it doesn't yield old data if the file is later grown.
3503 static int ext4_block_truncate_page(handle_t *handle,
3504 struct address_space *mapping, loff_t from)
3506 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3507 unsigned length;
3508 unsigned blocksize;
3509 struct inode *inode = mapping->host;
3511 blocksize = inode->i_sb->s_blocksize;
3512 length = blocksize - (offset & (blocksize - 1));
3514 return ext4_block_zero_page_range(handle, mapping, from, length);
3517 int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3518 loff_t lstart, loff_t length)
3520 struct super_block *sb = inode->i_sb;
3521 struct address_space *mapping = inode->i_mapping;
3522 unsigned partial_start, partial_end;
3523 ext4_fsblk_t start, end;
3524 loff_t byte_end = (lstart + length - 1);
3525 int err = 0;
3527 partial_start = lstart & (sb->s_blocksize - 1);
3528 partial_end = byte_end & (sb->s_blocksize - 1);
3530 start = lstart >> sb->s_blocksize_bits;
3531 end = byte_end >> sb->s_blocksize_bits;
3533 /* Handle partial zero within the single block */
3534 if (start == end &&
3535 (partial_start || (partial_end != sb->s_blocksize - 1))) {
3536 err = ext4_block_zero_page_range(handle, mapping,
3537 lstart, length);
3538 return err;
3540 /* Handle partial zero out on the start of the range */
3541 if (partial_start) {
3542 err = ext4_block_zero_page_range(handle, mapping,
3543 lstart, sb->s_blocksize);
3544 if (err)
3545 return err;
3547 /* Handle partial zero out on the end of the range */
3548 if (partial_end != sb->s_blocksize - 1)
3549 err = ext4_block_zero_page_range(handle, mapping,
3550 byte_end - partial_end,
3551 partial_end + 1);
3552 return err;
3555 int ext4_can_truncate(struct inode *inode)
3557 if (S_ISREG(inode->i_mode))
3558 return 1;
3559 if (S_ISDIR(inode->i_mode))
3560 return 1;
3561 if (S_ISLNK(inode->i_mode))
3562 return !ext4_inode_is_fast_symlink(inode);
3563 return 0;
3567 * ext4_punch_hole: punches a hole in a file by releaseing the blocks
3568 * associated with the given offset and length
3570 * @inode: File inode
3571 * @offset: The offset where the hole will begin
3572 * @len: The length of the hole
3574 * Returns: 0 on success or negative on failure
3577 int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length)
3579 struct super_block *sb = inode->i_sb;
3580 ext4_lblk_t first_block, stop_block;
3581 struct address_space *mapping = inode->i_mapping;
3582 loff_t first_block_offset, last_block_offset;
3583 handle_t *handle;
3584 unsigned int credits;
3585 int ret = 0;
3587 if (!S_ISREG(inode->i_mode))
3588 return -EOPNOTSUPP;
3590 trace_ext4_punch_hole(inode, offset, length, 0);
3593 * Write out all dirty pages to avoid race conditions
3594 * Then release them.
3596 if (mapping->nrpages && mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
3597 ret = filemap_write_and_wait_range(mapping, offset,
3598 offset + length - 1);
3599 if (ret)
3600 return ret;
3603 mutex_lock(&inode->i_mutex);
3605 /* No need to punch hole beyond i_size */
3606 if (offset >= inode->i_size)
3607 goto out_mutex;
3610 * If the hole extends beyond i_size, set the hole
3611 * to end after the page that contains i_size
3613 if (offset + length > inode->i_size) {
3614 length = inode->i_size +
3615 PAGE_CACHE_SIZE - (inode->i_size & (PAGE_CACHE_SIZE - 1)) -
3616 offset;
3619 if (offset & (sb->s_blocksize - 1) ||
3620 (offset + length) & (sb->s_blocksize - 1)) {
3622 * Attach jinode to inode for jbd2 if we do any zeroing of
3623 * partial block
3625 ret = ext4_inode_attach_jinode(inode);
3626 if (ret < 0)
3627 goto out_mutex;
3631 first_block_offset = round_up(offset, sb->s_blocksize);
3632 last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
3634 /* Now release the pages and zero block aligned part of pages*/
3635 if (last_block_offset > first_block_offset)
3636 truncate_pagecache_range(inode, first_block_offset,
3637 last_block_offset);
3639 /* Wait all existing dio workers, newcomers will block on i_mutex */
3640 ext4_inode_block_unlocked_dio(inode);
3641 inode_dio_wait(inode);
3643 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3644 credits = ext4_writepage_trans_blocks(inode);
3645 else
3646 credits = ext4_blocks_for_truncate(inode);
3647 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
3648 if (IS_ERR(handle)) {
3649 ret = PTR_ERR(handle);
3650 ext4_std_error(sb, ret);
3651 goto out_dio;
3654 ret = ext4_zero_partial_blocks(handle, inode, offset,
3655 length);
3656 if (ret)
3657 goto out_stop;
3659 first_block = (offset + sb->s_blocksize - 1) >>
3660 EXT4_BLOCK_SIZE_BITS(sb);
3661 stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
3663 /* If there are no blocks to remove, return now */
3664 if (first_block >= stop_block)
3665 goto out_stop;
3667 down_write(&EXT4_I(inode)->i_data_sem);
3668 ext4_discard_preallocations(inode);
3670 ret = ext4_es_remove_extent(inode, first_block,
3671 stop_block - first_block);
3672 if (ret) {
3673 up_write(&EXT4_I(inode)->i_data_sem);
3674 goto out_stop;
3677 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3678 ret = ext4_ext_remove_space(inode, first_block,
3679 stop_block - 1);
3680 else
3681 ret = ext4_ind_remove_space(handle, inode, first_block,
3682 stop_block);
3684 up_write(&EXT4_I(inode)->i_data_sem);
3685 if (IS_SYNC(inode))
3686 ext4_handle_sync(handle);
3688 /* Now release the pages again to reduce race window */
3689 if (last_block_offset > first_block_offset)
3690 truncate_pagecache_range(inode, first_block_offset,
3691 last_block_offset);
3693 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3694 ext4_mark_inode_dirty(handle, inode);
3695 out_stop:
3696 ext4_journal_stop(handle);
3697 out_dio:
3698 ext4_inode_resume_unlocked_dio(inode);
3699 out_mutex:
3700 mutex_unlock(&inode->i_mutex);
3701 return ret;
3704 int ext4_inode_attach_jinode(struct inode *inode)
3706 struct ext4_inode_info *ei = EXT4_I(inode);
3707 struct jbd2_inode *jinode;
3709 if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
3710 return 0;
3712 jinode = jbd2_alloc_inode(GFP_KERNEL);
3713 spin_lock(&inode->i_lock);
3714 if (!ei->jinode) {
3715 if (!jinode) {
3716 spin_unlock(&inode->i_lock);
3717 return -ENOMEM;
3719 ei->jinode = jinode;
3720 jbd2_journal_init_jbd_inode(ei->jinode, inode);
3721 jinode = NULL;
3723 spin_unlock(&inode->i_lock);
3724 if (unlikely(jinode != NULL))
3725 jbd2_free_inode(jinode);
3726 return 0;
3730 * ext4_truncate()
3732 * We block out ext4_get_block() block instantiations across the entire
3733 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
3734 * simultaneously on behalf of the same inode.
3736 * As we work through the truncate and commit bits of it to the journal there
3737 * is one core, guiding principle: the file's tree must always be consistent on
3738 * disk. We must be able to restart the truncate after a crash.
3740 * The file's tree may be transiently inconsistent in memory (although it
3741 * probably isn't), but whenever we close off and commit a journal transaction,
3742 * the contents of (the filesystem + the journal) must be consistent and
3743 * restartable. It's pretty simple, really: bottom up, right to left (although
3744 * left-to-right works OK too).
3746 * Note that at recovery time, journal replay occurs *before* the restart of
3747 * truncate against the orphan inode list.
3749 * The committed inode has the new, desired i_size (which is the same as
3750 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
3751 * that this inode's truncate did not complete and it will again call
3752 * ext4_truncate() to have another go. So there will be instantiated blocks
3753 * to the right of the truncation point in a crashed ext4 filesystem. But
3754 * that's fine - as long as they are linked from the inode, the post-crash
3755 * ext4_truncate() run will find them and release them.
3757 void ext4_truncate(struct inode *inode)
3759 struct ext4_inode_info *ei = EXT4_I(inode);
3760 unsigned int credits;
3761 handle_t *handle;
3762 struct address_space *mapping = inode->i_mapping;
3765 * There is a possibility that we're either freeing the inode
3766 * or it's a completely new inode. In those cases we might not
3767 * have i_mutex locked because it's not necessary.
3769 if (!(inode->i_state & (I_NEW|I_FREEING)))
3770 WARN_ON(!mutex_is_locked(&inode->i_mutex));
3771 trace_ext4_truncate_enter(inode);
3773 if (!ext4_can_truncate(inode))
3774 return;
3776 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3778 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
3779 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
3781 if (ext4_has_inline_data(inode)) {
3782 int has_inline = 1;
3784 ext4_inline_data_truncate(inode, &has_inline);
3785 if (has_inline)
3786 return;
3789 /* If we zero-out tail of the page, we have to create jinode for jbd2 */
3790 if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
3791 if (ext4_inode_attach_jinode(inode) < 0)
3792 return;
3795 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3796 credits = ext4_writepage_trans_blocks(inode);
3797 else
3798 credits = ext4_blocks_for_truncate(inode);
3800 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
3801 if (IS_ERR(handle)) {
3802 ext4_std_error(inode->i_sb, PTR_ERR(handle));
3803 return;
3806 if (inode->i_size & (inode->i_sb->s_blocksize - 1))
3807 ext4_block_truncate_page(handle, mapping, inode->i_size);
3810 * We add the inode to the orphan list, so that if this
3811 * truncate spans multiple transactions, and we crash, we will
3812 * resume the truncate when the filesystem recovers. It also
3813 * marks the inode dirty, to catch the new size.
3815 * Implication: the file must always be in a sane, consistent
3816 * truncatable state while each transaction commits.
3818 if (ext4_orphan_add(handle, inode))
3819 goto out_stop;
3821 down_write(&EXT4_I(inode)->i_data_sem);
3823 ext4_discard_preallocations(inode);
3825 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3826 ext4_ext_truncate(handle, inode);
3827 else
3828 ext4_ind_truncate(handle, inode);
3830 up_write(&ei->i_data_sem);
3832 if (IS_SYNC(inode))
3833 ext4_handle_sync(handle);
3835 out_stop:
3837 * If this was a simple ftruncate() and the file will remain alive,
3838 * then we need to clear up the orphan record which we created above.
3839 * However, if this was a real unlink then we were called by
3840 * ext4_delete_inode(), and we allow that function to clean up the
3841 * orphan info for us.
3843 if (inode->i_nlink)
3844 ext4_orphan_del(handle, inode);
3846 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3847 ext4_mark_inode_dirty(handle, inode);
3848 ext4_journal_stop(handle);
3850 trace_ext4_truncate_exit(inode);
3854 * ext4_get_inode_loc returns with an extra refcount against the inode's
3855 * underlying buffer_head on success. If 'in_mem' is true, we have all
3856 * data in memory that is needed to recreate the on-disk version of this
3857 * inode.
3859 static int __ext4_get_inode_loc(struct inode *inode,
3860 struct ext4_iloc *iloc, int in_mem)
3862 struct ext4_group_desc *gdp;
3863 struct buffer_head *bh;
3864 struct super_block *sb = inode->i_sb;
3865 ext4_fsblk_t block;
3866 int inodes_per_block, inode_offset;
3868 iloc->bh = NULL;
3869 if (!ext4_valid_inum(sb, inode->i_ino))
3870 return -EIO;
3872 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
3873 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
3874 if (!gdp)
3875 return -EIO;
3878 * Figure out the offset within the block group inode table
3880 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
3881 inode_offset = ((inode->i_ino - 1) %
3882 EXT4_INODES_PER_GROUP(sb));
3883 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
3884 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
3886 bh = sb_getblk(sb, block);
3887 if (unlikely(!bh))
3888 return -ENOMEM;
3889 if (!buffer_uptodate(bh)) {
3890 lock_buffer(bh);
3893 * If the buffer has the write error flag, we have failed
3894 * to write out another inode in the same block. In this
3895 * case, we don't have to read the block because we may
3896 * read the old inode data successfully.
3898 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
3899 set_buffer_uptodate(bh);
3901 if (buffer_uptodate(bh)) {
3902 /* someone brought it uptodate while we waited */
3903 unlock_buffer(bh);
3904 goto has_buffer;
3908 * If we have all information of the inode in memory and this
3909 * is the only valid inode in the block, we need not read the
3910 * block.
3912 if (in_mem) {
3913 struct buffer_head *bitmap_bh;
3914 int i, start;
3916 start = inode_offset & ~(inodes_per_block - 1);
3918 /* Is the inode bitmap in cache? */
3919 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
3920 if (unlikely(!bitmap_bh))
3921 goto make_io;
3924 * If the inode bitmap isn't in cache then the
3925 * optimisation may end up performing two reads instead
3926 * of one, so skip it.
3928 if (!buffer_uptodate(bitmap_bh)) {
3929 brelse(bitmap_bh);
3930 goto make_io;
3932 for (i = start; i < start + inodes_per_block; i++) {
3933 if (i == inode_offset)
3934 continue;
3935 if (ext4_test_bit(i, bitmap_bh->b_data))
3936 break;
3938 brelse(bitmap_bh);
3939 if (i == start + inodes_per_block) {
3940 /* all other inodes are free, so skip I/O */
3941 memset(bh->b_data, 0, bh->b_size);
3942 set_buffer_uptodate(bh);
3943 unlock_buffer(bh);
3944 goto has_buffer;
3948 make_io:
3950 * If we need to do any I/O, try to pre-readahead extra
3951 * blocks from the inode table.
3953 if (EXT4_SB(sb)->s_inode_readahead_blks) {
3954 ext4_fsblk_t b, end, table;
3955 unsigned num;
3956 __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
3958 table = ext4_inode_table(sb, gdp);
3959 /* s_inode_readahead_blks is always a power of 2 */
3960 b = block & ~((ext4_fsblk_t) ra_blks - 1);
3961 if (table > b)
3962 b = table;
3963 end = b + ra_blks;
3964 num = EXT4_INODES_PER_GROUP(sb);
3965 if (ext4_has_group_desc_csum(sb))
3966 num -= ext4_itable_unused_count(sb, gdp);
3967 table += num / inodes_per_block;
3968 if (end > table)
3969 end = table;
3970 while (b <= end)
3971 sb_breadahead(sb, b++);
3975 * There are other valid inodes in the buffer, this inode
3976 * has in-inode xattrs, or we don't have this inode in memory.
3977 * Read the block from disk.
3979 trace_ext4_load_inode(inode);
3980 get_bh(bh);
3981 bh->b_end_io = end_buffer_read_sync;
3982 submit_bh(READ | REQ_META | REQ_PRIO, bh);
3983 wait_on_buffer(bh);
3984 if (!buffer_uptodate(bh)) {
3985 EXT4_ERROR_INODE_BLOCK(inode, block,
3986 "unable to read itable block");
3987 brelse(bh);
3988 return -EIO;
3991 has_buffer:
3992 iloc->bh = bh;
3993 return 0;
3996 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
3998 /* We have all inode data except xattrs in memory here. */
3999 return __ext4_get_inode_loc(inode, iloc,
4000 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
4003 void ext4_set_inode_flags(struct inode *inode)
4005 unsigned int flags = EXT4_I(inode)->i_flags;
4006 unsigned int new_fl = 0;
4008 if (flags & EXT4_SYNC_FL)
4009 new_fl |= S_SYNC;
4010 if (flags & EXT4_APPEND_FL)
4011 new_fl |= S_APPEND;
4012 if (flags & EXT4_IMMUTABLE_FL)
4013 new_fl |= S_IMMUTABLE;
4014 if (flags & EXT4_NOATIME_FL)
4015 new_fl |= S_NOATIME;
4016 if (flags & EXT4_DIRSYNC_FL)
4017 new_fl |= S_DIRSYNC;
4018 inode_set_flags(inode, new_fl,
4019 S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
4022 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
4023 void ext4_get_inode_flags(struct ext4_inode_info *ei)
4025 unsigned int vfs_fl;
4026 unsigned long old_fl, new_fl;
4028 do {
4029 vfs_fl = ei->vfs_inode.i_flags;
4030 old_fl = ei->i_flags;
4031 new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
4032 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
4033 EXT4_DIRSYNC_FL);
4034 if (vfs_fl & S_SYNC)
4035 new_fl |= EXT4_SYNC_FL;
4036 if (vfs_fl & S_APPEND)
4037 new_fl |= EXT4_APPEND_FL;
4038 if (vfs_fl & S_IMMUTABLE)
4039 new_fl |= EXT4_IMMUTABLE_FL;
4040 if (vfs_fl & S_NOATIME)
4041 new_fl |= EXT4_NOATIME_FL;
4042 if (vfs_fl & S_DIRSYNC)
4043 new_fl |= EXT4_DIRSYNC_FL;
4044 } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
4047 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4048 struct ext4_inode_info *ei)
4050 blkcnt_t i_blocks ;
4051 struct inode *inode = &(ei->vfs_inode);
4052 struct super_block *sb = inode->i_sb;
4054 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4055 EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
4056 /* we are using combined 48 bit field */
4057 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4058 le32_to_cpu(raw_inode->i_blocks_lo);
4059 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
4060 /* i_blocks represent file system block size */
4061 return i_blocks << (inode->i_blkbits - 9);
4062 } else {
4063 return i_blocks;
4065 } else {
4066 return le32_to_cpu(raw_inode->i_blocks_lo);
4070 static inline void ext4_iget_extra_inode(struct inode *inode,
4071 struct ext4_inode *raw_inode,
4072 struct ext4_inode_info *ei)
4074 __le32 *magic = (void *)raw_inode +
4075 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4076 if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4077 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4078 ext4_find_inline_data_nolock(inode);
4079 } else
4080 EXT4_I(inode)->i_inline_off = 0;
4083 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
4085 struct ext4_iloc iloc;
4086 struct ext4_inode *raw_inode;
4087 struct ext4_inode_info *ei;
4088 struct inode *inode;
4089 journal_t *journal = EXT4_SB(sb)->s_journal;
4090 long ret;
4091 int block;
4092 uid_t i_uid;
4093 gid_t i_gid;
4095 inode = iget_locked(sb, ino);
4096 if (!inode)
4097 return ERR_PTR(-ENOMEM);
4098 if (!(inode->i_state & I_NEW))
4099 return inode;
4101 ei = EXT4_I(inode);
4102 iloc.bh = NULL;
4104 ret = __ext4_get_inode_loc(inode, &iloc, 0);
4105 if (ret < 0)
4106 goto bad_inode;
4107 raw_inode = ext4_raw_inode(&iloc);
4109 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4110 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4111 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4112 EXT4_INODE_SIZE(inode->i_sb)) {
4113 EXT4_ERROR_INODE(inode, "bad extra_isize (%u != %u)",
4114 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize,
4115 EXT4_INODE_SIZE(inode->i_sb));
4116 ret = -EIO;
4117 goto bad_inode;
4119 } else
4120 ei->i_extra_isize = 0;
4122 /* Precompute checksum seed for inode metadata */
4123 if (ext4_has_metadata_csum(sb)) {
4124 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4125 __u32 csum;
4126 __le32 inum = cpu_to_le32(inode->i_ino);
4127 __le32 gen = raw_inode->i_generation;
4128 csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4129 sizeof(inum));
4130 ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4131 sizeof(gen));
4134 if (!ext4_inode_csum_verify(inode, raw_inode, ei)) {
4135 EXT4_ERROR_INODE(inode, "checksum invalid");
4136 ret = -EIO;
4137 goto bad_inode;
4140 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4141 i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4142 i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4143 if (!(test_opt(inode->i_sb, NO_UID32))) {
4144 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4145 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4147 i_uid_write(inode, i_uid);
4148 i_gid_write(inode, i_gid);
4149 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4151 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
4152 ei->i_inline_off = 0;
4153 ei->i_dir_start_lookup = 0;
4154 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4155 /* We now have enough fields to check if the inode was active or not.
4156 * This is needed because nfsd might try to access dead inodes
4157 * the test is that same one that e2fsck uses
4158 * NeilBrown 1999oct15
4160 if (inode->i_nlink == 0) {
4161 if ((inode->i_mode == 0 ||
4162 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4163 ino != EXT4_BOOT_LOADER_INO) {
4164 /* this inode is deleted */
4165 ret = -ESTALE;
4166 goto bad_inode;
4168 /* The only unlinked inodes we let through here have
4169 * valid i_mode and are being read by the orphan
4170 * recovery code: that's fine, we're about to complete
4171 * the process of deleting those.
4172 * OR it is the EXT4_BOOT_LOADER_INO which is
4173 * not initialized on a new filesystem. */
4175 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4176 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4177 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4178 if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
4179 ei->i_file_acl |=
4180 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4181 inode->i_size = ext4_isize(raw_inode);
4182 ei->i_disksize = inode->i_size;
4183 #ifdef CONFIG_QUOTA
4184 ei->i_reserved_quota = 0;
4185 #endif
4186 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4187 ei->i_block_group = iloc.block_group;
4188 ei->i_last_alloc_group = ~0;
4190 * NOTE! The in-memory inode i_data array is in little-endian order
4191 * even on big-endian machines: we do NOT byteswap the block numbers!
4193 for (block = 0; block < EXT4_N_BLOCKS; block++)
4194 ei->i_data[block] = raw_inode->i_block[block];
4195 INIT_LIST_HEAD(&ei->i_orphan);
4198 * Set transaction id's of transactions that have to be committed
4199 * to finish f[data]sync. We set them to currently running transaction
4200 * as we cannot be sure that the inode or some of its metadata isn't
4201 * part of the transaction - the inode could have been reclaimed and
4202 * now it is reread from disk.
4204 if (journal) {
4205 transaction_t *transaction;
4206 tid_t tid;
4208 read_lock(&journal->j_state_lock);
4209 if (journal->j_running_transaction)
4210 transaction = journal->j_running_transaction;
4211 else
4212 transaction = journal->j_committing_transaction;
4213 if (transaction)
4214 tid = transaction->t_tid;
4215 else
4216 tid = journal->j_commit_sequence;
4217 read_unlock(&journal->j_state_lock);
4218 ei->i_sync_tid = tid;
4219 ei->i_datasync_tid = tid;
4222 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4223 if (ei->i_extra_isize == 0) {
4224 /* The extra space is currently unused. Use it. */
4225 ei->i_extra_isize = sizeof(struct ext4_inode) -
4226 EXT4_GOOD_OLD_INODE_SIZE;
4227 } else {
4228 ext4_iget_extra_inode(inode, raw_inode, ei);
4232 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4233 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4234 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4235 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4237 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4238 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
4239 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4240 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4241 inode->i_version |=
4242 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4246 ret = 0;
4247 if (ei->i_file_acl &&
4248 !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
4249 EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
4250 ei->i_file_acl);
4251 ret = -EIO;
4252 goto bad_inode;
4253 } else if (!ext4_has_inline_data(inode)) {
4254 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4255 if ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4256 (S_ISLNK(inode->i_mode) &&
4257 !ext4_inode_is_fast_symlink(inode))))
4258 /* Validate extent which is part of inode */
4259 ret = ext4_ext_check_inode(inode);
4260 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4261 (S_ISLNK(inode->i_mode) &&
4262 !ext4_inode_is_fast_symlink(inode))) {
4263 /* Validate block references which are part of inode */
4264 ret = ext4_ind_check_inode(inode);
4267 if (ret)
4268 goto bad_inode;
4270 if (S_ISREG(inode->i_mode)) {
4271 inode->i_op = &ext4_file_inode_operations;
4272 inode->i_fop = &ext4_file_operations;
4273 ext4_set_aops(inode);
4274 } else if (S_ISDIR(inode->i_mode)) {
4275 inode->i_op = &ext4_dir_inode_operations;
4276 inode->i_fop = &ext4_dir_operations;
4277 } else if (S_ISLNK(inode->i_mode)) {
4278 if (ext4_inode_is_fast_symlink(inode)) {
4279 inode->i_op = &ext4_fast_symlink_inode_operations;
4280 nd_terminate_link(ei->i_data, inode->i_size,
4281 sizeof(ei->i_data) - 1);
4282 } else {
4283 inode->i_op = &ext4_symlink_inode_operations;
4284 ext4_set_aops(inode);
4286 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4287 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4288 inode->i_op = &ext4_special_inode_operations;
4289 if (raw_inode->i_block[0])
4290 init_special_inode(inode, inode->i_mode,
4291 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4292 else
4293 init_special_inode(inode, inode->i_mode,
4294 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4295 } else if (ino == EXT4_BOOT_LOADER_INO) {
4296 make_bad_inode(inode);
4297 } else {
4298 ret = -EIO;
4299 EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
4300 goto bad_inode;
4302 brelse(iloc.bh);
4303 ext4_set_inode_flags(inode);
4304 unlock_new_inode(inode);
4305 return inode;
4307 bad_inode:
4308 brelse(iloc.bh);
4309 iget_failed(inode);
4310 return ERR_PTR(ret);
4313 struct inode *ext4_iget_normal(struct super_block *sb, unsigned long ino)
4315 if (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)
4316 return ERR_PTR(-EIO);
4317 return ext4_iget(sb, ino);
4320 static int ext4_inode_blocks_set(handle_t *handle,
4321 struct ext4_inode *raw_inode,
4322 struct ext4_inode_info *ei)
4324 struct inode *inode = &(ei->vfs_inode);
4325 u64 i_blocks = inode->i_blocks;
4326 struct super_block *sb = inode->i_sb;
4328 if (i_blocks <= ~0U) {
4330 * i_blocks can be represented in a 32 bit variable
4331 * as multiple of 512 bytes
4333 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4334 raw_inode->i_blocks_high = 0;
4335 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4336 return 0;
4338 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
4339 return -EFBIG;
4341 if (i_blocks <= 0xffffffffffffULL) {
4343 * i_blocks can be represented in a 48 bit variable
4344 * as multiple of 512 bytes
4346 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4347 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4348 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4349 } else {
4350 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4351 /* i_block is stored in file system block size */
4352 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4353 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4354 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4356 return 0;
4360 * Post the struct inode info into an on-disk inode location in the
4361 * buffer-cache. This gobbles the caller's reference to the
4362 * buffer_head in the inode location struct.
4364 * The caller must have write access to iloc->bh.
4366 static int ext4_do_update_inode(handle_t *handle,
4367 struct inode *inode,
4368 struct ext4_iloc *iloc)
4370 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
4371 struct ext4_inode_info *ei = EXT4_I(inode);
4372 struct buffer_head *bh = iloc->bh;
4373 struct super_block *sb = inode->i_sb;
4374 int err = 0, rc, block;
4375 int need_datasync = 0, set_large_file = 0;
4376 uid_t i_uid;
4377 gid_t i_gid;
4379 spin_lock(&ei->i_raw_lock);
4381 /* For fields not tracked in the in-memory inode,
4382 * initialise them to zero for new inodes. */
4383 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
4384 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
4386 ext4_get_inode_flags(ei);
4387 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4388 i_uid = i_uid_read(inode);
4389 i_gid = i_gid_read(inode);
4390 if (!(test_opt(inode->i_sb, NO_UID32))) {
4391 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
4392 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
4394 * Fix up interoperability with old kernels. Otherwise, old inodes get
4395 * re-used with the upper 16 bits of the uid/gid intact
4397 if (!ei->i_dtime) {
4398 raw_inode->i_uid_high =
4399 cpu_to_le16(high_16_bits(i_uid));
4400 raw_inode->i_gid_high =
4401 cpu_to_le16(high_16_bits(i_gid));
4402 } else {
4403 raw_inode->i_uid_high = 0;
4404 raw_inode->i_gid_high = 0;
4406 } else {
4407 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
4408 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
4409 raw_inode->i_uid_high = 0;
4410 raw_inode->i_gid_high = 0;
4412 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4414 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4415 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4416 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4417 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4419 if (ext4_inode_blocks_set(handle, raw_inode, ei)) {
4420 spin_unlock(&ei->i_raw_lock);
4421 goto out_brelse;
4423 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4424 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4425 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
4426 raw_inode->i_file_acl_high =
4427 cpu_to_le16(ei->i_file_acl >> 32);
4428 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4429 if (ei->i_disksize != ext4_isize(raw_inode)) {
4430 ext4_isize_set(raw_inode, ei->i_disksize);
4431 need_datasync = 1;
4433 if (ei->i_disksize > 0x7fffffffULL) {
4434 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
4435 EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
4436 EXT4_SB(sb)->s_es->s_rev_level ==
4437 cpu_to_le32(EXT4_GOOD_OLD_REV))
4438 set_large_file = 1;
4440 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4441 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4442 if (old_valid_dev(inode->i_rdev)) {
4443 raw_inode->i_block[0] =
4444 cpu_to_le32(old_encode_dev(inode->i_rdev));
4445 raw_inode->i_block[1] = 0;
4446 } else {
4447 raw_inode->i_block[0] = 0;
4448 raw_inode->i_block[1] =
4449 cpu_to_le32(new_encode_dev(inode->i_rdev));
4450 raw_inode->i_block[2] = 0;
4452 } else if (!ext4_has_inline_data(inode)) {
4453 for (block = 0; block < EXT4_N_BLOCKS; block++)
4454 raw_inode->i_block[block] = ei->i_data[block];
4457 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4458 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
4459 if (ei->i_extra_isize) {
4460 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4461 raw_inode->i_version_hi =
4462 cpu_to_le32(inode->i_version >> 32);
4463 raw_inode->i_extra_isize =
4464 cpu_to_le16(ei->i_extra_isize);
4468 ext4_inode_csum_set(inode, raw_inode, ei);
4470 spin_unlock(&ei->i_raw_lock);
4472 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4473 rc = ext4_handle_dirty_metadata(handle, NULL, bh);
4474 if (!err)
4475 err = rc;
4476 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
4477 if (set_large_file) {
4478 BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
4479 err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh);
4480 if (err)
4481 goto out_brelse;
4482 ext4_update_dynamic_rev(sb);
4483 EXT4_SET_RO_COMPAT_FEATURE(sb,
4484 EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
4485 ext4_handle_sync(handle);
4486 err = ext4_handle_dirty_super(handle, sb);
4488 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
4489 out_brelse:
4490 brelse(bh);
4491 ext4_std_error(inode->i_sb, err);
4492 return err;
4496 * ext4_write_inode()
4498 * We are called from a few places:
4500 * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
4501 * Here, there will be no transaction running. We wait for any running
4502 * transaction to commit.
4504 * - Within flush work (sys_sync(), kupdate and such).
4505 * We wait on commit, if told to.
4507 * - Within iput_final() -> write_inode_now()
4508 * We wait on commit, if told to.
4510 * In all cases it is actually safe for us to return without doing anything,
4511 * because the inode has been copied into a raw inode buffer in
4512 * ext4_mark_inode_dirty(). This is a correctness thing for WB_SYNC_ALL
4513 * writeback.
4515 * Note that we are absolutely dependent upon all inode dirtiers doing the
4516 * right thing: they *must* call mark_inode_dirty() after dirtying info in
4517 * which we are interested.
4519 * It would be a bug for them to not do this. The code:
4521 * mark_inode_dirty(inode)
4522 * stuff();
4523 * inode->i_size = expr;
4525 * is in error because write_inode() could occur while `stuff()' is running,
4526 * and the new i_size will be lost. Plus the inode will no longer be on the
4527 * superblock's dirty inode list.
4529 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
4531 int err;
4533 if (WARN_ON_ONCE(current->flags & PF_MEMALLOC))
4534 return 0;
4536 if (EXT4_SB(inode->i_sb)->s_journal) {
4537 if (ext4_journal_current_handle()) {
4538 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4539 dump_stack();
4540 return -EIO;
4544 * No need to force transaction in WB_SYNC_NONE mode. Also
4545 * ext4_sync_fs() will force the commit after everything is
4546 * written.
4548 if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
4549 return 0;
4551 err = ext4_force_commit(inode->i_sb);
4552 } else {
4553 struct ext4_iloc iloc;
4555 err = __ext4_get_inode_loc(inode, &iloc, 0);
4556 if (err)
4557 return err;
4559 * sync(2) will flush the whole buffer cache. No need to do
4560 * it here separately for each inode.
4562 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
4563 sync_dirty_buffer(iloc.bh);
4564 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
4565 EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
4566 "IO error syncing inode");
4567 err = -EIO;
4569 brelse(iloc.bh);
4571 return err;
4575 * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
4576 * buffers that are attached to a page stradding i_size and are undergoing
4577 * commit. In that case we have to wait for commit to finish and try again.
4579 static void ext4_wait_for_tail_page_commit(struct inode *inode)
4581 struct page *page;
4582 unsigned offset;
4583 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
4584 tid_t commit_tid = 0;
4585 int ret;
4587 offset = inode->i_size & (PAGE_CACHE_SIZE - 1);
4589 * All buffers in the last page remain valid? Then there's nothing to
4590 * do. We do the check mainly to optimize the common PAGE_CACHE_SIZE ==
4591 * blocksize case
4593 if (offset > PAGE_CACHE_SIZE - (1 << inode->i_blkbits))
4594 return;
4595 while (1) {
4596 page = find_lock_page(inode->i_mapping,
4597 inode->i_size >> PAGE_CACHE_SHIFT);
4598 if (!page)
4599 return;
4600 ret = __ext4_journalled_invalidatepage(page, offset,
4601 PAGE_CACHE_SIZE - offset);
4602 unlock_page(page);
4603 page_cache_release(page);
4604 if (ret != -EBUSY)
4605 return;
4606 commit_tid = 0;
4607 read_lock(&journal->j_state_lock);
4608 if (journal->j_committing_transaction)
4609 commit_tid = journal->j_committing_transaction->t_tid;
4610 read_unlock(&journal->j_state_lock);
4611 if (commit_tid)
4612 jbd2_log_wait_commit(journal, commit_tid);
4617 * ext4_setattr()
4619 * Called from notify_change.
4621 * We want to trap VFS attempts to truncate the file as soon as
4622 * possible. In particular, we want to make sure that when the VFS
4623 * shrinks i_size, we put the inode on the orphan list and modify
4624 * i_disksize immediately, so that during the subsequent flushing of
4625 * dirty pages and freeing of disk blocks, we can guarantee that any
4626 * commit will leave the blocks being flushed in an unused state on
4627 * disk. (On recovery, the inode will get truncated and the blocks will
4628 * be freed, so we have a strong guarantee that no future commit will
4629 * leave these blocks visible to the user.)
4631 * Another thing we have to assure is that if we are in ordered mode
4632 * and inode is still attached to the committing transaction, we must
4633 * we start writeout of all the dirty pages which are being truncated.
4634 * This way we are sure that all the data written in the previous
4635 * transaction are already on disk (truncate waits for pages under
4636 * writeback).
4638 * Called with inode->i_mutex down.
4640 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
4642 struct inode *inode = dentry->d_inode;
4643 int error, rc = 0;
4644 int orphan = 0;
4645 const unsigned int ia_valid = attr->ia_valid;
4647 error = inode_change_ok(inode, attr);
4648 if (error)
4649 return error;
4651 if (is_quota_modification(inode, attr))
4652 dquot_initialize(inode);
4653 if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
4654 (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
4655 handle_t *handle;
4657 /* (user+group)*(old+new) structure, inode write (sb,
4658 * inode block, ? - but truncate inode update has it) */
4659 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
4660 (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
4661 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
4662 if (IS_ERR(handle)) {
4663 error = PTR_ERR(handle);
4664 goto err_out;
4666 error = dquot_transfer(inode, attr);
4667 if (error) {
4668 ext4_journal_stop(handle);
4669 return error;
4671 /* Update corresponding info in inode so that everything is in
4672 * one transaction */
4673 if (attr->ia_valid & ATTR_UID)
4674 inode->i_uid = attr->ia_uid;
4675 if (attr->ia_valid & ATTR_GID)
4676 inode->i_gid = attr->ia_gid;
4677 error = ext4_mark_inode_dirty(handle, inode);
4678 ext4_journal_stop(handle);
4681 if (attr->ia_valid & ATTR_SIZE && attr->ia_size != inode->i_size) {
4682 handle_t *handle;
4684 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4685 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4687 if (attr->ia_size > sbi->s_bitmap_maxbytes)
4688 return -EFBIG;
4691 if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
4692 inode_inc_iversion(inode);
4694 if (S_ISREG(inode->i_mode) &&
4695 (attr->ia_size < inode->i_size)) {
4696 if (ext4_should_order_data(inode)) {
4697 error = ext4_begin_ordered_truncate(inode,
4698 attr->ia_size);
4699 if (error)
4700 goto err_out;
4702 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
4703 if (IS_ERR(handle)) {
4704 error = PTR_ERR(handle);
4705 goto err_out;
4707 if (ext4_handle_valid(handle)) {
4708 error = ext4_orphan_add(handle, inode);
4709 orphan = 1;
4711 down_write(&EXT4_I(inode)->i_data_sem);
4712 EXT4_I(inode)->i_disksize = attr->ia_size;
4713 rc = ext4_mark_inode_dirty(handle, inode);
4714 if (!error)
4715 error = rc;
4717 * We have to update i_size under i_data_sem together
4718 * with i_disksize to avoid races with writeback code
4719 * running ext4_wb_update_i_disksize().
4721 if (!error)
4722 i_size_write(inode, attr->ia_size);
4723 up_write(&EXT4_I(inode)->i_data_sem);
4724 ext4_journal_stop(handle);
4725 if (error) {
4726 ext4_orphan_del(NULL, inode);
4727 goto err_out;
4729 } else {
4730 loff_t oldsize = inode->i_size;
4732 i_size_write(inode, attr->ia_size);
4733 pagecache_isize_extended(inode, oldsize, inode->i_size);
4737 * Blocks are going to be removed from the inode. Wait
4738 * for dio in flight. Temporarily disable
4739 * dioread_nolock to prevent livelock.
4741 if (orphan) {
4742 if (!ext4_should_journal_data(inode)) {
4743 ext4_inode_block_unlocked_dio(inode);
4744 inode_dio_wait(inode);
4745 ext4_inode_resume_unlocked_dio(inode);
4746 } else
4747 ext4_wait_for_tail_page_commit(inode);
4750 * Truncate pagecache after we've waited for commit
4751 * in data=journal mode to make pages freeable.
4753 truncate_pagecache(inode, inode->i_size);
4756 * We want to call ext4_truncate() even if attr->ia_size ==
4757 * inode->i_size for cases like truncation of fallocated space
4759 if (attr->ia_valid & ATTR_SIZE)
4760 ext4_truncate(inode);
4762 if (!rc) {
4763 setattr_copy(inode, attr);
4764 mark_inode_dirty(inode);
4768 * If the call to ext4_truncate failed to get a transaction handle at
4769 * all, we need to clean up the in-core orphan list manually.
4771 if (orphan && inode->i_nlink)
4772 ext4_orphan_del(NULL, inode);
4774 if (!rc && (ia_valid & ATTR_MODE))
4775 rc = posix_acl_chmod(inode, inode->i_mode);
4777 err_out:
4778 ext4_std_error(inode->i_sb, error);
4779 if (!error)
4780 error = rc;
4781 return error;
4784 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
4785 struct kstat *stat)
4787 struct inode *inode;
4788 unsigned long long delalloc_blocks;
4790 inode = dentry->d_inode;
4791 generic_fillattr(inode, stat);
4794 * If there is inline data in the inode, the inode will normally not
4795 * have data blocks allocated (it may have an external xattr block).
4796 * Report at least one sector for such files, so tools like tar, rsync,
4797 * others doen't incorrectly think the file is completely sparse.
4799 if (unlikely(ext4_has_inline_data(inode)))
4800 stat->blocks += (stat->size + 511) >> 9;
4803 * We can't update i_blocks if the block allocation is delayed
4804 * otherwise in the case of system crash before the real block
4805 * allocation is done, we will have i_blocks inconsistent with
4806 * on-disk file blocks.
4807 * We always keep i_blocks updated together with real
4808 * allocation. But to not confuse with user, stat
4809 * will return the blocks that include the delayed allocation
4810 * blocks for this file.
4812 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
4813 EXT4_I(inode)->i_reserved_data_blocks);
4814 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
4815 return 0;
4818 static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
4819 int pextents)
4821 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
4822 return ext4_ind_trans_blocks(inode, lblocks);
4823 return ext4_ext_index_trans_blocks(inode, pextents);
4827 * Account for index blocks, block groups bitmaps and block group
4828 * descriptor blocks if modify datablocks and index blocks
4829 * worse case, the indexs blocks spread over different block groups
4831 * If datablocks are discontiguous, they are possible to spread over
4832 * different block groups too. If they are contiguous, with flexbg,
4833 * they could still across block group boundary.
4835 * Also account for superblock, inode, quota and xattr blocks
4837 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
4838 int pextents)
4840 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
4841 int gdpblocks;
4842 int idxblocks;
4843 int ret = 0;
4846 * How many index blocks need to touch to map @lblocks logical blocks
4847 * to @pextents physical extents?
4849 idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
4851 ret = idxblocks;
4854 * Now let's see how many group bitmaps and group descriptors need
4855 * to account
4857 groups = idxblocks + pextents;
4858 gdpblocks = groups;
4859 if (groups > ngroups)
4860 groups = ngroups;
4861 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
4862 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
4864 /* bitmaps and block group descriptor blocks */
4865 ret += groups + gdpblocks;
4867 /* Blocks for super block, inode, quota and xattr blocks */
4868 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
4870 return ret;
4874 * Calculate the total number of credits to reserve to fit
4875 * the modification of a single pages into a single transaction,
4876 * which may include multiple chunks of block allocations.
4878 * This could be called via ext4_write_begin()
4880 * We need to consider the worse case, when
4881 * one new block per extent.
4883 int ext4_writepage_trans_blocks(struct inode *inode)
4885 int bpp = ext4_journal_blocks_per_page(inode);
4886 int ret;
4888 ret = ext4_meta_trans_blocks(inode, bpp, bpp);
4890 /* Account for data blocks for journalled mode */
4891 if (ext4_should_journal_data(inode))
4892 ret += bpp;
4893 return ret;
4897 * Calculate the journal credits for a chunk of data modification.
4899 * This is called from DIO, fallocate or whoever calling
4900 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
4902 * journal buffers for data blocks are not included here, as DIO
4903 * and fallocate do no need to journal data buffers.
4905 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
4907 return ext4_meta_trans_blocks(inode, nrblocks, 1);
4911 * The caller must have previously called ext4_reserve_inode_write().
4912 * Give this, we know that the caller already has write access to iloc->bh.
4914 int ext4_mark_iloc_dirty(handle_t *handle,
4915 struct inode *inode, struct ext4_iloc *iloc)
4917 int err = 0;
4919 if (IS_I_VERSION(inode))
4920 inode_inc_iversion(inode);
4922 /* the do_update_inode consumes one bh->b_count */
4923 get_bh(iloc->bh);
4925 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
4926 err = ext4_do_update_inode(handle, inode, iloc);
4927 put_bh(iloc->bh);
4928 return err;
4932 * On success, We end up with an outstanding reference count against
4933 * iloc->bh. This _must_ be cleaned up later.
4937 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
4938 struct ext4_iloc *iloc)
4940 int err;
4942 err = ext4_get_inode_loc(inode, iloc);
4943 if (!err) {
4944 BUFFER_TRACE(iloc->bh, "get_write_access");
4945 err = ext4_journal_get_write_access(handle, iloc->bh);
4946 if (err) {
4947 brelse(iloc->bh);
4948 iloc->bh = NULL;
4951 ext4_std_error(inode->i_sb, err);
4952 return err;
4956 * Expand an inode by new_extra_isize bytes.
4957 * Returns 0 on success or negative error number on failure.
4959 static int ext4_expand_extra_isize(struct inode *inode,
4960 unsigned int new_extra_isize,
4961 struct ext4_iloc iloc,
4962 handle_t *handle)
4964 struct ext4_inode *raw_inode;
4965 struct ext4_xattr_ibody_header *header;
4967 if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
4968 return 0;
4970 raw_inode = ext4_raw_inode(&iloc);
4972 header = IHDR(inode, raw_inode);
4974 /* No extended attributes present */
4975 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
4976 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
4977 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
4978 new_extra_isize);
4979 EXT4_I(inode)->i_extra_isize = new_extra_isize;
4980 return 0;
4983 /* try to expand with EAs present */
4984 return ext4_expand_extra_isize_ea(inode, new_extra_isize,
4985 raw_inode, handle);
4989 * What we do here is to mark the in-core inode as clean with respect to inode
4990 * dirtiness (it may still be data-dirty).
4991 * This means that the in-core inode may be reaped by prune_icache
4992 * without having to perform any I/O. This is a very good thing,
4993 * because *any* task may call prune_icache - even ones which
4994 * have a transaction open against a different journal.
4996 * Is this cheating? Not really. Sure, we haven't written the
4997 * inode out, but prune_icache isn't a user-visible syncing function.
4998 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
4999 * we start and wait on commits.
5001 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
5003 struct ext4_iloc iloc;
5004 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5005 static unsigned int mnt_count;
5006 int err, ret;
5008 might_sleep();
5009 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5010 err = ext4_reserve_inode_write(handle, inode, &iloc);
5011 if (err)
5012 return err;
5013 if (ext4_handle_valid(handle) &&
5014 EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
5015 !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5017 * We need extra buffer credits since we may write into EA block
5018 * with this same handle. If journal_extend fails, then it will
5019 * only result in a minor loss of functionality for that inode.
5020 * If this is felt to be critical, then e2fsck should be run to
5021 * force a large enough s_min_extra_isize.
5023 if ((jbd2_journal_extend(handle,
5024 EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
5025 ret = ext4_expand_extra_isize(inode,
5026 sbi->s_want_extra_isize,
5027 iloc, handle);
5028 if (ret) {
5029 ext4_set_inode_state(inode,
5030 EXT4_STATE_NO_EXPAND);
5031 if (mnt_count !=
5032 le16_to_cpu(sbi->s_es->s_mnt_count)) {
5033 ext4_warning(inode->i_sb,
5034 "Unable to expand inode %lu. Delete"
5035 " some EAs or run e2fsck.",
5036 inode->i_ino);
5037 mnt_count =
5038 le16_to_cpu(sbi->s_es->s_mnt_count);
5043 return ext4_mark_iloc_dirty(handle, inode, &iloc);
5047 * ext4_dirty_inode() is called from __mark_inode_dirty()
5049 * We're really interested in the case where a file is being extended.
5050 * i_size has been changed by generic_commit_write() and we thus need
5051 * to include the updated inode in the current transaction.
5053 * Also, dquot_alloc_block() will always dirty the inode when blocks
5054 * are allocated to the file.
5056 * If the inode is marked synchronous, we don't honour that here - doing
5057 * so would cause a commit on atime updates, which we don't bother doing.
5058 * We handle synchronous inodes at the highest possible level.
5060 void ext4_dirty_inode(struct inode *inode, int flags)
5062 handle_t *handle;
5064 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
5065 if (IS_ERR(handle))
5066 goto out;
5068 ext4_mark_inode_dirty(handle, inode);
5070 ext4_journal_stop(handle);
5071 out:
5072 return;
5075 #if 0
5077 * Bind an inode's backing buffer_head into this transaction, to prevent
5078 * it from being flushed to disk early. Unlike
5079 * ext4_reserve_inode_write, this leaves behind no bh reference and
5080 * returns no iloc structure, so the caller needs to repeat the iloc
5081 * lookup to mark the inode dirty later.
5083 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
5085 struct ext4_iloc iloc;
5087 int err = 0;
5088 if (handle) {
5089 err = ext4_get_inode_loc(inode, &iloc);
5090 if (!err) {
5091 BUFFER_TRACE(iloc.bh, "get_write_access");
5092 err = jbd2_journal_get_write_access(handle, iloc.bh);
5093 if (!err)
5094 err = ext4_handle_dirty_metadata(handle,
5095 NULL,
5096 iloc.bh);
5097 brelse(iloc.bh);
5100 ext4_std_error(inode->i_sb, err);
5101 return err;
5103 #endif
5105 int ext4_change_inode_journal_flag(struct inode *inode, int val)
5107 journal_t *journal;
5108 handle_t *handle;
5109 int err;
5112 * We have to be very careful here: changing a data block's
5113 * journaling status dynamically is dangerous. If we write a
5114 * data block to the journal, change the status and then delete
5115 * that block, we risk forgetting to revoke the old log record
5116 * from the journal and so a subsequent replay can corrupt data.
5117 * So, first we make sure that the journal is empty and that
5118 * nobody is changing anything.
5121 journal = EXT4_JOURNAL(inode);
5122 if (!journal)
5123 return 0;
5124 if (is_journal_aborted(journal))
5125 return -EROFS;
5126 /* We have to allocate physical blocks for delalloc blocks
5127 * before flushing journal. otherwise delalloc blocks can not
5128 * be allocated any more. even more truncate on delalloc blocks
5129 * could trigger BUG by flushing delalloc blocks in journal.
5130 * There is no delalloc block in non-journal data mode.
5132 if (val && test_opt(inode->i_sb, DELALLOC)) {
5133 err = ext4_alloc_da_blocks(inode);
5134 if (err < 0)
5135 return err;
5138 /* Wait for all existing dio workers */
5139 ext4_inode_block_unlocked_dio(inode);
5140 inode_dio_wait(inode);
5142 jbd2_journal_lock_updates(journal);
5145 * OK, there are no updates running now, and all cached data is
5146 * synced to disk. We are now in a completely consistent state
5147 * which doesn't have anything in the journal, and we know that
5148 * no filesystem updates are running, so it is safe to modify
5149 * the inode's in-core data-journaling state flag now.
5152 if (val)
5153 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5154 else {
5155 jbd2_journal_flush(journal);
5156 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5158 ext4_set_aops(inode);
5160 jbd2_journal_unlock_updates(journal);
5161 ext4_inode_resume_unlocked_dio(inode);
5163 /* Finally we can mark the inode as dirty. */
5165 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
5166 if (IS_ERR(handle))
5167 return PTR_ERR(handle);
5169 err = ext4_mark_inode_dirty(handle, inode);
5170 ext4_handle_sync(handle);
5171 ext4_journal_stop(handle);
5172 ext4_std_error(inode->i_sb, err);
5174 return err;
5177 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
5179 return !buffer_mapped(bh);
5182 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
5184 struct page *page = vmf->page;
5185 loff_t size;
5186 unsigned long len;
5187 int ret;
5188 struct file *file = vma->vm_file;
5189 struct inode *inode = file_inode(file);
5190 struct address_space *mapping = inode->i_mapping;
5191 handle_t *handle;
5192 get_block_t *get_block;
5193 int retries = 0;
5195 sb_start_pagefault(inode->i_sb);
5196 file_update_time(vma->vm_file);
5197 /* Delalloc case is easy... */
5198 if (test_opt(inode->i_sb, DELALLOC) &&
5199 !ext4_should_journal_data(inode) &&
5200 !ext4_nonda_switch(inode->i_sb)) {
5201 do {
5202 ret = __block_page_mkwrite(vma, vmf,
5203 ext4_da_get_block_prep);
5204 } while (ret == -ENOSPC &&
5205 ext4_should_retry_alloc(inode->i_sb, &retries));
5206 goto out_ret;
5209 lock_page(page);
5210 size = i_size_read(inode);
5211 /* Page got truncated from under us? */
5212 if (page->mapping != mapping || page_offset(page) > size) {
5213 unlock_page(page);
5214 ret = VM_FAULT_NOPAGE;
5215 goto out;
5218 if (page->index == size >> PAGE_CACHE_SHIFT)
5219 len = size & ~PAGE_CACHE_MASK;
5220 else
5221 len = PAGE_CACHE_SIZE;
5223 * Return if we have all the buffers mapped. This avoids the need to do
5224 * journal_start/journal_stop which can block and take a long time
5226 if (page_has_buffers(page)) {
5227 if (!ext4_walk_page_buffers(NULL, page_buffers(page),
5228 0, len, NULL,
5229 ext4_bh_unmapped)) {
5230 /* Wait so that we don't change page under IO */
5231 wait_for_stable_page(page);
5232 ret = VM_FAULT_LOCKED;
5233 goto out;
5236 unlock_page(page);
5237 /* OK, we need to fill the hole... */
5238 if (ext4_should_dioread_nolock(inode))
5239 get_block = ext4_get_block_write;
5240 else
5241 get_block = ext4_get_block;
5242 retry_alloc:
5243 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
5244 ext4_writepage_trans_blocks(inode));
5245 if (IS_ERR(handle)) {
5246 ret = VM_FAULT_SIGBUS;
5247 goto out;
5249 ret = __block_page_mkwrite(vma, vmf, get_block);
5250 if (!ret && ext4_should_journal_data(inode)) {
5251 if (ext4_walk_page_buffers(handle, page_buffers(page), 0,
5252 PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) {
5253 unlock_page(page);
5254 ret = VM_FAULT_SIGBUS;
5255 ext4_journal_stop(handle);
5256 goto out;
5258 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
5260 ext4_journal_stop(handle);
5261 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
5262 goto retry_alloc;
5263 out_ret:
5264 ret = block_page_mkwrite_return(ret);
5265 out:
5266 sb_end_pagefault(inode->i_sb);
5267 return ret;