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