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