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