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