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