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