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