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