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