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