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