ext4: don't BUG when truncating encrypted inodes on the orphan list
[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         /* If we are processing an encrypted inode during orphan list handling */
3577         if (ext4_encrypted_inode(inode) && !ext4_has_encryption_key(inode))
3578                 return 0;
3579
3580         blocksize = inode->i_sb->s_blocksize;
3581         length = blocksize - (offset & (blocksize - 1));
3582
3583         return ext4_block_zero_page_range(handle, mapping, from, length);
3584 }
3585
3586 int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3587                              loff_t lstart, loff_t length)
3588 {
3589         struct super_block *sb = inode->i_sb;
3590         struct address_space *mapping = inode->i_mapping;
3591         unsigned partial_start, partial_end;
3592         ext4_fsblk_t start, end;
3593         loff_t byte_end = (lstart + length - 1);
3594         int err = 0;
3595
3596         partial_start = lstart & (sb->s_blocksize - 1);
3597         partial_end = byte_end & (sb->s_blocksize - 1);
3598
3599         start = lstart >> sb->s_blocksize_bits;
3600         end = byte_end >> sb->s_blocksize_bits;
3601
3602         /* Handle partial zero within the single block */
3603         if (start == end &&
3604             (partial_start || (partial_end != sb->s_blocksize - 1))) {
3605                 err = ext4_block_zero_page_range(handle, mapping,
3606                                                  lstart, length);
3607                 return err;
3608         }
3609         /* Handle partial zero out on the start of the range */
3610         if (partial_start) {
3611                 err = ext4_block_zero_page_range(handle, mapping,
3612                                                  lstart, sb->s_blocksize);
3613                 if (err)
3614                         return err;
3615         }
3616         /* Handle partial zero out on the end of the range */
3617         if (partial_end != sb->s_blocksize - 1)
3618                 err = ext4_block_zero_page_range(handle, mapping,
3619                                                  byte_end - partial_end,
3620                                                  partial_end + 1);
3621         return err;
3622 }
3623
3624 int ext4_can_truncate(struct inode *inode)
3625 {
3626         if (S_ISREG(inode->i_mode))
3627                 return 1;
3628         if (S_ISDIR(inode->i_mode))
3629                 return 1;
3630         if (S_ISLNK(inode->i_mode))
3631                 return !ext4_inode_is_fast_symlink(inode);
3632         return 0;
3633 }
3634
3635 /*
3636  * We have to make sure i_disksize gets properly updated before we truncate
3637  * page cache due to hole punching or zero range. Otherwise i_disksize update
3638  * can get lost as it may have been postponed to submission of writeback but
3639  * that will never happen after we truncate page cache.
3640  */
3641 int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
3642                                       loff_t len)
3643 {
3644         handle_t *handle;
3645         loff_t size = i_size_read(inode);
3646
3647         WARN_ON(!mutex_is_locked(&inode->i_mutex));
3648         if (offset > size || offset + len < size)
3649                 return 0;
3650
3651         if (EXT4_I(inode)->i_disksize >= size)
3652                 return 0;
3653
3654         handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
3655         if (IS_ERR(handle))
3656                 return PTR_ERR(handle);
3657         ext4_update_i_disksize(inode, size);
3658         ext4_mark_inode_dirty(handle, inode);
3659         ext4_journal_stop(handle);
3660
3661         return 0;
3662 }
3663
3664 /*
3665  * ext4_punch_hole: punches a hole in a file by releasing the blocks
3666  * associated with the given offset and length
3667  *
3668  * @inode:  File inode
3669  * @offset: The offset where the hole will begin
3670  * @len:    The length of the hole
3671  *
3672  * Returns: 0 on success or negative on failure
3673  */
3674
3675 int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length)
3676 {
3677         struct super_block *sb = inode->i_sb;
3678         ext4_lblk_t first_block, stop_block;
3679         struct address_space *mapping = inode->i_mapping;
3680         loff_t first_block_offset, last_block_offset;
3681         handle_t *handle;
3682         unsigned int credits;
3683         int ret = 0;
3684
3685         if (!S_ISREG(inode->i_mode))
3686                 return -EOPNOTSUPP;
3687
3688         trace_ext4_punch_hole(inode, offset, length, 0);
3689
3690         /*
3691          * Write out all dirty pages to avoid race conditions
3692          * Then release them.
3693          */
3694         if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
3695                 ret = filemap_write_and_wait_range(mapping, offset,
3696                                                    offset + length - 1);
3697                 if (ret)
3698                         return ret;
3699         }
3700
3701         mutex_lock(&inode->i_mutex);
3702
3703         /* No need to punch hole beyond i_size */
3704         if (offset >= inode->i_size)
3705                 goto out_mutex;
3706
3707         /*
3708          * If the hole extends beyond i_size, set the hole
3709          * to end after the page that contains i_size
3710          */
3711         if (offset + length > inode->i_size) {
3712                 length = inode->i_size +
3713                    PAGE_CACHE_SIZE - (inode->i_size & (PAGE_CACHE_SIZE - 1)) -
3714                    offset;
3715         }
3716
3717         if (offset & (sb->s_blocksize - 1) ||
3718             (offset + length) & (sb->s_blocksize - 1)) {
3719                 /*
3720                  * Attach jinode to inode for jbd2 if we do any zeroing of
3721                  * partial block
3722                  */
3723                 ret = ext4_inode_attach_jinode(inode);
3724                 if (ret < 0)
3725                         goto out_mutex;
3726
3727         }
3728
3729         /* Wait all existing dio workers, newcomers will block on i_mutex */
3730         ext4_inode_block_unlocked_dio(inode);
3731         inode_dio_wait(inode);
3732
3733         /*
3734          * Prevent page faults from reinstantiating pages we have released from
3735          * page cache.
3736          */
3737         down_write(&EXT4_I(inode)->i_mmap_sem);
3738         first_block_offset = round_up(offset, sb->s_blocksize);
3739         last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
3740
3741         /* Now release the pages and zero block aligned part of pages*/
3742         if (last_block_offset > first_block_offset) {
3743                 ret = ext4_update_disksize_before_punch(inode, offset, length);
3744                 if (ret)
3745                         goto out_dio;
3746                 truncate_pagecache_range(inode, first_block_offset,
3747                                          last_block_offset);
3748         }
3749
3750         if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3751                 credits = ext4_writepage_trans_blocks(inode);
3752         else
3753                 credits = ext4_blocks_for_truncate(inode);
3754         handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
3755         if (IS_ERR(handle)) {
3756                 ret = PTR_ERR(handle);
3757                 ext4_std_error(sb, ret);
3758                 goto out_dio;
3759         }
3760
3761         ret = ext4_zero_partial_blocks(handle, inode, offset,
3762                                        length);
3763         if (ret)
3764                 goto out_stop;
3765
3766         first_block = (offset + sb->s_blocksize - 1) >>
3767                 EXT4_BLOCK_SIZE_BITS(sb);
3768         stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
3769
3770         /* If there are no blocks to remove, return now */
3771         if (first_block >= stop_block)
3772                 goto out_stop;
3773
3774         down_write(&EXT4_I(inode)->i_data_sem);
3775         ext4_discard_preallocations(inode);
3776
3777         ret = ext4_es_remove_extent(inode, first_block,
3778                                     stop_block - first_block);
3779         if (ret) {
3780                 up_write(&EXT4_I(inode)->i_data_sem);
3781                 goto out_stop;
3782         }
3783
3784         if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3785                 ret = ext4_ext_remove_space(inode, first_block,
3786                                             stop_block - 1);
3787         else
3788                 ret = ext4_ind_remove_space(handle, inode, first_block,
3789                                             stop_block);
3790
3791         up_write(&EXT4_I(inode)->i_data_sem);
3792         if (IS_SYNC(inode))
3793                 ext4_handle_sync(handle);
3794
3795         inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3796         ext4_mark_inode_dirty(handle, inode);
3797 out_stop:
3798         ext4_journal_stop(handle);
3799 out_dio:
3800         up_write(&EXT4_I(inode)->i_mmap_sem);
3801         ext4_inode_resume_unlocked_dio(inode);
3802 out_mutex:
3803         mutex_unlock(&inode->i_mutex);
3804         return ret;
3805 }
3806
3807 int ext4_inode_attach_jinode(struct inode *inode)
3808 {
3809         struct ext4_inode_info *ei = EXT4_I(inode);
3810         struct jbd2_inode *jinode;
3811
3812         if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
3813                 return 0;
3814
3815         jinode = jbd2_alloc_inode(GFP_KERNEL);
3816         spin_lock(&inode->i_lock);
3817         if (!ei->jinode) {
3818                 if (!jinode) {
3819                         spin_unlock(&inode->i_lock);
3820                         return -ENOMEM;
3821                 }
3822                 ei->jinode = jinode;
3823                 jbd2_journal_init_jbd_inode(ei->jinode, inode);
3824                 jinode = NULL;
3825         }
3826         spin_unlock(&inode->i_lock);
3827         if (unlikely(jinode != NULL))
3828                 jbd2_free_inode(jinode);
3829         return 0;
3830 }
3831
3832 /*
3833  * ext4_truncate()
3834  *
3835  * We block out ext4_get_block() block instantiations across the entire
3836  * transaction, and VFS/VM ensures that ext4_truncate() cannot run
3837  * simultaneously on behalf of the same inode.
3838  *
3839  * As we work through the truncate and commit bits of it to the journal there
3840  * is one core, guiding principle: the file's tree must always be consistent on
3841  * disk.  We must be able to restart the truncate after a crash.
3842  *
3843  * The file's tree may be transiently inconsistent in memory (although it
3844  * probably isn't), but whenever we close off and commit a journal transaction,
3845  * the contents of (the filesystem + the journal) must be consistent and
3846  * restartable.  It's pretty simple, really: bottom up, right to left (although
3847  * left-to-right works OK too).
3848  *
3849  * Note that at recovery time, journal replay occurs *before* the restart of
3850  * truncate against the orphan inode list.
3851  *
3852  * The committed inode has the new, desired i_size (which is the same as
3853  * i_disksize in this case).  After a crash, ext4_orphan_cleanup() will see
3854  * that this inode's truncate did not complete and it will again call
3855  * ext4_truncate() to have another go.  So there will be instantiated blocks
3856  * to the right of the truncation point in a crashed ext4 filesystem.  But
3857  * that's fine - as long as they are linked from the inode, the post-crash
3858  * ext4_truncate() run will find them and release them.
3859  */
3860 void ext4_truncate(struct inode *inode)
3861 {
3862         struct ext4_inode_info *ei = EXT4_I(inode);
3863         unsigned int credits;
3864         handle_t *handle;
3865         struct address_space *mapping = inode->i_mapping;
3866
3867         /*
3868          * There is a possibility that we're either freeing the inode
3869          * or it's a completely new inode. In those cases we might not
3870          * have i_mutex locked because it's not necessary.
3871          */
3872         if (!(inode->i_state & (I_NEW|I_FREEING)))
3873                 WARN_ON(!mutex_is_locked(&inode->i_mutex));
3874         trace_ext4_truncate_enter(inode);
3875
3876         if (!ext4_can_truncate(inode))
3877                 return;
3878
3879         ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3880
3881         if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
3882                 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
3883
3884         if (ext4_has_inline_data(inode)) {
3885                 int has_inline = 1;
3886
3887                 ext4_inline_data_truncate(inode, &has_inline);
3888                 if (has_inline)
3889                         return;
3890         }
3891
3892         /* If we zero-out tail of the page, we have to create jinode for jbd2 */
3893         if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
3894                 if (ext4_inode_attach_jinode(inode) < 0)
3895                         return;
3896         }
3897
3898         if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3899                 credits = ext4_writepage_trans_blocks(inode);
3900         else
3901                 credits = ext4_blocks_for_truncate(inode);
3902
3903         handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
3904         if (IS_ERR(handle)) {
3905                 ext4_std_error(inode->i_sb, PTR_ERR(handle));
3906                 return;
3907         }
3908
3909         if (inode->i_size & (inode->i_sb->s_blocksize - 1))
3910                 ext4_block_truncate_page(handle, mapping, inode->i_size);
3911
3912         /*
3913          * We add the inode to the orphan list, so that if this
3914          * truncate spans multiple transactions, and we crash, we will
3915          * resume the truncate when the filesystem recovers.  It also
3916          * marks the inode dirty, to catch the new size.
3917          *
3918          * Implication: the file must always be in a sane, consistent
3919          * truncatable state while each transaction commits.
3920          */
3921         if (ext4_orphan_add(handle, inode))
3922                 goto out_stop;
3923
3924         down_write(&EXT4_I(inode)->i_data_sem);
3925
3926         ext4_discard_preallocations(inode);
3927
3928         if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3929                 ext4_ext_truncate(handle, inode);
3930         else
3931                 ext4_ind_truncate(handle, inode);
3932
3933         up_write(&ei->i_data_sem);
3934
3935         if (IS_SYNC(inode))
3936                 ext4_handle_sync(handle);
3937
3938 out_stop:
3939         /*
3940          * If this was a simple ftruncate() and the file will remain alive,
3941          * then we need to clear up the orphan record which we created above.
3942          * However, if this was a real unlink then we were called by
3943          * ext4_evict_inode(), and we allow that function to clean up the
3944          * orphan info for us.
3945          */
3946         if (inode->i_nlink)
3947                 ext4_orphan_del(handle, inode);
3948
3949         inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3950         ext4_mark_inode_dirty(handle, inode);
3951         ext4_journal_stop(handle);
3952
3953         trace_ext4_truncate_exit(inode);
3954 }
3955
3956 /*
3957  * ext4_get_inode_loc returns with an extra refcount against the inode's
3958  * underlying buffer_head on success. If 'in_mem' is true, we have all
3959  * data in memory that is needed to recreate the on-disk version of this
3960  * inode.
3961  */
3962 static int __ext4_get_inode_loc(struct inode *inode,
3963                                 struct ext4_iloc *iloc, int in_mem)
3964 {
3965         struct ext4_group_desc  *gdp;
3966         struct buffer_head      *bh;
3967         struct super_block      *sb = inode->i_sb;
3968         ext4_fsblk_t            block;
3969         int                     inodes_per_block, inode_offset;
3970
3971         iloc->bh = NULL;
3972         if (!ext4_valid_inum(sb, inode->i_ino))
3973                 return -EFSCORRUPTED;
3974
3975         iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
3976         gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
3977         if (!gdp)
3978                 return -EIO;
3979
3980         /*
3981          * Figure out the offset within the block group inode table
3982          */
3983         inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
3984         inode_offset = ((inode->i_ino - 1) %
3985                         EXT4_INODES_PER_GROUP(sb));
3986         block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
3987         iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
3988
3989         bh = sb_getblk(sb, block);
3990         if (unlikely(!bh))
3991                 return -ENOMEM;
3992         if (!buffer_uptodate(bh)) {
3993                 lock_buffer(bh);
3994
3995                 /*
3996                  * If the buffer has the write error flag, we have failed
3997                  * to write out another inode in the same block.  In this
3998                  * case, we don't have to read the block because we may
3999                  * read the old inode data successfully.
4000                  */
4001                 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
4002                         set_buffer_uptodate(bh);
4003
4004                 if (buffer_uptodate(bh)) {
4005                         /* someone brought it uptodate while we waited */
4006                         unlock_buffer(bh);
4007                         goto has_buffer;
4008                 }
4009
4010                 /*
4011                  * If we have all information of the inode in memory and this
4012                  * is the only valid inode in the block, we need not read the
4013                  * block.
4014                  */
4015                 if (in_mem) {
4016                         struct buffer_head *bitmap_bh;
4017                         int i, start;
4018
4019                         start = inode_offset & ~(inodes_per_block - 1);
4020
4021                         /* Is the inode bitmap in cache? */
4022                         bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4023                         if (unlikely(!bitmap_bh))
4024                                 goto make_io;
4025
4026                         /*
4027                          * If the inode bitmap isn't in cache then the
4028                          * optimisation may end up performing two reads instead
4029                          * of one, so skip it.
4030                          */
4031                         if (!buffer_uptodate(bitmap_bh)) {
4032                                 brelse(bitmap_bh);
4033                                 goto make_io;
4034                         }
4035                         for (i = start; i < start + inodes_per_block; i++) {
4036                                 if (i == inode_offset)
4037                                         continue;
4038                                 if (ext4_test_bit(i, bitmap_bh->b_data))
4039                                         break;
4040                         }
4041                         brelse(bitmap_bh);
4042                         if (i == start + inodes_per_block) {
4043                                 /* all other inodes are free, so skip I/O */
4044                                 memset(bh->b_data, 0, bh->b_size);
4045                                 set_buffer_uptodate(bh);
4046                                 unlock_buffer(bh);
4047                                 goto has_buffer;
4048                         }
4049                 }
4050
4051 make_io:
4052                 /*
4053                  * If we need to do any I/O, try to pre-readahead extra
4054                  * blocks from the inode table.
4055                  */
4056                 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4057                         ext4_fsblk_t b, end, table;
4058                         unsigned num;
4059                         __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4060
4061                         table = ext4_inode_table(sb, gdp);
4062                         /* s_inode_readahead_blks is always a power of 2 */
4063                         b = block & ~((ext4_fsblk_t) ra_blks - 1);
4064                         if (table > b)
4065                                 b = table;
4066                         end = b + ra_blks;
4067                         num = EXT4_INODES_PER_GROUP(sb);
4068                         if (ext4_has_group_desc_csum(sb))
4069                                 num -= ext4_itable_unused_count(sb, gdp);
4070                         table += num / inodes_per_block;
4071                         if (end > table)
4072                                 end = table;
4073                         while (b <= end)
4074                                 sb_breadahead(sb, b++);
4075                 }
4076
4077                 /*
4078                  * There are other valid inodes in the buffer, this inode
4079                  * has in-inode xattrs, or we don't have this inode in memory.
4080                  * Read the block from disk.
4081                  */
4082                 trace_ext4_load_inode(inode);
4083                 get_bh(bh);
4084                 bh->b_end_io = end_buffer_read_sync;
4085                 submit_bh(READ | REQ_META | REQ_PRIO, bh);
4086                 wait_on_buffer(bh);
4087                 if (!buffer_uptodate(bh)) {
4088                         EXT4_ERROR_INODE_BLOCK(inode, block,
4089                                                "unable to read itable block");
4090                         brelse(bh);
4091                         return -EIO;
4092                 }
4093         }
4094 has_buffer:
4095         iloc->bh = bh;
4096         return 0;
4097 }
4098
4099 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4100 {
4101         /* We have all inode data except xattrs in memory here. */
4102         return __ext4_get_inode_loc(inode, iloc,
4103                 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
4104 }
4105
4106 void ext4_set_inode_flags(struct inode *inode)
4107 {
4108         unsigned int flags = EXT4_I(inode)->i_flags;
4109         unsigned int new_fl = 0;
4110
4111         if (flags & EXT4_SYNC_FL)
4112                 new_fl |= S_SYNC;
4113         if (flags & EXT4_APPEND_FL)
4114                 new_fl |= S_APPEND;
4115         if (flags & EXT4_IMMUTABLE_FL)
4116                 new_fl |= S_IMMUTABLE;
4117         if (flags & EXT4_NOATIME_FL)
4118                 new_fl |= S_NOATIME;
4119         if (flags & EXT4_DIRSYNC_FL)
4120                 new_fl |= S_DIRSYNC;
4121         if (test_opt(inode->i_sb, DAX))
4122                 new_fl |= S_DAX;
4123         inode_set_flags(inode, new_fl,
4124                         S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX);
4125 }
4126
4127 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
4128 void ext4_get_inode_flags(struct ext4_inode_info *ei)
4129 {
4130         unsigned int vfs_fl;
4131         unsigned long old_fl, new_fl;
4132
4133         do {
4134                 vfs_fl = ei->vfs_inode.i_flags;
4135                 old_fl = ei->i_flags;
4136                 new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
4137                                 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
4138                                 EXT4_DIRSYNC_FL);
4139                 if (vfs_fl & S_SYNC)
4140                         new_fl |= EXT4_SYNC_FL;
4141                 if (vfs_fl & S_APPEND)
4142                         new_fl |= EXT4_APPEND_FL;
4143                 if (vfs_fl & S_IMMUTABLE)
4144                         new_fl |= EXT4_IMMUTABLE_FL;
4145                 if (vfs_fl & S_NOATIME)
4146                         new_fl |= EXT4_NOATIME_FL;
4147                 if (vfs_fl & S_DIRSYNC)
4148                         new_fl |= EXT4_DIRSYNC_FL;
4149         } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
4150 }
4151
4152 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4153                                   struct ext4_inode_info *ei)
4154 {
4155         blkcnt_t i_blocks ;
4156         struct inode *inode = &(ei->vfs_inode);
4157         struct super_block *sb = inode->i_sb;
4158
4159         if (ext4_has_feature_huge_file(sb)) {
4160                 /* we are using combined 48 bit field */
4161                 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4162                                         le32_to_cpu(raw_inode->i_blocks_lo);
4163                 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
4164                         /* i_blocks represent file system block size */
4165                         return i_blocks  << (inode->i_blkbits - 9);
4166                 } else {
4167                         return i_blocks;
4168                 }
4169         } else {
4170                 return le32_to_cpu(raw_inode->i_blocks_lo);
4171         }
4172 }
4173
4174 static inline void ext4_iget_extra_inode(struct inode *inode,
4175                                          struct ext4_inode *raw_inode,
4176                                          struct ext4_inode_info *ei)
4177 {
4178         __le32 *magic = (void *)raw_inode +
4179                         EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4180         if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4181                 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4182                 ext4_find_inline_data_nolock(inode);
4183         } else
4184                 EXT4_I(inode)->i_inline_off = 0;
4185 }
4186
4187 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
4188 {
4189         struct ext4_iloc iloc;
4190         struct ext4_inode *raw_inode;
4191         struct ext4_inode_info *ei;
4192         struct inode *inode;
4193         journal_t *journal = EXT4_SB(sb)->s_journal;
4194         long ret;
4195         loff_t size;
4196         int block;
4197         uid_t i_uid;
4198         gid_t i_gid;
4199
4200         inode = iget_locked(sb, ino);
4201         if (!inode)
4202                 return ERR_PTR(-ENOMEM);
4203         if (!(inode->i_state & I_NEW))
4204                 return inode;
4205
4206         ei = EXT4_I(inode);
4207         iloc.bh = NULL;
4208
4209         ret = __ext4_get_inode_loc(inode, &iloc, 0);
4210         if (ret < 0)
4211                 goto bad_inode;
4212         raw_inode = ext4_raw_inode(&iloc);
4213
4214         if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4215                 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4216                 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4217                     EXT4_INODE_SIZE(inode->i_sb)) {
4218                         EXT4_ERROR_INODE(inode, "bad extra_isize (%u != %u)",
4219                                 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize,
4220                                 EXT4_INODE_SIZE(inode->i_sb));
4221                         ret = -EFSCORRUPTED;
4222                         goto bad_inode;
4223                 }
4224         } else
4225                 ei->i_extra_isize = 0;
4226
4227         /* Precompute checksum seed for inode metadata */
4228         if (ext4_has_metadata_csum(sb)) {
4229                 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4230                 __u32 csum;
4231                 __le32 inum = cpu_to_le32(inode->i_ino);
4232                 __le32 gen = raw_inode->i_generation;
4233                 csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4234                                    sizeof(inum));
4235                 ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4236                                               sizeof(gen));
4237         }
4238
4239         if (!ext4_inode_csum_verify(inode, raw_inode, ei)) {
4240                 EXT4_ERROR_INODE(inode, "checksum invalid");
4241                 ret = -EFSBADCRC;
4242                 goto bad_inode;
4243         }
4244
4245         inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4246         i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4247         i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4248         if (!(test_opt(inode->i_sb, NO_UID32))) {
4249                 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4250                 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4251         }
4252         i_uid_write(inode, i_uid);
4253         i_gid_write(inode, i_gid);
4254         set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4255
4256         ext4_clear_state_flags(ei);     /* Only relevant on 32-bit archs */
4257         ei->i_inline_off = 0;
4258         ei->i_dir_start_lookup = 0;
4259         ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4260         /* We now have enough fields to check if the inode was active or not.
4261          * This is needed because nfsd might try to access dead inodes
4262          * the test is that same one that e2fsck uses
4263          * NeilBrown 1999oct15
4264          */
4265         if (inode->i_nlink == 0) {
4266                 if ((inode->i_mode == 0 ||
4267                      !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4268                     ino != EXT4_BOOT_LOADER_INO) {
4269                         /* this inode is deleted */
4270                         ret = -ESTALE;
4271                         goto bad_inode;
4272                 }
4273                 /* The only unlinked inodes we let through here have
4274                  * valid i_mode and are being read by the orphan
4275                  * recovery code: that's fine, we're about to complete
4276                  * the process of deleting those.
4277                  * OR it is the EXT4_BOOT_LOADER_INO which is
4278                  * not initialized on a new filesystem. */
4279         }
4280         ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4281         inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4282         ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4283         if (ext4_has_feature_64bit(sb))
4284                 ei->i_file_acl |=
4285                         ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4286         inode->i_size = ext4_isize(raw_inode);
4287         if ((size = i_size_read(inode)) < 0) {
4288                 EXT4_ERROR_INODE(inode, "bad i_size value: %lld", size);
4289                 ret = -EFSCORRUPTED;
4290                 goto bad_inode;
4291         }
4292         ei->i_disksize = inode->i_size;
4293 #ifdef CONFIG_QUOTA
4294         ei->i_reserved_quota = 0;
4295 #endif
4296         inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4297         ei->i_block_group = iloc.block_group;
4298         ei->i_last_alloc_group = ~0;
4299         /*
4300          * NOTE! The in-memory inode i_data array is in little-endian order
4301          * even on big-endian machines: we do NOT byteswap the block numbers!
4302          */
4303         for (block = 0; block < EXT4_N_BLOCKS; block++)
4304                 ei->i_data[block] = raw_inode->i_block[block];
4305         INIT_LIST_HEAD(&ei->i_orphan);
4306
4307         /*
4308          * Set transaction id's of transactions that have to be committed
4309          * to finish f[data]sync. We set them to currently running transaction
4310          * as we cannot be sure that the inode or some of its metadata isn't
4311          * part of the transaction - the inode could have been reclaimed and
4312          * now it is reread from disk.
4313          */
4314         if (journal) {
4315                 transaction_t *transaction;
4316                 tid_t tid;
4317
4318                 read_lock(&journal->j_state_lock);
4319                 if (journal->j_running_transaction)
4320                         transaction = journal->j_running_transaction;
4321                 else
4322                         transaction = journal->j_committing_transaction;
4323                 if (transaction)
4324                         tid = transaction->t_tid;
4325                 else
4326                         tid = journal->j_commit_sequence;
4327                 read_unlock(&journal->j_state_lock);
4328                 ei->i_sync_tid = tid;
4329                 ei->i_datasync_tid = tid;
4330         }
4331
4332         if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4333                 if (ei->i_extra_isize == 0) {
4334                         /* The extra space is currently unused. Use it. */
4335                         ei->i_extra_isize = sizeof(struct ext4_inode) -
4336                                             EXT4_GOOD_OLD_INODE_SIZE;
4337                 } else {
4338                         ext4_iget_extra_inode(inode, raw_inode, ei);
4339                 }
4340         }
4341
4342         EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4343         EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4344         EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4345         EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4346
4347         if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4348                 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
4349                 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4350                         if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4351                                 inode->i_version |=
4352                     (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4353                 }
4354         }
4355
4356         ret = 0;
4357         if (ei->i_file_acl &&
4358             !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
4359                 EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
4360                                  ei->i_file_acl);
4361                 ret = -EFSCORRUPTED;
4362                 goto bad_inode;
4363         } else if (!ext4_has_inline_data(inode)) {
4364                 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4365                         if ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4366                             (S_ISLNK(inode->i_mode) &&
4367                              !ext4_inode_is_fast_symlink(inode))))
4368                                 /* Validate extent which is part of inode */
4369                                 ret = ext4_ext_check_inode(inode);
4370                 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4371                            (S_ISLNK(inode->i_mode) &&
4372                             !ext4_inode_is_fast_symlink(inode))) {
4373                         /* Validate block references which are part of inode */
4374                         ret = ext4_ind_check_inode(inode);
4375                 }
4376         }
4377         if (ret)
4378                 goto bad_inode;
4379
4380         if (S_ISREG(inode->i_mode)) {
4381                 inode->i_op = &ext4_file_inode_operations;
4382                 inode->i_fop = &ext4_file_operations;
4383                 ext4_set_aops(inode);
4384         } else if (S_ISDIR(inode->i_mode)) {
4385                 inode->i_op = &ext4_dir_inode_operations;
4386                 inode->i_fop = &ext4_dir_operations;
4387         } else if (S_ISLNK(inode->i_mode)) {
4388                 if (ext4_encrypted_inode(inode)) {
4389                         inode->i_op = &ext4_encrypted_symlink_inode_operations;
4390                         ext4_set_aops(inode);
4391                 } else if (ext4_inode_is_fast_symlink(inode)) {
4392                         inode->i_link = (char *)ei->i_data;
4393                         inode->i_op = &ext4_fast_symlink_inode_operations;
4394                         nd_terminate_link(ei->i_data, inode->i_size,
4395                                 sizeof(ei->i_data) - 1);
4396                 } else {
4397                         inode->i_op = &ext4_symlink_inode_operations;
4398                         ext4_set_aops(inode);
4399                 }
4400         } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4401               S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4402                 inode->i_op = &ext4_special_inode_operations;
4403                 if (raw_inode->i_block[0])
4404                         init_special_inode(inode, inode->i_mode,
4405                            old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4406                 else
4407                         init_special_inode(inode, inode->i_mode,
4408                            new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4409         } else if (ino == EXT4_BOOT_LOADER_INO) {
4410                 make_bad_inode(inode);
4411         } else {
4412                 ret = -EFSCORRUPTED;
4413                 EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
4414                 goto bad_inode;
4415         }
4416         brelse(iloc.bh);
4417         ext4_set_inode_flags(inode);
4418         unlock_new_inode(inode);
4419         return inode;
4420
4421 bad_inode:
4422         brelse(iloc.bh);
4423         iget_failed(inode);
4424         return ERR_PTR(ret);
4425 }
4426
4427 struct inode *ext4_iget_normal(struct super_block *sb, unsigned long ino)
4428 {
4429         if (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)
4430                 return ERR_PTR(-EFSCORRUPTED);
4431         return ext4_iget(sb, ino);
4432 }
4433
4434 static int ext4_inode_blocks_set(handle_t *handle,
4435                                 struct ext4_inode *raw_inode,
4436                                 struct ext4_inode_info *ei)
4437 {
4438         struct inode *inode = &(ei->vfs_inode);
4439         u64 i_blocks = inode->i_blocks;
4440         struct super_block *sb = inode->i_sb;
4441
4442         if (i_blocks <= ~0U) {
4443                 /*
4444                  * i_blocks can be represented in a 32 bit variable
4445                  * as multiple of 512 bytes
4446                  */
4447                 raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
4448                 raw_inode->i_blocks_high = 0;
4449                 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4450                 return 0;
4451         }
4452         if (!ext4_has_feature_huge_file(sb))
4453                 return -EFBIG;
4454
4455         if (i_blocks <= 0xffffffffffffULL) {
4456                 /*
4457                  * i_blocks can be represented in a 48 bit variable
4458                  * as multiple of 512 bytes
4459                  */
4460                 raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
4461                 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4462                 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4463         } else {
4464                 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4465                 /* i_block is stored in file system block size */
4466                 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4467                 raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
4468                 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4469         }
4470         return 0;
4471 }
4472
4473 struct other_inode {
4474         unsigned long           orig_ino;
4475         struct ext4_inode       *raw_inode;
4476 };
4477
4478 static int other_inode_match(struct inode * inode, unsigned long ino,
4479                              void *data)
4480 {
4481         struct other_inode *oi = (struct other_inode *) data;
4482
4483         if ((inode->i_ino != ino) ||
4484             (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
4485                                I_DIRTY_SYNC | I_DIRTY_DATASYNC)) ||
4486             ((inode->i_state & I_DIRTY_TIME) == 0))
4487                 return 0;
4488         spin_lock(&inode->i_lock);
4489         if (((inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
4490                                 I_DIRTY_SYNC | I_DIRTY_DATASYNC)) == 0) &&
4491             (inode->i_state & I_DIRTY_TIME)) {
4492                 struct ext4_inode_info  *ei = EXT4_I(inode);
4493
4494                 inode->i_state &= ~(I_DIRTY_TIME | I_DIRTY_TIME_EXPIRED);
4495                 spin_unlock(&inode->i_lock);
4496
4497                 spin_lock(&ei->i_raw_lock);
4498                 EXT4_INODE_SET_XTIME(i_ctime, inode, oi->raw_inode);
4499                 EXT4_INODE_SET_XTIME(i_mtime, inode, oi->raw_inode);
4500                 EXT4_INODE_SET_XTIME(i_atime, inode, oi->raw_inode);
4501                 ext4_inode_csum_set(inode, oi->raw_inode, ei);
4502                 spin_unlock(&ei->i_raw_lock);
4503                 trace_ext4_other_inode_update_time(inode, oi->orig_ino);
4504                 return -1;
4505         }
4506         spin_unlock(&inode->i_lock);
4507         return -1;
4508 }
4509
4510 /*
4511  * Opportunistically update the other time fields for other inodes in
4512  * the same inode table block.
4513  */
4514 static void ext4_update_other_inodes_time(struct super_block *sb,
4515                                           unsigned long orig_ino, char *buf)
4516 {
4517         struct other_inode oi;
4518         unsigned long ino;
4519         int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4520         int inode_size = EXT4_INODE_SIZE(sb);
4521
4522         oi.orig_ino = orig_ino;
4523         /*
4524          * Calculate the first inode in the inode table block.  Inode
4525          * numbers are one-based.  That is, the first inode in a block
4526          * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
4527          */
4528         ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
4529         for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
4530                 if (ino == orig_ino)
4531                         continue;
4532                 oi.raw_inode = (struct ext4_inode *) buf;
4533                 (void) find_inode_nowait(sb, ino, other_inode_match, &oi);
4534         }
4535 }
4536
4537 /*
4538  * Post the struct inode info into an on-disk inode location in the
4539  * buffer-cache.  This gobbles the caller's reference to the
4540  * buffer_head in the inode location struct.
4541  *
4542  * The caller must have write access to iloc->bh.
4543  */
4544 static int ext4_do_update_inode(handle_t *handle,
4545                                 struct inode *inode,
4546                                 struct ext4_iloc *iloc)
4547 {
4548         struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
4549         struct ext4_inode_info *ei = EXT4_I(inode);
4550         struct buffer_head *bh = iloc->bh;
4551         struct super_block *sb = inode->i_sb;
4552         int err = 0, rc, block;
4553         int need_datasync = 0, set_large_file = 0;
4554         uid_t i_uid;
4555         gid_t i_gid;
4556
4557         spin_lock(&ei->i_raw_lock);
4558
4559         /* For fields not tracked in the in-memory inode,
4560          * initialise them to zero for new inodes. */
4561         if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
4562                 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
4563
4564         ext4_get_inode_flags(ei);
4565         raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4566         i_uid = i_uid_read(inode);
4567         i_gid = i_gid_read(inode);
4568         if (!(test_opt(inode->i_sb, NO_UID32))) {
4569                 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
4570                 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
4571 /*
4572  * Fix up interoperability with old kernels. Otherwise, old inodes get
4573  * re-used with the upper 16 bits of the uid/gid intact
4574  */
4575                 if (ei->i_dtime && list_empty(&ei->i_orphan)) {
4576                         raw_inode->i_uid_high = 0;
4577                         raw_inode->i_gid_high = 0;
4578                 } else {
4579                         raw_inode->i_uid_high =
4580                                 cpu_to_le16(high_16_bits(i_uid));
4581                         raw_inode->i_gid_high =
4582                                 cpu_to_le16(high_16_bits(i_gid));
4583                 }
4584         } else {
4585                 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
4586                 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
4587                 raw_inode->i_uid_high = 0;
4588                 raw_inode->i_gid_high = 0;
4589         }
4590         raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4591
4592         EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4593         EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4594         EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4595         EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4596
4597         err = ext4_inode_blocks_set(handle, raw_inode, ei);
4598         if (err) {
4599                 spin_unlock(&ei->i_raw_lock);
4600                 goto out_brelse;
4601         }
4602         raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4603         raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4604         if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
4605                 raw_inode->i_file_acl_high =
4606                         cpu_to_le16(ei->i_file_acl >> 32);
4607         raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4608         if (ei->i_disksize != ext4_isize(raw_inode)) {
4609                 ext4_isize_set(raw_inode, ei->i_disksize);
4610                 need_datasync = 1;
4611         }
4612         if (ei->i_disksize > 0x7fffffffULL) {
4613                 if (!ext4_has_feature_large_file(sb) ||
4614                                 EXT4_SB(sb)->s_es->s_rev_level ==
4615                     cpu_to_le32(EXT4_GOOD_OLD_REV))
4616                         set_large_file = 1;
4617         }
4618         raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4619         if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4620                 if (old_valid_dev(inode->i_rdev)) {
4621                         raw_inode->i_block[0] =
4622                                 cpu_to_le32(old_encode_dev(inode->i_rdev));
4623                         raw_inode->i_block[1] = 0;
4624                 } else {
4625                         raw_inode->i_block[0] = 0;
4626                         raw_inode->i_block[1] =
4627                                 cpu_to_le32(new_encode_dev(inode->i_rdev));
4628                         raw_inode->i_block[2] = 0;
4629                 }
4630         } else if (!ext4_has_inline_data(inode)) {
4631                 for (block = 0; block < EXT4_N_BLOCKS; block++)
4632                         raw_inode->i_block[block] = ei->i_data[block];
4633         }
4634
4635         if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4636                 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
4637                 if (ei->i_extra_isize) {
4638                         if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4639                                 raw_inode->i_version_hi =
4640                                         cpu_to_le32(inode->i_version >> 32);
4641                         raw_inode->i_extra_isize =
4642                                 cpu_to_le16(ei->i_extra_isize);
4643                 }
4644         }
4645         ext4_inode_csum_set(inode, raw_inode, ei);
4646         spin_unlock(&ei->i_raw_lock);
4647         if (inode->i_sb->s_flags & MS_LAZYTIME)
4648                 ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
4649                                               bh->b_data);
4650
4651         BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4652         rc = ext4_handle_dirty_metadata(handle, NULL, bh);
4653         if (!err)
4654                 err = rc;
4655         ext4_clear_inode_state(inode, EXT4_STATE_NEW);
4656         if (set_large_file) {
4657                 BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
4658                 err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh);
4659                 if (err)
4660                         goto out_brelse;
4661                 ext4_update_dynamic_rev(sb);
4662                 ext4_set_feature_large_file(sb);
4663                 ext4_handle_sync(handle);
4664                 err = ext4_handle_dirty_super(handle, sb);
4665         }
4666         ext4_update_inode_fsync_trans(handle, inode, need_datasync);
4667 out_brelse:
4668         brelse(bh);
4669         ext4_std_error(inode->i_sb, err);
4670         return err;
4671 }
4672
4673 /*
4674  * ext4_write_inode()
4675  *
4676  * We are called from a few places:
4677  *
4678  * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
4679  *   Here, there will be no transaction running. We wait for any running
4680  *   transaction to commit.
4681  *
4682  * - Within flush work (sys_sync(), kupdate and such).
4683  *   We wait on commit, if told to.
4684  *
4685  * - Within iput_final() -> write_inode_now()
4686  *   We wait on commit, if told to.
4687  *
4688  * In all cases it is actually safe for us to return without doing anything,
4689  * because the inode has been copied into a raw inode buffer in
4690  * ext4_mark_inode_dirty().  This is a correctness thing for WB_SYNC_ALL
4691  * writeback.
4692  *
4693  * Note that we are absolutely dependent upon all inode dirtiers doing the
4694  * right thing: they *must* call mark_inode_dirty() after dirtying info in
4695  * which we are interested.
4696  *
4697  * It would be a bug for them to not do this.  The code:
4698  *
4699  *      mark_inode_dirty(inode)
4700  *      stuff();
4701  *      inode->i_size = expr;
4702  *
4703  * is in error because write_inode() could occur while `stuff()' is running,
4704  * and the new i_size will be lost.  Plus the inode will no longer be on the
4705  * superblock's dirty inode list.
4706  */
4707 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
4708 {
4709         int err;
4710
4711         if (WARN_ON_ONCE(current->flags & PF_MEMALLOC))
4712                 return 0;
4713
4714         if (EXT4_SB(inode->i_sb)->s_journal) {
4715                 if (ext4_journal_current_handle()) {
4716                         jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4717                         dump_stack();
4718                         return -EIO;
4719                 }
4720
4721                 /*
4722                  * No need to force transaction in WB_SYNC_NONE mode. Also
4723                  * ext4_sync_fs() will force the commit after everything is
4724                  * written.
4725                  */
4726                 if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
4727                         return 0;
4728
4729                 err = ext4_force_commit(inode->i_sb);
4730         } else {
4731                 struct ext4_iloc iloc;
4732
4733                 err = __ext4_get_inode_loc(inode, &iloc, 0);
4734                 if (err)
4735                         return err;
4736                 /*
4737                  * sync(2) will flush the whole buffer cache. No need to do
4738                  * it here separately for each inode.
4739                  */
4740                 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
4741                         sync_dirty_buffer(iloc.bh);
4742                 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
4743                         EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
4744                                          "IO error syncing inode");
4745                         err = -EIO;
4746                 }
4747                 brelse(iloc.bh);
4748         }
4749         return err;
4750 }
4751
4752 /*
4753  * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
4754  * buffers that are attached to a page stradding i_size and are undergoing
4755  * commit. In that case we have to wait for commit to finish and try again.
4756  */
4757 static void ext4_wait_for_tail_page_commit(struct inode *inode)
4758 {
4759         struct page *page;
4760         unsigned offset;
4761         journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
4762         tid_t commit_tid = 0;
4763         int ret;
4764
4765         offset = inode->i_size & (PAGE_CACHE_SIZE - 1);
4766         /*
4767          * All buffers in the last page remain valid? Then there's nothing to
4768          * do. We do the check mainly to optimize the common PAGE_CACHE_SIZE ==
4769          * blocksize case
4770          */
4771         if (offset > PAGE_CACHE_SIZE - (1 << inode->i_blkbits))
4772                 return;
4773         while (1) {
4774                 page = find_lock_page(inode->i_mapping,
4775                                       inode->i_size >> PAGE_CACHE_SHIFT);
4776                 if (!page)
4777                         return;
4778                 ret = __ext4_journalled_invalidatepage(page, offset,
4779                                                 PAGE_CACHE_SIZE - offset);
4780                 unlock_page(page);
4781                 page_cache_release(page);
4782                 if (ret != -EBUSY)
4783                         return;
4784                 commit_tid = 0;
4785                 read_lock(&journal->j_state_lock);
4786                 if (journal->j_committing_transaction)
4787                         commit_tid = journal->j_committing_transaction->t_tid;
4788                 read_unlock(&journal->j_state_lock);
4789                 if (commit_tid)
4790                         jbd2_log_wait_commit(journal, commit_tid);
4791         }
4792 }
4793
4794 /*
4795  * ext4_setattr()
4796  *
4797  * Called from notify_change.
4798  *
4799  * We want to trap VFS attempts to truncate the file as soon as
4800  * possible.  In particular, we want to make sure that when the VFS
4801  * shrinks i_size, we put the inode on the orphan list and modify
4802  * i_disksize immediately, so that during the subsequent flushing of
4803  * dirty pages and freeing of disk blocks, we can guarantee that any
4804  * commit will leave the blocks being flushed in an unused state on
4805  * disk.  (On recovery, the inode will get truncated and the blocks will
4806  * be freed, so we have a strong guarantee that no future commit will
4807  * leave these blocks visible to the user.)
4808  *
4809  * Another thing we have to assure is that if we are in ordered mode
4810  * and inode is still attached to the committing transaction, we must
4811  * we start writeout of all the dirty pages which are being truncated.
4812  * This way we are sure that all the data written in the previous
4813  * transaction are already on disk (truncate waits for pages under
4814  * writeback).
4815  *
4816  * Called with inode->i_mutex down.
4817  */
4818 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
4819 {
4820         struct inode *inode = d_inode(dentry);
4821         int error, rc = 0;
4822         int orphan = 0;
4823         const unsigned int ia_valid = attr->ia_valid;
4824
4825         error = inode_change_ok(inode, attr);
4826         if (error)
4827                 return error;
4828
4829         if (is_quota_modification(inode, attr)) {
4830                 error = dquot_initialize(inode);
4831                 if (error)
4832                         return error;
4833         }
4834         if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
4835             (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
4836                 handle_t *handle;
4837
4838                 /* (user+group)*(old+new) structure, inode write (sb,
4839                  * inode block, ? - but truncate inode update has it) */
4840                 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
4841                         (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
4842                          EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
4843                 if (IS_ERR(handle)) {
4844                         error = PTR_ERR(handle);
4845                         goto err_out;
4846                 }
4847                 error = dquot_transfer(inode, attr);
4848                 if (error) {
4849                         ext4_journal_stop(handle);
4850                         return error;
4851                 }
4852                 /* Update corresponding info in inode so that everything is in
4853                  * one transaction */
4854                 if (attr->ia_valid & ATTR_UID)
4855                         inode->i_uid = attr->ia_uid;
4856                 if (attr->ia_valid & ATTR_GID)
4857                         inode->i_gid = attr->ia_gid;
4858                 error = ext4_mark_inode_dirty(handle, inode);
4859                 ext4_journal_stop(handle);
4860         }
4861
4862         if (attr->ia_valid & ATTR_SIZE) {
4863                 handle_t *handle;
4864                 loff_t oldsize = inode->i_size;
4865                 int shrink = (attr->ia_size <= inode->i_size);
4866
4867                 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4868                         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4869
4870                         if (attr->ia_size > sbi->s_bitmap_maxbytes)
4871                                 return -EFBIG;
4872                 }
4873                 if (!S_ISREG(inode->i_mode))
4874                         return -EINVAL;
4875
4876                 if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
4877                         inode_inc_iversion(inode);
4878
4879                 if (ext4_should_order_data(inode) &&
4880                     (attr->ia_size < inode->i_size)) {
4881                         error = ext4_begin_ordered_truncate(inode,
4882                                                             attr->ia_size);
4883                         if (error)
4884                                 goto err_out;
4885                 }
4886                 if (attr->ia_size != inode->i_size) {
4887                         handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
4888                         if (IS_ERR(handle)) {
4889                                 error = PTR_ERR(handle);
4890                                 goto err_out;
4891                         }
4892                         if (ext4_handle_valid(handle) && shrink) {
4893                                 error = ext4_orphan_add(handle, inode);
4894                                 orphan = 1;
4895                         }
4896                         /*
4897                          * Update c/mtime on truncate up, ext4_truncate() will
4898                          * update c/mtime in shrink case below
4899                          */
4900                         if (!shrink) {
4901                                 inode->i_mtime = ext4_current_time(inode);
4902                                 inode->i_ctime = inode->i_mtime;
4903                         }
4904                         down_write(&EXT4_I(inode)->i_data_sem);
4905                         EXT4_I(inode)->i_disksize = attr->ia_size;
4906                         rc = ext4_mark_inode_dirty(handle, inode);
4907                         if (!error)
4908                                 error = rc;
4909                         /*
4910                          * We have to update i_size under i_data_sem together
4911                          * with i_disksize to avoid races with writeback code
4912                          * running ext4_wb_update_i_disksize().
4913                          */
4914                         if (!error)
4915                                 i_size_write(inode, attr->ia_size);
4916                         up_write(&EXT4_I(inode)->i_data_sem);
4917                         ext4_journal_stop(handle);
4918                         if (error) {
4919                                 if (orphan)
4920                                         ext4_orphan_del(NULL, inode);
4921                                 goto err_out;
4922                         }
4923                 }
4924                 if (!shrink)
4925                         pagecache_isize_extended(inode, oldsize, inode->i_size);
4926
4927                 /*
4928                  * Blocks are going to be removed from the inode. Wait
4929                  * for dio in flight.  Temporarily disable
4930                  * dioread_nolock to prevent livelock.
4931                  */
4932                 if (orphan) {
4933                         if (!ext4_should_journal_data(inode)) {
4934                                 ext4_inode_block_unlocked_dio(inode);
4935                                 inode_dio_wait(inode);
4936                                 ext4_inode_resume_unlocked_dio(inode);
4937                         } else
4938                                 ext4_wait_for_tail_page_commit(inode);
4939                 }
4940                 down_write(&EXT4_I(inode)->i_mmap_sem);
4941                 /*
4942                  * Truncate pagecache after we've waited for commit
4943                  * in data=journal mode to make pages freeable.
4944                  */
4945                 truncate_pagecache(inode, inode->i_size);
4946                 if (shrink)
4947                         ext4_truncate(inode);
4948                 up_write(&EXT4_I(inode)->i_mmap_sem);
4949         }
4950
4951         if (!rc) {
4952                 setattr_copy(inode, attr);
4953                 mark_inode_dirty(inode);
4954         }
4955
4956         /*
4957          * If the call to ext4_truncate failed to get a transaction handle at
4958          * all, we need to clean up the in-core orphan list manually.
4959          */
4960         if (orphan && inode->i_nlink)
4961                 ext4_orphan_del(NULL, inode);
4962
4963         if (!rc && (ia_valid & ATTR_MODE))
4964                 rc = posix_acl_chmod(inode, inode->i_mode);
4965
4966 err_out:
4967         ext4_std_error(inode->i_sb, error);
4968         if (!error)
4969                 error = rc;
4970         return error;
4971 }
4972
4973 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
4974                  struct kstat *stat)
4975 {
4976         struct inode *inode;
4977         unsigned long long delalloc_blocks;
4978
4979         inode = d_inode(dentry);
4980         generic_fillattr(inode, stat);
4981
4982         /*
4983          * If there is inline data in the inode, the inode will normally not
4984          * have data blocks allocated (it may have an external xattr block).
4985          * Report at least one sector for such files, so tools like tar, rsync,
4986          * others doen't incorrectly think the file is completely sparse.
4987          */
4988         if (unlikely(ext4_has_inline_data(inode)))
4989                 stat->blocks += (stat->size + 511) >> 9;
4990
4991         /*
4992          * We can't update i_blocks if the block allocation is delayed
4993          * otherwise in the case of system crash before the real block
4994          * allocation is done, we will have i_blocks inconsistent with
4995          * on-disk file blocks.
4996          * We always keep i_blocks updated together with real
4997          * allocation. But to not confuse with user, stat
4998          * will return the blocks that include the delayed allocation
4999          * blocks for this file.
5000          */
5001         delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
5002                                    EXT4_I(inode)->i_reserved_data_blocks);
5003         stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
5004         return 0;
5005 }
5006
5007 static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5008                                    int pextents)
5009 {
5010         if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5011                 return ext4_ind_trans_blocks(inode, lblocks);
5012         return ext4_ext_index_trans_blocks(inode, pextents);
5013 }
5014
5015 /*
5016  * Account for index blocks, block groups bitmaps and block group
5017  * descriptor blocks if modify datablocks and index blocks
5018  * worse case, the indexs blocks spread over different block groups
5019  *
5020  * If datablocks are discontiguous, they are possible to spread over
5021  * different block groups too. If they are contiguous, with flexbg,
5022  * they could still across block group boundary.
5023  *
5024  * Also account for superblock, inode, quota and xattr blocks
5025  */
5026 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5027                                   int pextents)
5028 {
5029         ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
5030         int gdpblocks;
5031         int idxblocks;
5032         int ret = 0;
5033
5034         /*
5035          * How many index blocks need to touch to map @lblocks logical blocks
5036          * to @pextents physical extents?
5037          */
5038         idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5039
5040         ret = idxblocks;
5041
5042         /*
5043          * Now let's see how many group bitmaps and group descriptors need
5044          * to account
5045          */
5046         groups = idxblocks + pextents;
5047         gdpblocks = groups;
5048         if (groups > ngroups)
5049                 groups = ngroups;
5050         if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5051                 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5052
5053         /* bitmaps and block group descriptor blocks */
5054         ret += groups + gdpblocks;
5055
5056         /* Blocks for super block, inode, quota and xattr blocks */
5057         ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5058
5059         return ret;
5060 }
5061
5062 /*
5063  * Calculate the total number of credits to reserve to fit
5064  * the modification of a single pages into a single transaction,
5065  * which may include multiple chunks of block allocations.
5066  *
5067  * This could be called via ext4_write_begin()
5068  *
5069  * We need to consider the worse case, when
5070  * one new block per extent.
5071  */
5072 int ext4_writepage_trans_blocks(struct inode *inode)
5073 {
5074         int bpp = ext4_journal_blocks_per_page(inode);
5075         int ret;
5076
5077         ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5078
5079         /* Account for data blocks for journalled mode */
5080         if (ext4_should_journal_data(inode))
5081                 ret += bpp;
5082         return ret;
5083 }
5084
5085 /*
5086  * Calculate the journal credits for a chunk of data modification.
5087  *
5088  * This is called from DIO, fallocate or whoever calling
5089  * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5090  *
5091  * journal buffers for data blocks are not included here, as DIO
5092  * and fallocate do no need to journal data buffers.
5093  */
5094 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5095 {
5096         return ext4_meta_trans_blocks(inode, nrblocks, 1);
5097 }
5098
5099 /*
5100  * The caller must have previously called ext4_reserve_inode_write().
5101  * Give this, we know that the caller already has write access to iloc->bh.
5102  */
5103 int ext4_mark_iloc_dirty(handle_t *handle,
5104                          struct inode *inode, struct ext4_iloc *iloc)
5105 {
5106         int err = 0;
5107
5108         if (IS_I_VERSION(inode))
5109                 inode_inc_iversion(inode);
5110
5111         /* the do_update_inode consumes one bh->b_count */
5112         get_bh(iloc->bh);
5113
5114         /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5115         err = ext4_do_update_inode(handle, inode, iloc);
5116         put_bh(iloc->bh);
5117         return err;
5118 }
5119
5120 /*
5121  * On success, We end up with an outstanding reference count against
5122  * iloc->bh.  This _must_ be cleaned up later.
5123  */
5124
5125 int
5126 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5127                          struct ext4_iloc *iloc)
5128 {
5129         int err;
5130
5131         err = ext4_get_inode_loc(inode, iloc);
5132         if (!err) {
5133                 BUFFER_TRACE(iloc->bh, "get_write_access");
5134                 err = ext4_journal_get_write_access(handle, iloc->bh);
5135                 if (err) {
5136                         brelse(iloc->bh);
5137                         iloc->bh = NULL;
5138                 }
5139         }
5140         ext4_std_error(inode->i_sb, err);
5141         return err;
5142 }
5143
5144 /*
5145  * Expand an inode by new_extra_isize bytes.
5146  * Returns 0 on success or negative error number on failure.
5147  */
5148 static int ext4_expand_extra_isize(struct inode *inode,
5149                                    unsigned int new_extra_isize,
5150                                    struct ext4_iloc iloc,
5151                                    handle_t *handle)
5152 {
5153         struct ext4_inode *raw_inode;
5154         struct ext4_xattr_ibody_header *header;
5155
5156         if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
5157                 return 0;
5158
5159         raw_inode = ext4_raw_inode(&iloc);
5160
5161         header = IHDR(inode, raw_inode);
5162
5163         /* No extended attributes present */
5164         if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5165             header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5166                 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
5167                         new_extra_isize);
5168                 EXT4_I(inode)->i_extra_isize = new_extra_isize;
5169                 return 0;
5170         }
5171
5172         /* try to expand with EAs present */
5173         return ext4_expand_extra_isize_ea(inode, new_extra_isize,
5174                                           raw_inode, handle);
5175 }
5176
5177 /*
5178  * What we do here is to mark the in-core inode as clean with respect to inode
5179  * dirtiness (it may still be data-dirty).
5180  * This means that the in-core inode may be reaped by prune_icache
5181  * without having to perform any I/O.  This is a very good thing,
5182  * because *any* task may call prune_icache - even ones which
5183  * have a transaction open against a different journal.
5184  *
5185  * Is this cheating?  Not really.  Sure, we haven't written the
5186  * inode out, but prune_icache isn't a user-visible syncing function.
5187  * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5188  * we start and wait on commits.
5189  */
5190 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
5191 {
5192         struct ext4_iloc iloc;
5193         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5194         static unsigned int mnt_count;
5195         int err, ret;
5196
5197         might_sleep();
5198         trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5199         err = ext4_reserve_inode_write(handle, inode, &iloc);
5200         if (err)
5201                 return err;
5202         if (ext4_handle_valid(handle) &&
5203             EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
5204             !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5205                 /*
5206                  * We need extra buffer credits since we may write into EA block
5207                  * with this same handle. If journal_extend fails, then it will
5208                  * only result in a minor loss of functionality for that inode.
5209                  * If this is felt to be critical, then e2fsck should be run to
5210                  * force a large enough s_min_extra_isize.
5211                  */
5212                 if ((jbd2_journal_extend(handle,
5213                              EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
5214                         ret = ext4_expand_extra_isize(inode,
5215                                                       sbi->s_want_extra_isize,
5216                                                       iloc, handle);
5217                         if (ret) {
5218                                 if (mnt_count !=
5219                                         le16_to_cpu(sbi->s_es->s_mnt_count)) {
5220                                         ext4_warning(inode->i_sb,
5221                                         "Unable to expand inode %lu. Delete"
5222                                         " some EAs or run e2fsck.",
5223                                         inode->i_ino);
5224                                         mnt_count =
5225                                           le16_to_cpu(sbi->s_es->s_mnt_count);
5226                                 }
5227                         }
5228                 }
5229         }
5230         return ext4_mark_iloc_dirty(handle, inode, &iloc);
5231 }
5232
5233 /*
5234  * ext4_dirty_inode() is called from __mark_inode_dirty()
5235  *
5236  * We're really interested in the case where a file is being extended.
5237  * i_size has been changed by generic_commit_write() and we thus need
5238  * to include the updated inode in the current transaction.
5239  *
5240  * Also, dquot_alloc_block() will always dirty the inode when blocks
5241  * are allocated to the file.
5242  *
5243  * If the inode is marked synchronous, we don't honour that here - doing
5244  * so would cause a commit on atime updates, which we don't bother doing.
5245  * We handle synchronous inodes at the highest possible level.
5246  *
5247  * If only the I_DIRTY_TIME flag is set, we can skip everything.  If
5248  * I_DIRTY_TIME and I_DIRTY_SYNC is set, the only inode fields we need
5249  * to copy into the on-disk inode structure are the timestamp files.
5250  */
5251 void ext4_dirty_inode(struct inode *inode, int flags)
5252 {
5253         handle_t *handle;
5254
5255         if (flags == I_DIRTY_TIME)
5256                 return;
5257         handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
5258         if (IS_ERR(handle))
5259                 goto out;
5260
5261         ext4_mark_inode_dirty(handle, inode);
5262
5263         ext4_journal_stop(handle);
5264 out:
5265         return;
5266 }
5267
5268 #if 0
5269 /*
5270  * Bind an inode's backing buffer_head into this transaction, to prevent
5271  * it from being flushed to disk early.  Unlike
5272  * ext4_reserve_inode_write, this leaves behind no bh reference and
5273  * returns no iloc structure, so the caller needs to repeat the iloc
5274  * lookup to mark the inode dirty later.
5275  */
5276 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
5277 {
5278         struct ext4_iloc iloc;
5279
5280         int err = 0;
5281         if (handle) {
5282                 err = ext4_get_inode_loc(inode, &iloc);
5283                 if (!err) {
5284                         BUFFER_TRACE(iloc.bh, "get_write_access");
5285                         err = jbd2_journal_get_write_access(handle, iloc.bh);
5286                         if (!err)
5287                                 err = ext4_handle_dirty_metadata(handle,
5288                                                                  NULL,
5289                                                                  iloc.bh);
5290                         brelse(iloc.bh);
5291                 }
5292         }
5293         ext4_std_error(inode->i_sb, err);
5294         return err;
5295 }
5296 #endif
5297
5298 int ext4_change_inode_journal_flag(struct inode *inode, int val)
5299 {
5300         journal_t *journal;
5301         handle_t *handle;
5302         int err;
5303
5304         /*
5305          * We have to be very careful here: changing a data block's
5306          * journaling status dynamically is dangerous.  If we write a
5307          * data block to the journal, change the status and then delete
5308          * that block, we risk forgetting to revoke the old log record
5309          * from the journal and so a subsequent replay can corrupt data.
5310          * So, first we make sure that the journal is empty and that
5311          * nobody is changing anything.
5312          */
5313
5314         journal = EXT4_JOURNAL(inode);
5315         if (!journal)
5316                 return 0;
5317         if (is_journal_aborted(journal))
5318                 return -EROFS;
5319         /* We have to allocate physical blocks for delalloc blocks
5320          * before flushing journal. otherwise delalloc blocks can not
5321          * be allocated any more. even more truncate on delalloc blocks
5322          * could trigger BUG by flushing delalloc blocks in journal.
5323          * There is no delalloc block in non-journal data mode.
5324          */
5325         if (val && test_opt(inode->i_sb, DELALLOC)) {
5326                 err = ext4_alloc_da_blocks(inode);
5327                 if (err < 0)
5328                         return err;
5329         }
5330
5331         /* Wait for all existing dio workers */
5332         ext4_inode_block_unlocked_dio(inode);
5333         inode_dio_wait(inode);
5334
5335         jbd2_journal_lock_updates(journal);
5336
5337         /*
5338          * OK, there are no updates running now, and all cached data is
5339          * synced to disk.  We are now in a completely consistent state
5340          * which doesn't have anything in the journal, and we know that
5341          * no filesystem updates are running, so it is safe to modify
5342          * the inode's in-core data-journaling state flag now.
5343          */
5344
5345         if (val)
5346                 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5347         else {
5348                 err = jbd2_journal_flush(journal);
5349                 if (err < 0) {
5350                         jbd2_journal_unlock_updates(journal);
5351                         ext4_inode_resume_unlocked_dio(inode);
5352                         return err;
5353                 }
5354                 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5355         }
5356         ext4_set_aops(inode);
5357
5358         jbd2_journal_unlock_updates(journal);
5359         ext4_inode_resume_unlocked_dio(inode);
5360
5361         /* Finally we can mark the inode as dirty. */
5362
5363         handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
5364         if (IS_ERR(handle))
5365                 return PTR_ERR(handle);
5366
5367         err = ext4_mark_inode_dirty(handle, inode);
5368         ext4_handle_sync(handle);
5369         ext4_journal_stop(handle);
5370         ext4_std_error(inode->i_sb, err);
5371
5372         return err;
5373 }
5374
5375 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
5376 {
5377         return !buffer_mapped(bh);
5378 }
5379
5380 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
5381 {
5382         struct page *page = vmf->page;
5383         loff_t size;
5384         unsigned long len;
5385         int ret;
5386         struct file *file = vma->vm_file;
5387         struct inode *inode = file_inode(file);
5388         struct address_space *mapping = inode->i_mapping;
5389         handle_t *handle;
5390         get_block_t *get_block;
5391         int retries = 0;
5392
5393         sb_start_pagefault(inode->i_sb);
5394         file_update_time(vma->vm_file);
5395
5396         down_read(&EXT4_I(inode)->i_mmap_sem);
5397         /* Delalloc case is easy... */
5398         if (test_opt(inode->i_sb, DELALLOC) &&
5399             !ext4_should_journal_data(inode) &&
5400             !ext4_nonda_switch(inode->i_sb)) {
5401                 do {
5402                         ret = block_page_mkwrite(vma, vmf,
5403                                                    ext4_da_get_block_prep);
5404                 } while (ret == -ENOSPC &&
5405                        ext4_should_retry_alloc(inode->i_sb, &retries));
5406                 goto out_ret;
5407         }
5408
5409         lock_page(page);
5410         size = i_size_read(inode);
5411         /* Page got truncated from under us? */
5412         if (page->mapping != mapping || page_offset(page) > size) {
5413                 unlock_page(page);
5414                 ret = VM_FAULT_NOPAGE;
5415                 goto out;
5416         }
5417
5418         if (page->index == size >> PAGE_CACHE_SHIFT)
5419                 len = size & ~PAGE_CACHE_MASK;
5420         else
5421                 len = PAGE_CACHE_SIZE;
5422         /*
5423          * Return if we have all the buffers mapped. This avoids the need to do
5424          * journal_start/journal_stop which can block and take a long time
5425          */
5426         if (page_has_buffers(page)) {
5427                 if (!ext4_walk_page_buffers(NULL, page_buffers(page),
5428                                             0, len, NULL,
5429                                             ext4_bh_unmapped)) {
5430                         /* Wait so that we don't change page under IO */
5431                         wait_for_stable_page(page);
5432                         ret = VM_FAULT_LOCKED;
5433                         goto out;
5434                 }
5435         }
5436         unlock_page(page);
5437         /* OK, we need to fill the hole... */
5438         if (ext4_should_dioread_nolock(inode))
5439                 get_block = ext4_get_block_write;
5440         else
5441                 get_block = ext4_get_block;
5442 retry_alloc:
5443         handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
5444                                     ext4_writepage_trans_blocks(inode));
5445         if (IS_ERR(handle)) {
5446                 ret = VM_FAULT_SIGBUS;
5447                 goto out;
5448         }
5449         ret = block_page_mkwrite(vma, vmf, get_block);
5450         if (!ret && ext4_should_journal_data(inode)) {
5451                 if (ext4_walk_page_buffers(handle, page_buffers(page), 0,
5452                           PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) {
5453                         unlock_page(page);
5454                         ret = VM_FAULT_SIGBUS;
5455                         ext4_journal_stop(handle);
5456                         goto out;
5457                 }
5458                 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
5459         }
5460         ext4_journal_stop(handle);
5461         if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
5462                 goto retry_alloc;
5463 out_ret:
5464         ret = block_page_mkwrite_return(ret);
5465 out:
5466         up_read(&EXT4_I(inode)->i_mmap_sem);
5467         sb_end_pagefault(inode->i_sb);
5468         return ret;
5469 }
5470
5471 int ext4_filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
5472 {
5473         struct inode *inode = file_inode(vma->vm_file);
5474         int err;
5475
5476         down_read(&EXT4_I(inode)->i_mmap_sem);
5477         err = filemap_fault(vma, vmf);
5478         up_read(&EXT4_I(inode)->i_mmap_sem);
5479
5480         return err;
5481 }