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