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