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