fs: Add helper to clean bdev aliases under a bh and use it
[sfrench/cifs-2.6.git] / fs / ext4 / inode.c
1 /*
2  *  linux/fs/ext4/inode.c
3  *
4  * Copyright (C) 1992, 1993, 1994, 1995
5  * Remy Card (card@masi.ibp.fr)
6  * Laboratoire MASI - Institut Blaise Pascal
7  * Universite Pierre et Marie Curie (Paris VI)
8  *
9  *  from
10  *
11  *  linux/fs/minix/inode.c
12  *
13  *  Copyright (C) 1991, 1992  Linus Torvalds
14  *
15  *  64-bit file support on 64-bit platforms by Jakub Jelinek
16  *      (jj@sunsite.ms.mff.cuni.cz)
17  *
18  *  Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
19  */
20
21 #include <linux/fs.h>
22 #include <linux/time.h>
23 #include <linux/highuid.h>
24 #include <linux/pagemap.h>
25 #include <linux/dax.h>
26 #include <linux/quotaops.h>
27 #include <linux/string.h>
28 #include <linux/buffer_head.h>
29 #include <linux/writeback.h>
30 #include <linux/pagevec.h>
31 #include <linux/mpage.h>
32 #include <linux/namei.h>
33 #include <linux/uio.h>
34 #include <linux/bio.h>
35 #include <linux/workqueue.h>
36 #include <linux/kernel.h>
37 #include <linux/printk.h>
38 #include <linux/slab.h>
39 #include <linux/bitops.h>
40
41 #include "ext4_jbd2.h"
42 #include "xattr.h"
43 #include "acl.h"
44 #include "truncate.h"
45
46 #include <trace/events/ext4.h>
47
48 #define MPAGE_DA_EXTENT_TAIL 0x01
49
50 static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
51                               struct ext4_inode_info *ei)
52 {
53         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
54         __u32 csum;
55         __u16 dummy_csum = 0;
56         int offset = offsetof(struct ext4_inode, i_checksum_lo);
57         unsigned int csum_size = sizeof(dummy_csum);
58
59         csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw, offset);
60         csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, csum_size);
61         offset += csum_size;
62         csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
63                            EXT4_GOOD_OLD_INODE_SIZE - offset);
64
65         if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
66                 offset = offsetof(struct ext4_inode, i_checksum_hi);
67                 csum = ext4_chksum(sbi, csum, (__u8 *)raw +
68                                    EXT4_GOOD_OLD_INODE_SIZE,
69                                    offset - EXT4_GOOD_OLD_INODE_SIZE);
70                 if (EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
71                         csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum,
72                                            csum_size);
73                         offset += csum_size;
74                         csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
75                                            EXT4_INODE_SIZE(inode->i_sb) -
76                                            offset);
77                 }
78         }
79
80         return csum;
81 }
82
83 static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
84                                   struct ext4_inode_info *ei)
85 {
86         __u32 provided, calculated;
87
88         if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
89             cpu_to_le32(EXT4_OS_LINUX) ||
90             !ext4_has_metadata_csum(inode->i_sb))
91                 return 1;
92
93         provided = le16_to_cpu(raw->i_checksum_lo);
94         calculated = ext4_inode_csum(inode, raw, ei);
95         if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
96             EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
97                 provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
98         else
99                 calculated &= 0xFFFF;
100
101         return provided == calculated;
102 }
103
104 static void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
105                                 struct ext4_inode_info *ei)
106 {
107         __u32 csum;
108
109         if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
110             cpu_to_le32(EXT4_OS_LINUX) ||
111             !ext4_has_metadata_csum(inode->i_sb))
112                 return;
113
114         csum = ext4_inode_csum(inode, raw, ei);
115         raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
116         if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
117             EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
118                 raw->i_checksum_hi = cpu_to_le16(csum >> 16);
119 }
120
121 static inline int ext4_begin_ordered_truncate(struct inode *inode,
122                                               loff_t new_size)
123 {
124         trace_ext4_begin_ordered_truncate(inode, new_size);
125         /*
126          * If jinode is zero, then we never opened the file for
127          * writing, so there's no need to call
128          * jbd2_journal_begin_ordered_truncate() since there's no
129          * outstanding writes we need to flush.
130          */
131         if (!EXT4_I(inode)->jinode)
132                 return 0;
133         return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
134                                                    EXT4_I(inode)->jinode,
135                                                    new_size);
136 }
137
138 static void ext4_invalidatepage(struct page *page, unsigned int offset,
139                                 unsigned int length);
140 static int __ext4_journalled_writepage(struct page *page, unsigned int len);
141 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
142 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
143                                   int pextents);
144
145 /*
146  * Test whether an inode is a fast symlink.
147  */
148 int ext4_inode_is_fast_symlink(struct inode *inode)
149 {
150         int ea_blocks = EXT4_I(inode)->i_file_acl ?
151                 EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
152
153         if (ext4_has_inline_data(inode))
154                 return 0;
155
156         return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
157 }
158
159 /*
160  * Restart the transaction associated with *handle.  This does a commit,
161  * so before we call here everything must be consistently dirtied against
162  * this transaction.
163  */
164 int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
165                                  int nblocks)
166 {
167         int ret;
168
169         /*
170          * Drop i_data_sem to avoid deadlock with ext4_map_blocks.  At this
171          * moment, get_block can be called only for blocks inside i_size since
172          * page cache has been already dropped and writes are blocked by
173          * i_mutex. So we can safely drop the i_data_sem here.
174          */
175         BUG_ON(EXT4_JOURNAL(inode) == NULL);
176         jbd_debug(2, "restarting handle %p\n", handle);
177         up_write(&EXT4_I(inode)->i_data_sem);
178         ret = ext4_journal_restart(handle, nblocks);
179         down_write(&EXT4_I(inode)->i_data_sem);
180         ext4_discard_preallocations(inode);
181
182         return ret;
183 }
184
185 /*
186  * Called at the last iput() if i_nlink is zero.
187  */
188 void ext4_evict_inode(struct inode *inode)
189 {
190         handle_t *handle;
191         int err;
192
193         trace_ext4_evict_inode(inode);
194
195         if (inode->i_nlink) {
196                 /*
197                  * When journalling data dirty buffers are tracked only in the
198                  * journal. So although mm thinks everything is clean and
199                  * ready for reaping the inode might still have some pages to
200                  * write in the running transaction or waiting to be
201                  * checkpointed. Thus calling jbd2_journal_invalidatepage()
202                  * (via truncate_inode_pages()) to discard these buffers can
203                  * cause data loss. Also even if we did not discard these
204                  * buffers, we would have no way to find them after the inode
205                  * is reaped and thus user could see stale data if he tries to
206                  * read them before the transaction is checkpointed. So be
207                  * careful and force everything to disk here... We use
208                  * ei->i_datasync_tid to store the newest transaction
209                  * containing inode's data.
210                  *
211                  * Note that directories do not have this problem because they
212                  * don't use page cache.
213                  */
214                 if (inode->i_ino != EXT4_JOURNAL_INO &&
215                     ext4_should_journal_data(inode) &&
216                     (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode))) {
217                         journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
218                         tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
219
220                         jbd2_complete_transaction(journal, commit_tid);
221                         filemap_write_and_wait(&inode->i_data);
222                 }
223                 truncate_inode_pages_final(&inode->i_data);
224
225                 goto no_delete;
226         }
227
228         if (is_bad_inode(inode))
229                 goto no_delete;
230         dquot_initialize(inode);
231
232         if (ext4_should_order_data(inode))
233                 ext4_begin_ordered_truncate(inode, 0);
234         truncate_inode_pages_final(&inode->i_data);
235
236         /*
237          * Protect us against freezing - iput() caller didn't have to have any
238          * protection against it
239          */
240         sb_start_intwrite(inode->i_sb);
241         handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
242                                     ext4_blocks_for_truncate(inode)+3);
243         if (IS_ERR(handle)) {
244                 ext4_std_error(inode->i_sb, PTR_ERR(handle));
245                 /*
246                  * If we're going to skip the normal cleanup, we still need to
247                  * make sure that the in-core orphan linked list is properly
248                  * cleaned up.
249                  */
250                 ext4_orphan_del(NULL, inode);
251                 sb_end_intwrite(inode->i_sb);
252                 goto no_delete;
253         }
254
255         if (IS_SYNC(inode))
256                 ext4_handle_sync(handle);
257         inode->i_size = 0;
258         err = ext4_mark_inode_dirty(handle, inode);
259         if (err) {
260                 ext4_warning(inode->i_sb,
261                              "couldn't mark inode dirty (err %d)", err);
262                 goto stop_handle;
263         }
264         if (inode->i_blocks)
265                 ext4_truncate(inode);
266
267         /*
268          * ext4_ext_truncate() doesn't reserve any slop when it
269          * restarts journal transactions; therefore there may not be
270          * enough credits left in the handle to remove the inode from
271          * the orphan list and set the dtime field.
272          */
273         if (!ext4_handle_has_enough_credits(handle, 3)) {
274                 err = ext4_journal_extend(handle, 3);
275                 if (err > 0)
276                         err = ext4_journal_restart(handle, 3);
277                 if (err != 0) {
278                         ext4_warning(inode->i_sb,
279                                      "couldn't extend journal (err %d)", err);
280                 stop_handle:
281                         ext4_journal_stop(handle);
282                         ext4_orphan_del(NULL, inode);
283                         sb_end_intwrite(inode->i_sb);
284                         goto no_delete;
285                 }
286         }
287
288         /*
289          * Kill off the orphan record which ext4_truncate created.
290          * AKPM: I think this can be inside the above `if'.
291          * Note that ext4_orphan_del() has to be able to cope with the
292          * deletion of a non-existent orphan - this is because we don't
293          * know if ext4_truncate() actually created an orphan record.
294          * (Well, we could do this if we need to, but heck - it works)
295          */
296         ext4_orphan_del(handle, inode);
297         EXT4_I(inode)->i_dtime  = get_seconds();
298
299         /*
300          * One subtle ordering requirement: if anything has gone wrong
301          * (transaction abort, IO errors, whatever), then we can still
302          * do these next steps (the fs will already have been marked as
303          * having errors), but we can't free the inode if the mark_dirty
304          * fails.
305          */
306         if (ext4_mark_inode_dirty(handle, inode))
307                 /* If that failed, just do the required in-core inode clear. */
308                 ext4_clear_inode(inode);
309         else
310                 ext4_free_inode(handle, inode);
311         ext4_journal_stop(handle);
312         sb_end_intwrite(inode->i_sb);
313         return;
314 no_delete:
315         ext4_clear_inode(inode);        /* We must guarantee clearing of inode... */
316 }
317
318 #ifdef CONFIG_QUOTA
319 qsize_t *ext4_get_reserved_space(struct inode *inode)
320 {
321         return &EXT4_I(inode)->i_reserved_quota;
322 }
323 #endif
324
325 /*
326  * Called with i_data_sem down, which is important since we can call
327  * ext4_discard_preallocations() from here.
328  */
329 void ext4_da_update_reserve_space(struct inode *inode,
330                                         int used, int quota_claim)
331 {
332         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
333         struct ext4_inode_info *ei = EXT4_I(inode);
334
335         spin_lock(&ei->i_block_reservation_lock);
336         trace_ext4_da_update_reserve_space(inode, used, quota_claim);
337         if (unlikely(used > ei->i_reserved_data_blocks)) {
338                 ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
339                          "with only %d reserved data blocks",
340                          __func__, inode->i_ino, used,
341                          ei->i_reserved_data_blocks);
342                 WARN_ON(1);
343                 used = ei->i_reserved_data_blocks;
344         }
345
346         /* Update per-inode reservations */
347         ei->i_reserved_data_blocks -= used;
348         percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
349
350         spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
351
352         /* Update quota subsystem for data blocks */
353         if (quota_claim)
354                 dquot_claim_block(inode, EXT4_C2B(sbi, used));
355         else {
356                 /*
357                  * We did fallocate with an offset that is already delayed
358                  * allocated. So on delayed allocated writeback we should
359                  * not re-claim the quota for fallocated blocks.
360                  */
361                 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
362         }
363
364         /*
365          * If we have done all the pending block allocations and if
366          * there aren't any writers on the inode, we can discard the
367          * inode's preallocations.
368          */
369         if ((ei->i_reserved_data_blocks == 0) &&
370             (atomic_read(&inode->i_writecount) == 0))
371                 ext4_discard_preallocations(inode);
372 }
373
374 static int __check_block_validity(struct inode *inode, const char *func,
375                                 unsigned int line,
376                                 struct ext4_map_blocks *map)
377 {
378         if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
379                                    map->m_len)) {
380                 ext4_error_inode(inode, func, line, map->m_pblk,
381                                  "lblock %lu mapped to illegal pblock "
382                                  "(length %d)", (unsigned long) map->m_lblk,
383                                  map->m_len);
384                 return -EFSCORRUPTED;
385         }
386         return 0;
387 }
388
389 int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
390                        ext4_lblk_t len)
391 {
392         int ret;
393
394         if (ext4_encrypted_inode(inode))
395                 return fscrypt_zeroout_range(inode, lblk, pblk, len);
396
397         ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
398         if (ret > 0)
399                 ret = 0;
400
401         return ret;
402 }
403
404 #define check_block_validity(inode, map)        \
405         __check_block_validity((inode), __func__, __LINE__, (map))
406
407 #ifdef ES_AGGRESSIVE_TEST
408 static void ext4_map_blocks_es_recheck(handle_t *handle,
409                                        struct inode *inode,
410                                        struct ext4_map_blocks *es_map,
411                                        struct ext4_map_blocks *map,
412                                        int flags)
413 {
414         int retval;
415
416         map->m_flags = 0;
417         /*
418          * There is a race window that the result is not the same.
419          * e.g. xfstests #223 when dioread_nolock enables.  The reason
420          * is that we lookup a block mapping in extent status tree with
421          * out taking i_data_sem.  So at the time the unwritten extent
422          * could be converted.
423          */
424         down_read(&EXT4_I(inode)->i_data_sem);
425         if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
426                 retval = ext4_ext_map_blocks(handle, inode, map, flags &
427                                              EXT4_GET_BLOCKS_KEEP_SIZE);
428         } else {
429                 retval = ext4_ind_map_blocks(handle, inode, map, flags &
430                                              EXT4_GET_BLOCKS_KEEP_SIZE);
431         }
432         up_read((&EXT4_I(inode)->i_data_sem));
433
434         /*
435          * We don't check m_len because extent will be collpased in status
436          * tree.  So the m_len might not equal.
437          */
438         if (es_map->m_lblk != map->m_lblk ||
439             es_map->m_flags != map->m_flags ||
440             es_map->m_pblk != map->m_pblk) {
441                 printk("ES cache assertion failed for inode: %lu "
442                        "es_cached ex [%d/%d/%llu/%x] != "
443                        "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
444                        inode->i_ino, es_map->m_lblk, es_map->m_len,
445                        es_map->m_pblk, es_map->m_flags, map->m_lblk,
446                        map->m_len, map->m_pblk, map->m_flags,
447                        retval, flags);
448         }
449 }
450 #endif /* ES_AGGRESSIVE_TEST */
451
452 /*
453  * The ext4_map_blocks() function tries to look up the requested blocks,
454  * and returns if the blocks are already mapped.
455  *
456  * Otherwise it takes the write lock of the i_data_sem and allocate blocks
457  * and store the allocated blocks in the result buffer head and mark it
458  * mapped.
459  *
460  * If file type is extents based, it will call ext4_ext_map_blocks(),
461  * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
462  * based files
463  *
464  * On success, it returns the number of blocks being mapped or allocated.  if
465  * create==0 and the blocks are pre-allocated and unwritten, the resulting @map
466  * is marked as unwritten. If the create == 1, it will mark @map as mapped.
467  *
468  * It returns 0 if plain look up failed (blocks have not been allocated), in
469  * that case, @map is returned as unmapped but we still do fill map->m_len to
470  * indicate the length of a hole starting at map->m_lblk.
471  *
472  * It returns the error in case of allocation failure.
473  */
474 int ext4_map_blocks(handle_t *handle, struct inode *inode,
475                     struct ext4_map_blocks *map, int flags)
476 {
477         struct extent_status es;
478         int retval;
479         int ret = 0;
480 #ifdef ES_AGGRESSIVE_TEST
481         struct ext4_map_blocks orig_map;
482
483         memcpy(&orig_map, map, sizeof(*map));
484 #endif
485
486         map->m_flags = 0;
487         ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
488                   "logical block %lu\n", inode->i_ino, flags, map->m_len,
489                   (unsigned long) map->m_lblk);
490
491         /*
492          * ext4_map_blocks returns an int, and m_len is an unsigned int
493          */
494         if (unlikely(map->m_len > INT_MAX))
495                 map->m_len = INT_MAX;
496
497         /* We can handle the block number less than EXT_MAX_BLOCKS */
498         if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
499                 return -EFSCORRUPTED;
500
501         /* Lookup extent status tree firstly */
502         if (ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
503                 if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
504                         map->m_pblk = ext4_es_pblock(&es) +
505                                         map->m_lblk - es.es_lblk;
506                         map->m_flags |= ext4_es_is_written(&es) ?
507                                         EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
508                         retval = es.es_len - (map->m_lblk - es.es_lblk);
509                         if (retval > map->m_len)
510                                 retval = map->m_len;
511                         map->m_len = retval;
512                 } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
513                         map->m_pblk = 0;
514                         retval = es.es_len - (map->m_lblk - es.es_lblk);
515                         if (retval > map->m_len)
516                                 retval = map->m_len;
517                         map->m_len = retval;
518                         retval = 0;
519                 } else {
520                         BUG_ON(1);
521                 }
522 #ifdef ES_AGGRESSIVE_TEST
523                 ext4_map_blocks_es_recheck(handle, inode, map,
524                                            &orig_map, flags);
525 #endif
526                 goto found;
527         }
528
529         /*
530          * Try to see if we can get the block without requesting a new
531          * file system block.
532          */
533         down_read(&EXT4_I(inode)->i_data_sem);
534         if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
535                 retval = ext4_ext_map_blocks(handle, inode, map, flags &
536                                              EXT4_GET_BLOCKS_KEEP_SIZE);
537         } else {
538                 retval = ext4_ind_map_blocks(handle, inode, map, flags &
539                                              EXT4_GET_BLOCKS_KEEP_SIZE);
540         }
541         if (retval > 0) {
542                 unsigned int status;
543
544                 if (unlikely(retval != map->m_len)) {
545                         ext4_warning(inode->i_sb,
546                                      "ES len assertion failed for inode "
547                                      "%lu: retval %d != map->m_len %d",
548                                      inode->i_ino, retval, map->m_len);
549                         WARN_ON(1);
550                 }
551
552                 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
553                                 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
554                 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
555                     !(status & EXTENT_STATUS_WRITTEN) &&
556                     ext4_find_delalloc_range(inode, map->m_lblk,
557                                              map->m_lblk + map->m_len - 1))
558                         status |= EXTENT_STATUS_DELAYED;
559                 ret = ext4_es_insert_extent(inode, map->m_lblk,
560                                             map->m_len, map->m_pblk, status);
561                 if (ret < 0)
562                         retval = ret;
563         }
564         up_read((&EXT4_I(inode)->i_data_sem));
565
566 found:
567         if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
568                 ret = check_block_validity(inode, map);
569                 if (ret != 0)
570                         return ret;
571         }
572
573         /* If it is only a block(s) look up */
574         if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
575                 return retval;
576
577         /*
578          * Returns if the blocks have already allocated
579          *
580          * Note that if blocks have been preallocated
581          * ext4_ext_get_block() returns the create = 0
582          * with buffer head unmapped.
583          */
584         if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
585                 /*
586                  * If we need to convert extent to unwritten
587                  * we continue and do the actual work in
588                  * ext4_ext_map_blocks()
589                  */
590                 if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
591                         return retval;
592
593         /*
594          * Here we clear m_flags because after allocating an new extent,
595          * it will be set again.
596          */
597         map->m_flags &= ~EXT4_MAP_FLAGS;
598
599         /*
600          * New blocks allocate and/or writing to unwritten extent
601          * will possibly result in updating i_data, so we take
602          * the write lock of i_data_sem, and call get_block()
603          * with create == 1 flag.
604          */
605         down_write(&EXT4_I(inode)->i_data_sem);
606
607         /*
608          * We need to check for EXT4 here because migrate
609          * could have changed the inode type in between
610          */
611         if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
612                 retval = ext4_ext_map_blocks(handle, inode, map, flags);
613         } else {
614                 retval = ext4_ind_map_blocks(handle, inode, map, flags);
615
616                 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
617                         /*
618                          * We allocated new blocks which will result in
619                          * i_data's format changing.  Force the migrate
620                          * to fail by clearing migrate flags
621                          */
622                         ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
623                 }
624
625                 /*
626                  * Update reserved blocks/metadata blocks after successful
627                  * block allocation which had been deferred till now. We don't
628                  * support fallocate for non extent files. So we can update
629                  * reserve space here.
630                  */
631                 if ((retval > 0) &&
632                         (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
633                         ext4_da_update_reserve_space(inode, retval, 1);
634         }
635
636         if (retval > 0) {
637                 unsigned int status;
638
639                 if (unlikely(retval != map->m_len)) {
640                         ext4_warning(inode->i_sb,
641                                      "ES len assertion failed for inode "
642                                      "%lu: retval %d != map->m_len %d",
643                                      inode->i_ino, retval, map->m_len);
644                         WARN_ON(1);
645                 }
646
647                 /*
648                  * We have to zeroout blocks before inserting them into extent
649                  * status tree. Otherwise someone could look them up there and
650                  * use them before they are really zeroed. We also have to
651                  * unmap metadata before zeroing as otherwise writeback can
652                  * overwrite zeros with stale data from block device.
653                  */
654                 if (flags & EXT4_GET_BLOCKS_ZERO &&
655                     map->m_flags & EXT4_MAP_MAPPED &&
656                     map->m_flags & EXT4_MAP_NEW) {
657                         clean_bdev_aliases(inode->i_sb->s_bdev, map->m_pblk,
658                                            map->m_len);
659                         ret = ext4_issue_zeroout(inode, map->m_lblk,
660                                                  map->m_pblk, map->m_len);
661                         if (ret) {
662                                 retval = ret;
663                                 goto out_sem;
664                         }
665                 }
666
667                 /*
668                  * If the extent has been zeroed out, we don't need to update
669                  * extent status tree.
670                  */
671                 if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
672                     ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
673                         if (ext4_es_is_written(&es))
674                                 goto out_sem;
675                 }
676                 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
677                                 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
678                 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
679                     !(status & EXTENT_STATUS_WRITTEN) &&
680                     ext4_find_delalloc_range(inode, map->m_lblk,
681                                              map->m_lblk + map->m_len - 1))
682                         status |= EXTENT_STATUS_DELAYED;
683                 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
684                                             map->m_pblk, status);
685                 if (ret < 0) {
686                         retval = ret;
687                         goto out_sem;
688                 }
689         }
690
691 out_sem:
692         up_write((&EXT4_I(inode)->i_data_sem));
693         if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
694                 ret = check_block_validity(inode, map);
695                 if (ret != 0)
696                         return ret;
697
698                 /*
699                  * Inodes with freshly allocated blocks where contents will be
700                  * visible after transaction commit must be on transaction's
701                  * ordered data list.
702                  */
703                 if (map->m_flags & EXT4_MAP_NEW &&
704                     !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
705                     !(flags & EXT4_GET_BLOCKS_ZERO) &&
706                     !IS_NOQUOTA(inode) &&
707                     ext4_should_order_data(inode)) {
708                         if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
709                                 ret = ext4_jbd2_inode_add_wait(handle, inode);
710                         else
711                                 ret = ext4_jbd2_inode_add_write(handle, inode);
712                         if (ret)
713                                 return ret;
714                 }
715         }
716         return retval;
717 }
718
719 /*
720  * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
721  * we have to be careful as someone else may be manipulating b_state as well.
722  */
723 static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
724 {
725         unsigned long old_state;
726         unsigned long new_state;
727
728         flags &= EXT4_MAP_FLAGS;
729
730         /* Dummy buffer_head? Set non-atomically. */
731         if (!bh->b_page) {
732                 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
733                 return;
734         }
735         /*
736          * Someone else may be modifying b_state. Be careful! This is ugly but
737          * once we get rid of using bh as a container for mapping information
738          * to pass to / from get_block functions, this can go away.
739          */
740         do {
741                 old_state = READ_ONCE(bh->b_state);
742                 new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
743         } while (unlikely(
744                  cmpxchg(&bh->b_state, old_state, new_state) != old_state));
745 }
746
747 static int _ext4_get_block(struct inode *inode, sector_t iblock,
748                            struct buffer_head *bh, int flags)
749 {
750         struct ext4_map_blocks map;
751         int ret = 0;
752
753         if (ext4_has_inline_data(inode))
754                 return -ERANGE;
755
756         map.m_lblk = iblock;
757         map.m_len = bh->b_size >> inode->i_blkbits;
758
759         ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
760                               flags);
761         if (ret > 0) {
762                 map_bh(bh, inode->i_sb, map.m_pblk);
763                 ext4_update_bh_state(bh, map.m_flags);
764                 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
765                 ret = 0;
766         }
767         return ret;
768 }
769
770 int ext4_get_block(struct inode *inode, sector_t iblock,
771                    struct buffer_head *bh, int create)
772 {
773         return _ext4_get_block(inode, iblock, bh,
774                                create ? EXT4_GET_BLOCKS_CREATE : 0);
775 }
776
777 /*
778  * Get block function used when preparing for buffered write if we require
779  * creating an unwritten extent if blocks haven't been allocated.  The extent
780  * will be converted to written after the IO is complete.
781  */
782 int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
783                              struct buffer_head *bh_result, int create)
784 {
785         ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
786                    inode->i_ino, create);
787         return _ext4_get_block(inode, iblock, bh_result,
788                                EXT4_GET_BLOCKS_IO_CREATE_EXT);
789 }
790
791 /* Maximum number of blocks we map for direct IO at once. */
792 #define DIO_MAX_BLOCKS 4096
793
794 /*
795  * Get blocks function for the cases that need to start a transaction -
796  * generally difference cases of direct IO and DAX IO. It also handles retries
797  * in case of ENOSPC.
798  */
799 static int ext4_get_block_trans(struct inode *inode, sector_t iblock,
800                                 struct buffer_head *bh_result, int flags)
801 {
802         int dio_credits;
803         handle_t *handle;
804         int retries = 0;
805         int ret;
806
807         /* Trim mapping request to maximum we can map at once for DIO */
808         if (bh_result->b_size >> inode->i_blkbits > DIO_MAX_BLOCKS)
809                 bh_result->b_size = DIO_MAX_BLOCKS << inode->i_blkbits;
810         dio_credits = ext4_chunk_trans_blocks(inode,
811                                       bh_result->b_size >> inode->i_blkbits);
812 retry:
813         handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
814         if (IS_ERR(handle))
815                 return PTR_ERR(handle);
816
817         ret = _ext4_get_block(inode, iblock, bh_result, flags);
818         ext4_journal_stop(handle);
819
820         if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
821                 goto retry;
822         return ret;
823 }
824
825 /* Get block function for DIO reads and writes to inodes without extents */
826 int ext4_dio_get_block(struct inode *inode, sector_t iblock,
827                        struct buffer_head *bh, int create)
828 {
829         /* We don't expect handle for direct IO */
830         WARN_ON_ONCE(ext4_journal_current_handle());
831
832         if (!create)
833                 return _ext4_get_block(inode, iblock, bh, 0);
834         return ext4_get_block_trans(inode, iblock, bh, EXT4_GET_BLOCKS_CREATE);
835 }
836
837 /*
838  * Get block function for AIO DIO writes when we create unwritten extent if
839  * blocks are not allocated yet. The extent will be converted to written
840  * after IO is complete.
841  */
842 static int ext4_dio_get_block_unwritten_async(struct inode *inode,
843                 sector_t iblock, struct buffer_head *bh_result, int create)
844 {
845         int ret;
846
847         /* We don't expect handle for direct IO */
848         WARN_ON_ONCE(ext4_journal_current_handle());
849
850         ret = ext4_get_block_trans(inode, iblock, bh_result,
851                                    EXT4_GET_BLOCKS_IO_CREATE_EXT);
852
853         /*
854          * When doing DIO using unwritten extents, we need io_end to convert
855          * unwritten extents to written on IO completion. We allocate io_end
856          * once we spot unwritten extent and store it in b_private. Generic
857          * DIO code keeps b_private set and furthermore passes the value to
858          * our completion callback in 'private' argument.
859          */
860         if (!ret && buffer_unwritten(bh_result)) {
861                 if (!bh_result->b_private) {
862                         ext4_io_end_t *io_end;
863
864                         io_end = ext4_init_io_end(inode, GFP_KERNEL);
865                         if (!io_end)
866                                 return -ENOMEM;
867                         bh_result->b_private = io_end;
868                         ext4_set_io_unwritten_flag(inode, io_end);
869                 }
870                 set_buffer_defer_completion(bh_result);
871         }
872
873         return ret;
874 }
875
876 /*
877  * Get block function for non-AIO DIO writes when we create unwritten extent if
878  * blocks are not allocated yet. The extent will be converted to written
879  * after IO is complete from ext4_ext_direct_IO() function.
880  */
881 static int ext4_dio_get_block_unwritten_sync(struct inode *inode,
882                 sector_t iblock, struct buffer_head *bh_result, int create)
883 {
884         int ret;
885
886         /* We don't expect handle for direct IO */
887         WARN_ON_ONCE(ext4_journal_current_handle());
888
889         ret = ext4_get_block_trans(inode, iblock, bh_result,
890                                    EXT4_GET_BLOCKS_IO_CREATE_EXT);
891
892         /*
893          * Mark inode as having pending DIO writes to unwritten extents.
894          * ext4_ext_direct_IO() checks this flag and converts extents to
895          * written.
896          */
897         if (!ret && buffer_unwritten(bh_result))
898                 ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
899
900         return ret;
901 }
902
903 static int ext4_dio_get_block_overwrite(struct inode *inode, sector_t iblock,
904                    struct buffer_head *bh_result, int create)
905 {
906         int ret;
907
908         ext4_debug("ext4_dio_get_block_overwrite: inode %lu, create flag %d\n",
909                    inode->i_ino, create);
910         /* We don't expect handle for direct IO */
911         WARN_ON_ONCE(ext4_journal_current_handle());
912
913         ret = _ext4_get_block(inode, iblock, bh_result, 0);
914         /*
915          * Blocks should have been preallocated! ext4_file_write_iter() checks
916          * that.
917          */
918         WARN_ON_ONCE(!buffer_mapped(bh_result) || buffer_unwritten(bh_result));
919
920         return ret;
921 }
922
923
924 /*
925  * `handle' can be NULL if create is zero
926  */
927 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
928                                 ext4_lblk_t block, int map_flags)
929 {
930         struct ext4_map_blocks map;
931         struct buffer_head *bh;
932         int create = map_flags & EXT4_GET_BLOCKS_CREATE;
933         int err;
934
935         J_ASSERT(handle != NULL || create == 0);
936
937         map.m_lblk = block;
938         map.m_len = 1;
939         err = ext4_map_blocks(handle, inode, &map, map_flags);
940
941         if (err == 0)
942                 return create ? ERR_PTR(-ENOSPC) : NULL;
943         if (err < 0)
944                 return ERR_PTR(err);
945
946         bh = sb_getblk(inode->i_sb, map.m_pblk);
947         if (unlikely(!bh))
948                 return ERR_PTR(-ENOMEM);
949         if (map.m_flags & EXT4_MAP_NEW) {
950                 J_ASSERT(create != 0);
951                 J_ASSERT(handle != NULL);
952
953                 /*
954                  * Now that we do not always journal data, we should
955                  * keep in mind whether this should always journal the
956                  * new buffer as metadata.  For now, regular file
957                  * writes use ext4_get_block instead, so it's not a
958                  * problem.
959                  */
960                 lock_buffer(bh);
961                 BUFFER_TRACE(bh, "call get_create_access");
962                 err = ext4_journal_get_create_access(handle, bh);
963                 if (unlikely(err)) {
964                         unlock_buffer(bh);
965                         goto errout;
966                 }
967                 if (!buffer_uptodate(bh)) {
968                         memset(bh->b_data, 0, inode->i_sb->s_blocksize);
969                         set_buffer_uptodate(bh);
970                 }
971                 unlock_buffer(bh);
972                 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
973                 err = ext4_handle_dirty_metadata(handle, inode, bh);
974                 if (unlikely(err))
975                         goto errout;
976         } else
977                 BUFFER_TRACE(bh, "not a new buffer");
978         return bh;
979 errout:
980         brelse(bh);
981         return ERR_PTR(err);
982 }
983
984 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
985                                ext4_lblk_t block, int map_flags)
986 {
987         struct buffer_head *bh;
988
989         bh = ext4_getblk(handle, inode, block, map_flags);
990         if (IS_ERR(bh))
991                 return bh;
992         if (!bh || buffer_uptodate(bh))
993                 return bh;
994         ll_rw_block(REQ_OP_READ, REQ_META | REQ_PRIO, 1, &bh);
995         wait_on_buffer(bh);
996         if (buffer_uptodate(bh))
997                 return bh;
998         put_bh(bh);
999         return ERR_PTR(-EIO);
1000 }
1001
1002 int ext4_walk_page_buffers(handle_t *handle,
1003                            struct buffer_head *head,
1004                            unsigned from,
1005                            unsigned to,
1006                            int *partial,
1007                            int (*fn)(handle_t *handle,
1008                                      struct buffer_head *bh))
1009 {
1010         struct buffer_head *bh;
1011         unsigned block_start, block_end;
1012         unsigned blocksize = head->b_size;
1013         int err, ret = 0;
1014         struct buffer_head *next;
1015
1016         for (bh = head, block_start = 0;
1017              ret == 0 && (bh != head || !block_start);
1018              block_start = block_end, bh = next) {
1019                 next = bh->b_this_page;
1020                 block_end = block_start + blocksize;
1021                 if (block_end <= from || block_start >= to) {
1022                         if (partial && !buffer_uptodate(bh))
1023                                 *partial = 1;
1024                         continue;
1025                 }
1026                 err = (*fn)(handle, bh);
1027                 if (!ret)
1028                         ret = err;
1029         }
1030         return ret;
1031 }
1032
1033 /*
1034  * To preserve ordering, it is essential that the hole instantiation and
1035  * the data write be encapsulated in a single transaction.  We cannot
1036  * close off a transaction and start a new one between the ext4_get_block()
1037  * and the commit_write().  So doing the jbd2_journal_start at the start of
1038  * prepare_write() is the right place.
1039  *
1040  * Also, this function can nest inside ext4_writepage().  In that case, we
1041  * *know* that ext4_writepage() has generated enough buffer credits to do the
1042  * whole page.  So we won't block on the journal in that case, which is good,
1043  * because the caller may be PF_MEMALLOC.
1044  *
1045  * By accident, ext4 can be reentered when a transaction is open via
1046  * quota file writes.  If we were to commit the transaction while thus
1047  * reentered, there can be a deadlock - we would be holding a quota
1048  * lock, and the commit would never complete if another thread had a
1049  * transaction open and was blocking on the quota lock - a ranking
1050  * violation.
1051  *
1052  * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
1053  * will _not_ run commit under these circumstances because handle->h_ref
1054  * is elevated.  We'll still have enough credits for the tiny quotafile
1055  * write.
1056  */
1057 int do_journal_get_write_access(handle_t *handle,
1058                                 struct buffer_head *bh)
1059 {
1060         int dirty = buffer_dirty(bh);
1061         int ret;
1062
1063         if (!buffer_mapped(bh) || buffer_freed(bh))
1064                 return 0;
1065         /*
1066          * __block_write_begin() could have dirtied some buffers. Clean
1067          * the dirty bit as jbd2_journal_get_write_access() could complain
1068          * otherwise about fs integrity issues. Setting of the dirty bit
1069          * by __block_write_begin() isn't a real problem here as we clear
1070          * the bit before releasing a page lock and thus writeback cannot
1071          * ever write the buffer.
1072          */
1073         if (dirty)
1074                 clear_buffer_dirty(bh);
1075         BUFFER_TRACE(bh, "get write access");
1076         ret = ext4_journal_get_write_access(handle, bh);
1077         if (!ret && dirty)
1078                 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1079         return ret;
1080 }
1081
1082 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1083 static int ext4_block_write_begin(struct page *page, loff_t pos, unsigned len,
1084                                   get_block_t *get_block)
1085 {
1086         unsigned from = pos & (PAGE_SIZE - 1);
1087         unsigned to = from + len;
1088         struct inode *inode = page->mapping->host;
1089         unsigned block_start, block_end;
1090         sector_t block;
1091         int err = 0;
1092         unsigned blocksize = inode->i_sb->s_blocksize;
1093         unsigned bbits;
1094         struct buffer_head *bh, *head, *wait[2], **wait_bh = wait;
1095         bool decrypt = false;
1096
1097         BUG_ON(!PageLocked(page));
1098         BUG_ON(from > PAGE_SIZE);
1099         BUG_ON(to > PAGE_SIZE);
1100         BUG_ON(from > to);
1101
1102         if (!page_has_buffers(page))
1103                 create_empty_buffers(page, blocksize, 0);
1104         head = page_buffers(page);
1105         bbits = ilog2(blocksize);
1106         block = (sector_t)page->index << (PAGE_SHIFT - bbits);
1107
1108         for (bh = head, block_start = 0; bh != head || !block_start;
1109             block++, block_start = block_end, bh = bh->b_this_page) {
1110                 block_end = block_start + blocksize;
1111                 if (block_end <= from || block_start >= to) {
1112                         if (PageUptodate(page)) {
1113                                 if (!buffer_uptodate(bh))
1114                                         set_buffer_uptodate(bh);
1115                         }
1116                         continue;
1117                 }
1118                 if (buffer_new(bh))
1119                         clear_buffer_new(bh);
1120                 if (!buffer_mapped(bh)) {
1121                         WARN_ON(bh->b_size != blocksize);
1122                         err = get_block(inode, block, bh, 1);
1123                         if (err)
1124                                 break;
1125                         if (buffer_new(bh)) {
1126                                 clean_bdev_bh_alias(bh);
1127                                 if (PageUptodate(page)) {
1128                                         clear_buffer_new(bh);
1129                                         set_buffer_uptodate(bh);
1130                                         mark_buffer_dirty(bh);
1131                                         continue;
1132                                 }
1133                                 if (block_end > to || block_start < from)
1134                                         zero_user_segments(page, to, block_end,
1135                                                            block_start, from);
1136                                 continue;
1137                         }
1138                 }
1139                 if (PageUptodate(page)) {
1140                         if (!buffer_uptodate(bh))
1141                                 set_buffer_uptodate(bh);
1142                         continue;
1143                 }
1144                 if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
1145                     !buffer_unwritten(bh) &&
1146                     (block_start < from || block_end > to)) {
1147                         ll_rw_block(REQ_OP_READ, 0, 1, &bh);
1148                         *wait_bh++ = bh;
1149                         decrypt = ext4_encrypted_inode(inode) &&
1150                                 S_ISREG(inode->i_mode);
1151                 }
1152         }
1153         /*
1154          * If we issued read requests, let them complete.
1155          */
1156         while (wait_bh > wait) {
1157                 wait_on_buffer(*--wait_bh);
1158                 if (!buffer_uptodate(*wait_bh))
1159                         err = -EIO;
1160         }
1161         if (unlikely(err))
1162                 page_zero_new_buffers(page, from, to);
1163         else if (decrypt)
1164                 err = fscrypt_decrypt_page(page);
1165         return err;
1166 }
1167 #endif
1168
1169 static int ext4_write_begin(struct file *file, struct address_space *mapping,
1170                             loff_t pos, unsigned len, unsigned flags,
1171                             struct page **pagep, void **fsdata)
1172 {
1173         struct inode *inode = mapping->host;
1174         int ret, needed_blocks;
1175         handle_t *handle;
1176         int retries = 0;
1177         struct page *page;
1178         pgoff_t index;
1179         unsigned from, to;
1180
1181         trace_ext4_write_begin(inode, pos, len, flags);
1182         /*
1183          * Reserve one block more for addition to orphan list in case
1184          * we allocate blocks but write fails for some reason
1185          */
1186         needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
1187         index = pos >> PAGE_SHIFT;
1188         from = pos & (PAGE_SIZE - 1);
1189         to = from + len;
1190
1191         if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1192                 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1193                                                     flags, pagep);
1194                 if (ret < 0)
1195                         return ret;
1196                 if (ret == 1)
1197                         return 0;
1198         }
1199
1200         /*
1201          * grab_cache_page_write_begin() can take a long time if the
1202          * system is thrashing due to memory pressure, or if the page
1203          * is being written back.  So grab it first before we start
1204          * the transaction handle.  This also allows us to allocate
1205          * the page (if needed) without using GFP_NOFS.
1206          */
1207 retry_grab:
1208         page = grab_cache_page_write_begin(mapping, index, flags);
1209         if (!page)
1210                 return -ENOMEM;
1211         unlock_page(page);
1212
1213 retry_journal:
1214         handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1215         if (IS_ERR(handle)) {
1216                 put_page(page);
1217                 return PTR_ERR(handle);
1218         }
1219
1220         lock_page(page);
1221         if (page->mapping != mapping) {
1222                 /* The page got truncated from under us */
1223                 unlock_page(page);
1224                 put_page(page);
1225                 ext4_journal_stop(handle);
1226                 goto retry_grab;
1227         }
1228         /* In case writeback began while the page was unlocked */
1229         wait_for_stable_page(page);
1230
1231 #ifdef CONFIG_EXT4_FS_ENCRYPTION
1232         if (ext4_should_dioread_nolock(inode))
1233                 ret = ext4_block_write_begin(page, pos, len,
1234                                              ext4_get_block_unwritten);
1235         else
1236                 ret = ext4_block_write_begin(page, pos, len,
1237                                              ext4_get_block);
1238 #else
1239         if (ext4_should_dioread_nolock(inode))
1240                 ret = __block_write_begin(page, pos, len,
1241                                           ext4_get_block_unwritten);
1242         else
1243                 ret = __block_write_begin(page, pos, len, ext4_get_block);
1244 #endif
1245         if (!ret && ext4_should_journal_data(inode)) {
1246                 ret = ext4_walk_page_buffers(handle, page_buffers(page),
1247                                              from, to, NULL,
1248                                              do_journal_get_write_access);
1249         }
1250
1251         if (ret) {
1252                 unlock_page(page);
1253                 /*
1254                  * __block_write_begin may have instantiated a few blocks
1255                  * outside i_size.  Trim these off again. Don't need
1256                  * i_size_read because we hold i_mutex.
1257                  *
1258                  * Add inode to orphan list in case we crash before
1259                  * truncate finishes
1260                  */
1261                 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1262                         ext4_orphan_add(handle, inode);
1263
1264                 ext4_journal_stop(handle);
1265                 if (pos + len > inode->i_size) {
1266                         ext4_truncate_failed_write(inode);
1267                         /*
1268                          * If truncate failed early the inode might
1269                          * still be on the orphan list; we need to
1270                          * make sure the inode is removed from the
1271                          * orphan list in that case.
1272                          */
1273                         if (inode->i_nlink)
1274                                 ext4_orphan_del(NULL, inode);
1275                 }
1276
1277                 if (ret == -ENOSPC &&
1278                     ext4_should_retry_alloc(inode->i_sb, &retries))
1279                         goto retry_journal;
1280                 put_page(page);
1281                 return ret;
1282         }
1283         *pagep = page;
1284         return ret;
1285 }
1286
1287 /* For write_end() in data=journal mode */
1288 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1289 {
1290         int ret;
1291         if (!buffer_mapped(bh) || buffer_freed(bh))
1292                 return 0;
1293         set_buffer_uptodate(bh);
1294         ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1295         clear_buffer_meta(bh);
1296         clear_buffer_prio(bh);
1297         return ret;
1298 }
1299
1300 /*
1301  * We need to pick up the new inode size which generic_commit_write gave us
1302  * `file' can be NULL - eg, when called from page_symlink().
1303  *
1304  * ext4 never places buffers on inode->i_mapping->private_list.  metadata
1305  * buffers are managed internally.
1306  */
1307 static int ext4_write_end(struct file *file,
1308                           struct address_space *mapping,
1309                           loff_t pos, unsigned len, unsigned copied,
1310                           struct page *page, void *fsdata)
1311 {
1312         handle_t *handle = ext4_journal_current_handle();
1313         struct inode *inode = mapping->host;
1314         loff_t old_size = inode->i_size;
1315         int ret = 0, ret2;
1316         int i_size_changed = 0;
1317
1318         trace_ext4_write_end(inode, pos, len, copied);
1319         if (ext4_has_inline_data(inode)) {
1320                 ret = ext4_write_inline_data_end(inode, pos, len,
1321                                                  copied, page);
1322                 if (ret < 0)
1323                         goto errout;
1324                 copied = ret;
1325         } else
1326                 copied = block_write_end(file, mapping, pos,
1327                                          len, copied, page, fsdata);
1328         /*
1329          * it's important to update i_size while still holding page lock:
1330          * page writeout could otherwise come in and zero beyond i_size.
1331          */
1332         i_size_changed = ext4_update_inode_size(inode, pos + copied);
1333         unlock_page(page);
1334         put_page(page);
1335
1336         if (old_size < pos)
1337                 pagecache_isize_extended(inode, old_size, pos);
1338         /*
1339          * Don't mark the inode dirty under page lock. First, it unnecessarily
1340          * makes the holding time of page lock longer. Second, it forces lock
1341          * ordering of page lock and transaction start for journaling
1342          * filesystems.
1343          */
1344         if (i_size_changed)
1345                 ext4_mark_inode_dirty(handle, inode);
1346
1347         if (pos + len > inode->i_size && ext4_can_truncate(inode))
1348                 /* if we have allocated more blocks and copied
1349                  * less. We will have blocks allocated outside
1350                  * inode->i_size. So truncate them
1351                  */
1352                 ext4_orphan_add(handle, inode);
1353 errout:
1354         ret2 = ext4_journal_stop(handle);
1355         if (!ret)
1356                 ret = ret2;
1357
1358         if (pos + len > inode->i_size) {
1359                 ext4_truncate_failed_write(inode);
1360                 /*
1361                  * If truncate failed early the inode might still be
1362                  * on the orphan list; we need to make sure the inode
1363                  * is removed from the orphan list in that case.
1364                  */
1365                 if (inode->i_nlink)
1366                         ext4_orphan_del(NULL, inode);
1367         }
1368
1369         return ret ? ret : copied;
1370 }
1371
1372 /*
1373  * This is a private version of page_zero_new_buffers() which doesn't
1374  * set the buffer to be dirty, since in data=journalled mode we need
1375  * to call ext4_handle_dirty_metadata() instead.
1376  */
1377 static void zero_new_buffers(struct page *page, unsigned from, unsigned to)
1378 {
1379         unsigned int block_start = 0, block_end;
1380         struct buffer_head *head, *bh;
1381
1382         bh = head = page_buffers(page);
1383         do {
1384                 block_end = block_start + bh->b_size;
1385                 if (buffer_new(bh)) {
1386                         if (block_end > from && block_start < to) {
1387                                 if (!PageUptodate(page)) {
1388                                         unsigned start, size;
1389
1390                                         start = max(from, block_start);
1391                                         size = min(to, block_end) - start;
1392
1393                                         zero_user(page, start, size);
1394                                         set_buffer_uptodate(bh);
1395                                 }
1396                                 clear_buffer_new(bh);
1397                         }
1398                 }
1399                 block_start = block_end;
1400                 bh = bh->b_this_page;
1401         } while (bh != head);
1402 }
1403
1404 static int ext4_journalled_write_end(struct file *file,
1405                                      struct address_space *mapping,
1406                                      loff_t pos, unsigned len, unsigned copied,
1407                                      struct page *page, void *fsdata)
1408 {
1409         handle_t *handle = ext4_journal_current_handle();
1410         struct inode *inode = mapping->host;
1411         loff_t old_size = inode->i_size;
1412         int ret = 0, ret2;
1413         int partial = 0;
1414         unsigned from, to;
1415         int size_changed = 0;
1416
1417         trace_ext4_journalled_write_end(inode, pos, len, copied);
1418         from = pos & (PAGE_SIZE - 1);
1419         to = from + len;
1420
1421         BUG_ON(!ext4_handle_valid(handle));
1422
1423         if (ext4_has_inline_data(inode))
1424                 copied = ext4_write_inline_data_end(inode, pos, len,
1425                                                     copied, page);
1426         else {
1427                 if (copied < len) {
1428                         if (!PageUptodate(page))
1429                                 copied = 0;
1430                         zero_new_buffers(page, from+copied, to);
1431                 }
1432
1433                 ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
1434                                              to, &partial, write_end_fn);
1435                 if (!partial)
1436                         SetPageUptodate(page);
1437         }
1438         size_changed = ext4_update_inode_size(inode, pos + copied);
1439         ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1440         EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1441         unlock_page(page);
1442         put_page(page);
1443
1444         if (old_size < pos)
1445                 pagecache_isize_extended(inode, old_size, pos);
1446
1447         if (size_changed) {
1448                 ret2 = ext4_mark_inode_dirty(handle, inode);
1449                 if (!ret)
1450                         ret = ret2;
1451         }
1452
1453         if (pos + len > inode->i_size && ext4_can_truncate(inode))
1454                 /* if we have allocated more blocks and copied
1455                  * less. We will have blocks allocated outside
1456                  * inode->i_size. So truncate them
1457                  */
1458                 ext4_orphan_add(handle, inode);
1459
1460         ret2 = ext4_journal_stop(handle);
1461         if (!ret)
1462                 ret = ret2;
1463         if (pos + len > inode->i_size) {
1464                 ext4_truncate_failed_write(inode);
1465                 /*
1466                  * If truncate failed early the inode might still be
1467                  * on the orphan list; we need to make sure the inode
1468                  * is removed from the orphan list in that case.
1469                  */
1470                 if (inode->i_nlink)
1471                         ext4_orphan_del(NULL, inode);
1472         }
1473
1474         return ret ? ret : copied;
1475 }
1476
1477 /*
1478  * Reserve space for a single cluster
1479  */
1480 static int ext4_da_reserve_space(struct inode *inode)
1481 {
1482         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1483         struct ext4_inode_info *ei = EXT4_I(inode);
1484         int ret;
1485
1486         /*
1487          * We will charge metadata quota at writeout time; this saves
1488          * us from metadata over-estimation, though we may go over by
1489          * a small amount in the end.  Here we just reserve for data.
1490          */
1491         ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1492         if (ret)
1493                 return ret;
1494
1495         spin_lock(&ei->i_block_reservation_lock);
1496         if (ext4_claim_free_clusters(sbi, 1, 0)) {
1497                 spin_unlock(&ei->i_block_reservation_lock);
1498                 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1499                 return -ENOSPC;
1500         }
1501         ei->i_reserved_data_blocks++;
1502         trace_ext4_da_reserve_space(inode);
1503         spin_unlock(&ei->i_block_reservation_lock);
1504
1505         return 0;       /* success */
1506 }
1507
1508 static void ext4_da_release_space(struct inode *inode, int to_free)
1509 {
1510         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1511         struct ext4_inode_info *ei = EXT4_I(inode);
1512
1513         if (!to_free)
1514                 return;         /* Nothing to release, exit */
1515
1516         spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1517
1518         trace_ext4_da_release_space(inode, to_free);
1519         if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1520                 /*
1521                  * if there aren't enough reserved blocks, then the
1522                  * counter is messed up somewhere.  Since this
1523                  * function is called from invalidate page, it's
1524                  * harmless to return without any action.
1525                  */
1526                 ext4_warning(inode->i_sb, "ext4_da_release_space: "
1527                          "ino %lu, to_free %d with only %d reserved "
1528                          "data blocks", inode->i_ino, to_free,
1529                          ei->i_reserved_data_blocks);
1530                 WARN_ON(1);
1531                 to_free = ei->i_reserved_data_blocks;
1532         }
1533         ei->i_reserved_data_blocks -= to_free;
1534
1535         /* update fs dirty data blocks counter */
1536         percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1537
1538         spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1539
1540         dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1541 }
1542
1543 static void ext4_da_page_release_reservation(struct page *page,
1544                                              unsigned int offset,
1545                                              unsigned int length)
1546 {
1547         int to_release = 0, contiguous_blks = 0;
1548         struct buffer_head *head, *bh;
1549         unsigned int curr_off = 0;
1550         struct inode *inode = page->mapping->host;
1551         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1552         unsigned int stop = offset + length;
1553         int num_clusters;
1554         ext4_fsblk_t lblk;
1555
1556         BUG_ON(stop > PAGE_SIZE || stop < length);
1557
1558         head = page_buffers(page);
1559         bh = head;
1560         do {
1561                 unsigned int next_off = curr_off + bh->b_size;
1562
1563                 if (next_off > stop)
1564                         break;
1565
1566                 if ((offset <= curr_off) && (buffer_delay(bh))) {
1567                         to_release++;
1568                         contiguous_blks++;
1569                         clear_buffer_delay(bh);
1570                 } else if (contiguous_blks) {
1571                         lblk = page->index <<
1572                                (PAGE_SHIFT - inode->i_blkbits);
1573                         lblk += (curr_off >> inode->i_blkbits) -
1574                                 contiguous_blks;
1575                         ext4_es_remove_extent(inode, lblk, contiguous_blks);
1576                         contiguous_blks = 0;
1577                 }
1578                 curr_off = next_off;
1579         } while ((bh = bh->b_this_page) != head);
1580
1581         if (contiguous_blks) {
1582                 lblk = page->index << (PAGE_SHIFT - inode->i_blkbits);
1583                 lblk += (curr_off >> inode->i_blkbits) - contiguous_blks;
1584                 ext4_es_remove_extent(inode, lblk, contiguous_blks);
1585         }
1586
1587         /* If we have released all the blocks belonging to a cluster, then we
1588          * need to release the reserved space for that cluster. */
1589         num_clusters = EXT4_NUM_B2C(sbi, to_release);
1590         while (num_clusters > 0) {
1591                 lblk = (page->index << (PAGE_SHIFT - inode->i_blkbits)) +
1592                         ((num_clusters - 1) << sbi->s_cluster_bits);
1593                 if (sbi->s_cluster_ratio == 1 ||
1594                     !ext4_find_delalloc_cluster(inode, lblk))
1595                         ext4_da_release_space(inode, 1);
1596
1597                 num_clusters--;
1598         }
1599 }
1600
1601 /*
1602  * Delayed allocation stuff
1603  */
1604
1605 struct mpage_da_data {
1606         struct inode *inode;
1607         struct writeback_control *wbc;
1608
1609         pgoff_t first_page;     /* The first page to write */
1610         pgoff_t next_page;      /* Current page to examine */
1611         pgoff_t last_page;      /* Last page to examine */
1612         /*
1613          * Extent to map - this can be after first_page because that can be
1614          * fully mapped. We somewhat abuse m_flags to store whether the extent
1615          * is delalloc or unwritten.
1616          */
1617         struct ext4_map_blocks map;
1618         struct ext4_io_submit io_submit;        /* IO submission data */
1619 };
1620
1621 static void mpage_release_unused_pages(struct mpage_da_data *mpd,
1622                                        bool invalidate)
1623 {
1624         int nr_pages, i;
1625         pgoff_t index, end;
1626         struct pagevec pvec;
1627         struct inode *inode = mpd->inode;
1628         struct address_space *mapping = inode->i_mapping;
1629
1630         /* This is necessary when next_page == 0. */
1631         if (mpd->first_page >= mpd->next_page)
1632                 return;
1633
1634         index = mpd->first_page;
1635         end   = mpd->next_page - 1;
1636         if (invalidate) {
1637                 ext4_lblk_t start, last;
1638                 start = index << (PAGE_SHIFT - inode->i_blkbits);
1639                 last = end << (PAGE_SHIFT - inode->i_blkbits);
1640                 ext4_es_remove_extent(inode, start, last - start + 1);
1641         }
1642
1643         pagevec_init(&pvec, 0);
1644         while (index <= end) {
1645                 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1646                 if (nr_pages == 0)
1647                         break;
1648                 for (i = 0; i < nr_pages; i++) {
1649                         struct page *page = pvec.pages[i];
1650                         if (page->index > end)
1651                                 break;
1652                         BUG_ON(!PageLocked(page));
1653                         BUG_ON(PageWriteback(page));
1654                         if (invalidate) {
1655                                 if (page_mapped(page))
1656                                         clear_page_dirty_for_io(page);
1657                                 block_invalidatepage(page, 0, PAGE_SIZE);
1658                                 ClearPageUptodate(page);
1659                         }
1660                         unlock_page(page);
1661                 }
1662                 index = pvec.pages[nr_pages - 1]->index + 1;
1663                 pagevec_release(&pvec);
1664         }
1665 }
1666
1667 static void ext4_print_free_blocks(struct inode *inode)
1668 {
1669         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1670         struct super_block *sb = inode->i_sb;
1671         struct ext4_inode_info *ei = EXT4_I(inode);
1672
1673         ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1674                EXT4_C2B(EXT4_SB(inode->i_sb),
1675                         ext4_count_free_clusters(sb)));
1676         ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1677         ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1678                (long long) EXT4_C2B(EXT4_SB(sb),
1679                 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1680         ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1681                (long long) EXT4_C2B(EXT4_SB(sb),
1682                 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1683         ext4_msg(sb, KERN_CRIT, "Block reservation details");
1684         ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1685                  ei->i_reserved_data_blocks);
1686         return;
1687 }
1688
1689 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1690 {
1691         return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1692 }
1693
1694 /*
1695  * This function is grabs code from the very beginning of
1696  * ext4_map_blocks, but assumes that the caller is from delayed write
1697  * time. This function looks up the requested blocks and sets the
1698  * buffer delay bit under the protection of i_data_sem.
1699  */
1700 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1701                               struct ext4_map_blocks *map,
1702                               struct buffer_head *bh)
1703 {
1704         struct extent_status es;
1705         int retval;
1706         sector_t invalid_block = ~((sector_t) 0xffff);
1707 #ifdef ES_AGGRESSIVE_TEST
1708         struct ext4_map_blocks orig_map;
1709
1710         memcpy(&orig_map, map, sizeof(*map));
1711 #endif
1712
1713         if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1714                 invalid_block = ~0;
1715
1716         map->m_flags = 0;
1717         ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
1718                   "logical block %lu\n", inode->i_ino, map->m_len,
1719                   (unsigned long) map->m_lblk);
1720
1721         /* Lookup extent status tree firstly */
1722         if (ext4_es_lookup_extent(inode, iblock, &es)) {
1723                 if (ext4_es_is_hole(&es)) {
1724                         retval = 0;
1725                         down_read(&EXT4_I(inode)->i_data_sem);
1726                         goto add_delayed;
1727                 }
1728
1729                 /*
1730                  * Delayed extent could be allocated by fallocate.
1731                  * So we need to check it.
1732                  */
1733                 if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1734                         map_bh(bh, inode->i_sb, invalid_block);
1735                         set_buffer_new(bh);
1736                         set_buffer_delay(bh);
1737                         return 0;
1738                 }
1739
1740                 map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1741                 retval = es.es_len - (iblock - es.es_lblk);
1742                 if (retval > map->m_len)
1743                         retval = map->m_len;
1744                 map->m_len = retval;
1745                 if (ext4_es_is_written(&es))
1746                         map->m_flags |= EXT4_MAP_MAPPED;
1747                 else if (ext4_es_is_unwritten(&es))
1748                         map->m_flags |= EXT4_MAP_UNWRITTEN;
1749                 else
1750                         BUG_ON(1);
1751
1752 #ifdef ES_AGGRESSIVE_TEST
1753                 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1754 #endif
1755                 return retval;
1756         }
1757
1758         /*
1759          * Try to see if we can get the block without requesting a new
1760          * file system block.
1761          */
1762         down_read(&EXT4_I(inode)->i_data_sem);
1763         if (ext4_has_inline_data(inode))
1764                 retval = 0;
1765         else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1766                 retval = ext4_ext_map_blocks(NULL, inode, map, 0);
1767         else
1768                 retval = ext4_ind_map_blocks(NULL, inode, map, 0);
1769
1770 add_delayed:
1771         if (retval == 0) {
1772                 int ret;
1773                 /*
1774                  * XXX: __block_prepare_write() unmaps passed block,
1775                  * is it OK?
1776                  */
1777                 /*
1778                  * If the block was allocated from previously allocated cluster,
1779                  * then we don't need to reserve it again. However we still need
1780                  * to reserve metadata for every block we're going to write.
1781                  */
1782                 if (EXT4_SB(inode->i_sb)->s_cluster_ratio == 1 ||
1783                     !ext4_find_delalloc_cluster(inode, map->m_lblk)) {
1784                         ret = ext4_da_reserve_space(inode);
1785                         if (ret) {
1786                                 /* not enough space to reserve */
1787                                 retval = ret;
1788                                 goto out_unlock;
1789                         }
1790                 }
1791
1792                 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1793                                             ~0, EXTENT_STATUS_DELAYED);
1794                 if (ret) {
1795                         retval = ret;
1796                         goto out_unlock;
1797                 }
1798
1799                 map_bh(bh, inode->i_sb, invalid_block);
1800                 set_buffer_new(bh);
1801                 set_buffer_delay(bh);
1802         } else if (retval > 0) {
1803                 int ret;
1804                 unsigned int status;
1805
1806                 if (unlikely(retval != map->m_len)) {
1807                         ext4_warning(inode->i_sb,
1808                                      "ES len assertion failed for inode "
1809                                      "%lu: retval %d != map->m_len %d",
1810                                      inode->i_ino, retval, map->m_len);
1811                         WARN_ON(1);
1812                 }
1813
1814                 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1815                                 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1816                 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1817                                             map->m_pblk, status);
1818                 if (ret != 0)
1819                         retval = ret;
1820         }
1821
1822 out_unlock:
1823         up_read((&EXT4_I(inode)->i_data_sem));
1824
1825         return retval;
1826 }
1827
1828 /*
1829  * This is a special get_block_t callback which is used by
1830  * ext4_da_write_begin().  It will either return mapped block or
1831  * reserve space for a single block.
1832  *
1833  * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1834  * We also have b_blocknr = -1 and b_bdev initialized properly
1835  *
1836  * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1837  * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1838  * initialized properly.
1839  */
1840 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1841                            struct buffer_head *bh, int create)
1842 {
1843         struct ext4_map_blocks map;
1844         int ret = 0;
1845
1846         BUG_ON(create == 0);
1847         BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1848
1849         map.m_lblk = iblock;
1850         map.m_len = 1;
1851
1852         /*
1853          * first, we need to know whether the block is allocated already
1854          * preallocated blocks are unmapped but should treated
1855          * the same as allocated blocks.
1856          */
1857         ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1858         if (ret <= 0)
1859                 return ret;
1860
1861         map_bh(bh, inode->i_sb, map.m_pblk);
1862         ext4_update_bh_state(bh, map.m_flags);
1863
1864         if (buffer_unwritten(bh)) {
1865                 /* A delayed write to unwritten bh should be marked
1866                  * new and mapped.  Mapped ensures that we don't do
1867                  * get_block multiple times when we write to the same
1868                  * offset and new ensures that we do proper zero out
1869                  * for partial write.
1870                  */
1871                 set_buffer_new(bh);
1872                 set_buffer_mapped(bh);
1873         }
1874         return 0;
1875 }
1876
1877 static int bget_one(handle_t *handle, struct buffer_head *bh)
1878 {
1879         get_bh(bh);
1880         return 0;
1881 }
1882
1883 static int bput_one(handle_t *handle, struct buffer_head *bh)
1884 {
1885         put_bh(bh);
1886         return 0;
1887 }
1888
1889 static int __ext4_journalled_writepage(struct page *page,
1890                                        unsigned int len)
1891 {
1892         struct address_space *mapping = page->mapping;
1893         struct inode *inode = mapping->host;
1894         struct buffer_head *page_bufs = NULL;
1895         handle_t *handle = NULL;
1896         int ret = 0, err = 0;
1897         int inline_data = ext4_has_inline_data(inode);
1898         struct buffer_head *inode_bh = NULL;
1899
1900         ClearPageChecked(page);
1901
1902         if (inline_data) {
1903                 BUG_ON(page->index != 0);
1904                 BUG_ON(len > ext4_get_max_inline_size(inode));
1905                 inode_bh = ext4_journalled_write_inline_data(inode, len, page);
1906                 if (inode_bh == NULL)
1907                         goto out;
1908         } else {
1909                 page_bufs = page_buffers(page);
1910                 if (!page_bufs) {
1911                         BUG();
1912                         goto out;
1913                 }
1914                 ext4_walk_page_buffers(handle, page_bufs, 0, len,
1915                                        NULL, bget_one);
1916         }
1917         /*
1918          * We need to release the page lock before we start the
1919          * journal, so grab a reference so the page won't disappear
1920          * out from under us.
1921          */
1922         get_page(page);
1923         unlock_page(page);
1924
1925         handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
1926                                     ext4_writepage_trans_blocks(inode));
1927         if (IS_ERR(handle)) {
1928                 ret = PTR_ERR(handle);
1929                 put_page(page);
1930                 goto out_no_pagelock;
1931         }
1932         BUG_ON(!ext4_handle_valid(handle));
1933
1934         lock_page(page);
1935         put_page(page);
1936         if (page->mapping != mapping) {
1937                 /* The page got truncated from under us */
1938                 ext4_journal_stop(handle);
1939                 ret = 0;
1940                 goto out;
1941         }
1942
1943         if (inline_data) {
1944                 BUFFER_TRACE(inode_bh, "get write access");
1945                 ret = ext4_journal_get_write_access(handle, inode_bh);
1946
1947                 err = ext4_handle_dirty_metadata(handle, inode, inode_bh);
1948
1949         } else {
1950                 ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1951                                              do_journal_get_write_access);
1952
1953                 err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1954                                              write_end_fn);
1955         }
1956         if (ret == 0)
1957                 ret = err;
1958         EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1959         err = ext4_journal_stop(handle);
1960         if (!ret)
1961                 ret = err;
1962
1963         if (!ext4_has_inline_data(inode))
1964                 ext4_walk_page_buffers(NULL, page_bufs, 0, len,
1965                                        NULL, bput_one);
1966         ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1967 out:
1968         unlock_page(page);
1969 out_no_pagelock:
1970         brelse(inode_bh);
1971         return ret;
1972 }
1973
1974 /*
1975  * Note that we don't need to start a transaction unless we're journaling data
1976  * because we should have holes filled from ext4_page_mkwrite(). We even don't
1977  * need to file the inode to the transaction's list in ordered mode because if
1978  * we are writing back data added by write(), the inode is already there and if
1979  * we are writing back data modified via mmap(), no one guarantees in which
1980  * transaction the data will hit the disk. In case we are journaling data, we
1981  * cannot start transaction directly because transaction start ranks above page
1982  * lock so we have to do some magic.
1983  *
1984  * This function can get called via...
1985  *   - ext4_writepages after taking page lock (have journal handle)
1986  *   - journal_submit_inode_data_buffers (no journal handle)
1987  *   - shrink_page_list via the kswapd/direct reclaim (no journal handle)
1988  *   - grab_page_cache when doing write_begin (have journal handle)
1989  *
1990  * We don't do any block allocation in this function. If we have page with
1991  * multiple blocks we need to write those buffer_heads that are mapped. This
1992  * is important for mmaped based write. So if we do with blocksize 1K
1993  * truncate(f, 1024);
1994  * a = mmap(f, 0, 4096);
1995  * a[0] = 'a';
1996  * truncate(f, 4096);
1997  * we have in the page first buffer_head mapped via page_mkwrite call back
1998  * but other buffer_heads would be unmapped but dirty (dirty done via the
1999  * do_wp_page). So writepage should write the first block. If we modify
2000  * the mmap area beyond 1024 we will again get a page_fault and the
2001  * page_mkwrite callback will do the block allocation and mark the
2002  * buffer_heads mapped.
2003  *
2004  * We redirty the page if we have any buffer_heads that is either delay or
2005  * unwritten in the page.
2006  *
2007  * We can get recursively called as show below.
2008  *
2009  *      ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
2010  *              ext4_writepage()
2011  *
2012  * But since we don't do any block allocation we should not deadlock.
2013  * Page also have the dirty flag cleared so we don't get recurive page_lock.
2014  */
2015 static int ext4_writepage(struct page *page,
2016                           struct writeback_control *wbc)
2017 {
2018         int ret = 0;
2019         loff_t size;
2020         unsigned int len;
2021         struct buffer_head *page_bufs = NULL;
2022         struct inode *inode = page->mapping->host;
2023         struct ext4_io_submit io_submit;
2024         bool keep_towrite = false;
2025
2026         trace_ext4_writepage(page);
2027         size = i_size_read(inode);
2028         if (page->index == size >> PAGE_SHIFT)
2029                 len = size & ~PAGE_MASK;
2030         else
2031                 len = PAGE_SIZE;
2032
2033         page_bufs = page_buffers(page);
2034         /*
2035          * We cannot do block allocation or other extent handling in this
2036          * function. If there are buffers needing that, we have to redirty
2037          * the page. But we may reach here when we do a journal commit via
2038          * journal_submit_inode_data_buffers() and in that case we must write
2039          * allocated buffers to achieve data=ordered mode guarantees.
2040          *
2041          * Also, if there is only one buffer per page (the fs block
2042          * size == the page size), if one buffer needs block
2043          * allocation or needs to modify the extent tree to clear the
2044          * unwritten flag, we know that the page can't be written at
2045          * all, so we might as well refuse the write immediately.
2046          * Unfortunately if the block size != page size, we can't as
2047          * easily detect this case using ext4_walk_page_buffers(), but
2048          * for the extremely common case, this is an optimization that
2049          * skips a useless round trip through ext4_bio_write_page().
2050          */
2051         if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2052                                    ext4_bh_delay_or_unwritten)) {
2053                 redirty_page_for_writepage(wbc, page);
2054                 if ((current->flags & PF_MEMALLOC) ||
2055                     (inode->i_sb->s_blocksize == PAGE_SIZE)) {
2056                         /*
2057                          * For memory cleaning there's no point in writing only
2058                          * some buffers. So just bail out. Warn if we came here
2059                          * from direct reclaim.
2060                          */
2061                         WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
2062                                                         == PF_MEMALLOC);
2063                         unlock_page(page);
2064                         return 0;
2065                 }
2066                 keep_towrite = true;
2067         }
2068
2069         if (PageChecked(page) && ext4_should_journal_data(inode))
2070                 /*
2071                  * It's mmapped pagecache.  Add buffers and journal it.  There
2072                  * doesn't seem much point in redirtying the page here.
2073                  */
2074                 return __ext4_journalled_writepage(page, len);
2075
2076         ext4_io_submit_init(&io_submit, wbc);
2077         io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
2078         if (!io_submit.io_end) {
2079                 redirty_page_for_writepage(wbc, page);
2080                 unlock_page(page);
2081                 return -ENOMEM;
2082         }
2083         ret = ext4_bio_write_page(&io_submit, page, len, wbc, keep_towrite);
2084         ext4_io_submit(&io_submit);
2085         /* Drop io_end reference we got from init */
2086         ext4_put_io_end_defer(io_submit.io_end);
2087         return ret;
2088 }
2089
2090 static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
2091 {
2092         int len;
2093         loff_t size = i_size_read(mpd->inode);
2094         int err;
2095
2096         BUG_ON(page->index != mpd->first_page);
2097         if (page->index == size >> PAGE_SHIFT)
2098                 len = size & ~PAGE_MASK;
2099         else
2100                 len = PAGE_SIZE;
2101         clear_page_dirty_for_io(page);
2102         err = ext4_bio_write_page(&mpd->io_submit, page, len, mpd->wbc, false);
2103         if (!err)
2104                 mpd->wbc->nr_to_write--;
2105         mpd->first_page++;
2106
2107         return err;
2108 }
2109
2110 #define BH_FLAGS ((1 << BH_Unwritten) | (1 << BH_Delay))
2111
2112 /*
2113  * mballoc gives us at most this number of blocks...
2114  * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
2115  * The rest of mballoc seems to handle chunks up to full group size.
2116  */
2117 #define MAX_WRITEPAGES_EXTENT_LEN 2048
2118
2119 /*
2120  * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
2121  *
2122  * @mpd - extent of blocks
2123  * @lblk - logical number of the block in the file
2124  * @bh - buffer head we want to add to the extent
2125  *
2126  * The function is used to collect contig. blocks in the same state. If the
2127  * buffer doesn't require mapping for writeback and we haven't started the
2128  * extent of buffers to map yet, the function returns 'true' immediately - the
2129  * caller can write the buffer right away. Otherwise the function returns true
2130  * if the block has been added to the extent, false if the block couldn't be
2131  * added.
2132  */
2133 static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
2134                                    struct buffer_head *bh)
2135 {
2136         struct ext4_map_blocks *map = &mpd->map;
2137
2138         /* Buffer that doesn't need mapping for writeback? */
2139         if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
2140             (!buffer_delay(bh) && !buffer_unwritten(bh))) {
2141                 /* So far no extent to map => we write the buffer right away */
2142                 if (map->m_len == 0)
2143                         return true;
2144                 return false;
2145         }
2146
2147         /* First block in the extent? */
2148         if (map->m_len == 0) {
2149                 map->m_lblk = lblk;
2150                 map->m_len = 1;
2151                 map->m_flags = bh->b_state & BH_FLAGS;
2152                 return true;
2153         }
2154
2155         /* Don't go larger than mballoc is willing to allocate */
2156         if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
2157                 return false;
2158
2159         /* Can we merge the block to our big extent? */
2160         if (lblk == map->m_lblk + map->m_len &&
2161             (bh->b_state & BH_FLAGS) == map->m_flags) {
2162                 map->m_len++;
2163                 return true;
2164         }
2165         return false;
2166 }
2167
2168 /*
2169  * mpage_process_page_bufs - submit page buffers for IO or add them to extent
2170  *
2171  * @mpd - extent of blocks for mapping
2172  * @head - the first buffer in the page
2173  * @bh - buffer we should start processing from
2174  * @lblk - logical number of the block in the file corresponding to @bh
2175  *
2176  * Walk through page buffers from @bh upto @head (exclusive) and either submit
2177  * the page for IO if all buffers in this page were mapped and there's no
2178  * accumulated extent of buffers to map or add buffers in the page to the
2179  * extent of buffers to map. The function returns 1 if the caller can continue
2180  * by processing the next page, 0 if it should stop adding buffers to the
2181  * extent to map because we cannot extend it anymore. It can also return value
2182  * < 0 in case of error during IO submission.
2183  */
2184 static int mpage_process_page_bufs(struct mpage_da_data *mpd,
2185                                    struct buffer_head *head,
2186                                    struct buffer_head *bh,
2187                                    ext4_lblk_t lblk)
2188 {
2189         struct inode *inode = mpd->inode;
2190         int err;
2191         ext4_lblk_t blocks = (i_size_read(inode) + (1 << inode->i_blkbits) - 1)
2192                                                         >> inode->i_blkbits;
2193
2194         do {
2195                 BUG_ON(buffer_locked(bh));
2196
2197                 if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
2198                         /* Found extent to map? */
2199                         if (mpd->map.m_len)
2200                                 return 0;
2201                         /* Everything mapped so far and we hit EOF */
2202                         break;
2203                 }
2204         } while (lblk++, (bh = bh->b_this_page) != head);
2205         /* So far everything mapped? Submit the page for IO. */
2206         if (mpd->map.m_len == 0) {
2207                 err = mpage_submit_page(mpd, head->b_page);
2208                 if (err < 0)
2209                         return err;
2210         }
2211         return lblk < blocks;
2212 }
2213
2214 /*
2215  * mpage_map_buffers - update buffers corresponding to changed extent and
2216  *                     submit fully mapped pages for IO
2217  *
2218  * @mpd - description of extent to map, on return next extent to map
2219  *
2220  * Scan buffers corresponding to changed extent (we expect corresponding pages
2221  * to be already locked) and update buffer state according to new extent state.
2222  * We map delalloc buffers to their physical location, clear unwritten bits,
2223  * and mark buffers as uninit when we perform writes to unwritten extents
2224  * and do extent conversion after IO is finished. If the last page is not fully
2225  * mapped, we update @map to the next extent in the last page that needs
2226  * mapping. Otherwise we submit the page for IO.
2227  */
2228 static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
2229 {
2230         struct pagevec pvec;
2231         int nr_pages, i;
2232         struct inode *inode = mpd->inode;
2233         struct buffer_head *head, *bh;
2234         int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
2235         pgoff_t start, end;
2236         ext4_lblk_t lblk;
2237         sector_t pblock;
2238         int err;
2239
2240         start = mpd->map.m_lblk >> bpp_bits;
2241         end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
2242         lblk = start << bpp_bits;
2243         pblock = mpd->map.m_pblk;
2244
2245         pagevec_init(&pvec, 0);
2246         while (start <= end) {
2247                 nr_pages = pagevec_lookup(&pvec, inode->i_mapping, start,
2248                                           PAGEVEC_SIZE);
2249                 if (nr_pages == 0)
2250                         break;
2251                 for (i = 0; i < nr_pages; i++) {
2252                         struct page *page = pvec.pages[i];
2253
2254                         if (page->index > end)
2255                                 break;
2256                         /* Up to 'end' pages must be contiguous */
2257                         BUG_ON(page->index != start);
2258                         bh = head = page_buffers(page);
2259                         do {
2260                                 if (lblk < mpd->map.m_lblk)
2261                                         continue;
2262                                 if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2263                                         /*
2264                                          * Buffer after end of mapped extent.
2265                                          * Find next buffer in the page to map.
2266                                          */
2267                                         mpd->map.m_len = 0;
2268                                         mpd->map.m_flags = 0;
2269                                         /*
2270                                          * FIXME: If dioread_nolock supports
2271                                          * blocksize < pagesize, we need to make
2272                                          * sure we add size mapped so far to
2273                                          * io_end->size as the following call
2274                                          * can submit the page for IO.
2275                                          */
2276                                         err = mpage_process_page_bufs(mpd, head,
2277                                                                       bh, lblk);
2278                                         pagevec_release(&pvec);
2279                                         if (err > 0)
2280                                                 err = 0;
2281                                         return err;
2282                                 }
2283                                 if (buffer_delay(bh)) {
2284                                         clear_buffer_delay(bh);
2285                                         bh->b_blocknr = pblock++;
2286                                 }
2287                                 clear_buffer_unwritten(bh);
2288                         } while (lblk++, (bh = bh->b_this_page) != head);
2289
2290                         /*
2291                          * FIXME: This is going to break if dioread_nolock
2292                          * supports blocksize < pagesize as we will try to
2293                          * convert potentially unmapped parts of inode.
2294                          */
2295                         mpd->io_submit.io_end->size += PAGE_SIZE;
2296                         /* Page fully mapped - let IO run! */
2297                         err = mpage_submit_page(mpd, page);
2298                         if (err < 0) {
2299                                 pagevec_release(&pvec);
2300                                 return err;
2301                         }
2302                         start++;
2303                 }
2304                 pagevec_release(&pvec);
2305         }
2306         /* Extent fully mapped and matches with page boundary. We are done. */
2307         mpd->map.m_len = 0;
2308         mpd->map.m_flags = 0;
2309         return 0;
2310 }
2311
2312 static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2313 {
2314         struct inode *inode = mpd->inode;
2315         struct ext4_map_blocks *map = &mpd->map;
2316         int get_blocks_flags;
2317         int err, dioread_nolock;
2318
2319         trace_ext4_da_write_pages_extent(inode, map);
2320         /*
2321          * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2322          * to convert an unwritten extent to be initialized (in the case
2323          * where we have written into one or more preallocated blocks).  It is
2324          * possible that we're going to need more metadata blocks than
2325          * previously reserved. However we must not fail because we're in
2326          * writeback and there is nothing we can do about it so it might result
2327          * in data loss.  So use reserved blocks to allocate metadata if
2328          * possible.
2329          *
2330          * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2331          * the blocks in question are delalloc blocks.  This indicates
2332          * that the blocks and quotas has already been checked when
2333          * the data was copied into the page cache.
2334          */
2335         get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2336                            EXT4_GET_BLOCKS_METADATA_NOFAIL |
2337                            EXT4_GET_BLOCKS_IO_SUBMIT;
2338         dioread_nolock = ext4_should_dioread_nolock(inode);
2339         if (dioread_nolock)
2340                 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2341         if (map->m_flags & (1 << BH_Delay))
2342                 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2343
2344         err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2345         if (err < 0)
2346                 return err;
2347         if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
2348                 if (!mpd->io_submit.io_end->handle &&
2349                     ext4_handle_valid(handle)) {
2350                         mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2351                         handle->h_rsv_handle = NULL;
2352                 }
2353                 ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
2354         }
2355
2356         BUG_ON(map->m_len == 0);
2357         if (map->m_flags & EXT4_MAP_NEW) {
2358                 clean_bdev_aliases(inode->i_sb->s_bdev, map->m_pblk,
2359                                    map->m_len);
2360         }
2361         return 0;
2362 }
2363
2364 /*
2365  * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2366  *                               mpd->len and submit pages underlying it for IO
2367  *
2368  * @handle - handle for journal operations
2369  * @mpd - extent to map
2370  * @give_up_on_write - we set this to true iff there is a fatal error and there
2371  *                     is no hope of writing the data. The caller should discard
2372  *                     dirty pages to avoid infinite loops.
2373  *
2374  * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2375  * delayed, blocks are allocated, if it is unwritten, we may need to convert
2376  * them to initialized or split the described range from larger unwritten
2377  * extent. Note that we need not map all the described range since allocation
2378  * can return less blocks or the range is covered by more unwritten extents. We
2379  * cannot map more because we are limited by reserved transaction credits. On
2380  * the other hand we always make sure that the last touched page is fully
2381  * mapped so that it can be written out (and thus forward progress is
2382  * guaranteed). After mapping we submit all mapped pages for IO.
2383  */
2384 static int mpage_map_and_submit_extent(handle_t *handle,
2385                                        struct mpage_da_data *mpd,
2386                                        bool *give_up_on_write)
2387 {
2388         struct inode *inode = mpd->inode;
2389         struct ext4_map_blocks *map = &mpd->map;
2390         int err;
2391         loff_t disksize;
2392         int progress = 0;
2393
2394         mpd->io_submit.io_end->offset =
2395                                 ((loff_t)map->m_lblk) << inode->i_blkbits;
2396         do {
2397                 err = mpage_map_one_extent(handle, mpd);
2398                 if (err < 0) {
2399                         struct super_block *sb = inode->i_sb;
2400
2401                         if (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)
2402                                 goto invalidate_dirty_pages;
2403                         /*
2404                          * Let the uper layers retry transient errors.
2405                          * In the case of ENOSPC, if ext4_count_free_blocks()
2406                          * is non-zero, a commit should free up blocks.
2407                          */
2408                         if ((err == -ENOMEM) ||
2409                             (err == -ENOSPC && ext4_count_free_clusters(sb))) {
2410                                 if (progress)
2411                                         goto update_disksize;
2412                                 return err;
2413                         }
2414                         ext4_msg(sb, KERN_CRIT,
2415                                  "Delayed block allocation failed for "
2416                                  "inode %lu at logical offset %llu with"
2417                                  " max blocks %u with error %d",
2418                                  inode->i_ino,
2419                                  (unsigned long long)map->m_lblk,
2420                                  (unsigned)map->m_len, -err);
2421                         ext4_msg(sb, KERN_CRIT,
2422                                  "This should not happen!! Data will "
2423                                  "be lost\n");
2424                         if (err == -ENOSPC)
2425                                 ext4_print_free_blocks(inode);
2426                 invalidate_dirty_pages:
2427                         *give_up_on_write = true;
2428                         return err;
2429                 }
2430                 progress = 1;
2431                 /*
2432                  * Update buffer state, submit mapped pages, and get us new
2433                  * extent to map
2434                  */
2435                 err = mpage_map_and_submit_buffers(mpd);
2436                 if (err < 0)
2437                         goto update_disksize;
2438         } while (map->m_len);
2439
2440 update_disksize:
2441         /*
2442          * Update on-disk size after IO is submitted.  Races with
2443          * truncate are avoided by checking i_size under i_data_sem.
2444          */
2445         disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
2446         if (disksize > EXT4_I(inode)->i_disksize) {
2447                 int err2;
2448                 loff_t i_size;
2449
2450                 down_write(&EXT4_I(inode)->i_data_sem);
2451                 i_size = i_size_read(inode);
2452                 if (disksize > i_size)
2453                         disksize = i_size;
2454                 if (disksize > EXT4_I(inode)->i_disksize)
2455                         EXT4_I(inode)->i_disksize = disksize;
2456                 err2 = ext4_mark_inode_dirty(handle, inode);
2457                 up_write(&EXT4_I(inode)->i_data_sem);
2458                 if (err2)
2459                         ext4_error(inode->i_sb,
2460                                    "Failed to mark inode %lu dirty",
2461                                    inode->i_ino);
2462                 if (!err)
2463                         err = err2;
2464         }
2465         return err;
2466 }
2467
2468 /*
2469  * Calculate the total number of credits to reserve for one writepages
2470  * iteration. This is called from ext4_writepages(). We map an extent of
2471  * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2472  * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2473  * bpp - 1 blocks in bpp different extents.
2474  */
2475 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2476 {
2477         int bpp = ext4_journal_blocks_per_page(inode);
2478
2479         return ext4_meta_trans_blocks(inode,
2480                                 MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2481 }
2482
2483 /*
2484  * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2485  *                               and underlying extent to map
2486  *
2487  * @mpd - where to look for pages
2488  *
2489  * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2490  * IO immediately. When we find a page which isn't mapped we start accumulating
2491  * extent of buffers underlying these pages that needs mapping (formed by
2492  * either delayed or unwritten buffers). We also lock the pages containing
2493  * these buffers. The extent found is returned in @mpd structure (starting at
2494  * mpd->lblk with length mpd->len blocks).
2495  *
2496  * Note that this function can attach bios to one io_end structure which are
2497  * neither logically nor physically contiguous. Although it may seem as an
2498  * unnecessary complication, it is actually inevitable in blocksize < pagesize
2499  * case as we need to track IO to all buffers underlying a page in one io_end.
2500  */
2501 static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
2502 {
2503         struct address_space *mapping = mpd->inode->i_mapping;
2504         struct pagevec pvec;
2505         unsigned int nr_pages;
2506         long left = mpd->wbc->nr_to_write;
2507         pgoff_t index = mpd->first_page;
2508         pgoff_t end = mpd->last_page;
2509         int tag;
2510         int i, err = 0;
2511         int blkbits = mpd->inode->i_blkbits;
2512         ext4_lblk_t lblk;
2513         struct buffer_head *head;
2514
2515         if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
2516                 tag = PAGECACHE_TAG_TOWRITE;
2517         else
2518                 tag = PAGECACHE_TAG_DIRTY;
2519
2520         pagevec_init(&pvec, 0);
2521         mpd->map.m_len = 0;
2522         mpd->next_page = index;
2523         while (index <= end) {
2524                 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
2525                               min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
2526                 if (nr_pages == 0)
2527                         goto out;
2528
2529                 for (i = 0; i < nr_pages; i++) {
2530                         struct page *page = pvec.pages[i];
2531
2532                         /*
2533                          * At this point, the page may be truncated or
2534                          * invalidated (changing page->mapping to NULL), or
2535                          * even swizzled back from swapper_space to tmpfs file
2536                          * mapping. However, page->index will not change
2537                          * because we have a reference on the page.
2538                          */
2539                         if (page->index > end)
2540                                 goto out;
2541
2542                         /*
2543                          * Accumulated enough dirty pages? This doesn't apply
2544                          * to WB_SYNC_ALL mode. For integrity sync we have to
2545                          * keep going because someone may be concurrently
2546                          * dirtying pages, and we might have synced a lot of
2547                          * newly appeared dirty pages, but have not synced all
2548                          * of the old dirty pages.
2549                          */
2550                         if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2551                                 goto out;
2552
2553                         /* If we can't merge this page, we are done. */
2554                         if (mpd->map.m_len > 0 && mpd->next_page != page->index)
2555                                 goto out;
2556
2557                         lock_page(page);
2558                         /*
2559                          * If the page is no longer dirty, or its mapping no
2560                          * longer corresponds to inode we are writing (which
2561                          * means it has been truncated or invalidated), or the
2562                          * page is already under writeback and we are not doing
2563                          * a data integrity writeback, skip the page
2564                          */
2565                         if (!PageDirty(page) ||
2566                             (PageWriteback(page) &&
2567                              (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
2568                             unlikely(page->mapping != mapping)) {
2569                                 unlock_page(page);
2570                                 continue;
2571                         }
2572
2573                         wait_on_page_writeback(page);
2574                         BUG_ON(PageWriteback(page));
2575
2576                         if (mpd->map.m_len == 0)
2577                                 mpd->first_page = page->index;
2578                         mpd->next_page = page->index + 1;
2579                         /* Add all dirty buffers to mpd */
2580                         lblk = ((ext4_lblk_t)page->index) <<
2581                                 (PAGE_SHIFT - blkbits);
2582                         head = page_buffers(page);
2583                         err = mpage_process_page_bufs(mpd, head, head, lblk);
2584                         if (err <= 0)
2585                                 goto out;
2586                         err = 0;
2587                         left--;
2588                 }
2589                 pagevec_release(&pvec);
2590                 cond_resched();
2591         }
2592         return 0;
2593 out:
2594         pagevec_release(&pvec);
2595         return err;
2596 }
2597
2598 static int __writepage(struct page *page, struct writeback_control *wbc,
2599                        void *data)
2600 {
2601         struct address_space *mapping = data;
2602         int ret = ext4_writepage(page, wbc);
2603         mapping_set_error(mapping, ret);
2604         return ret;
2605 }
2606
2607 static int ext4_writepages(struct address_space *mapping,
2608                            struct writeback_control *wbc)
2609 {
2610         pgoff_t writeback_index = 0;
2611         long nr_to_write = wbc->nr_to_write;
2612         int range_whole = 0;
2613         int cycled = 1;
2614         handle_t *handle = NULL;
2615         struct mpage_da_data mpd;
2616         struct inode *inode = mapping->host;
2617         int needed_blocks, rsv_blocks = 0, ret = 0;
2618         struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2619         bool done;
2620         struct blk_plug plug;
2621         bool give_up_on_write = false;
2622
2623         percpu_down_read(&sbi->s_journal_flag_rwsem);
2624         trace_ext4_writepages(inode, wbc);
2625
2626         if (dax_mapping(mapping)) {
2627                 ret = dax_writeback_mapping_range(mapping, inode->i_sb->s_bdev,
2628                                                   wbc);
2629                 goto out_writepages;
2630         }
2631
2632         /*
2633          * No pages to write? This is mainly a kludge to avoid starting
2634          * a transaction for special inodes like journal inode on last iput()
2635          * because that could violate lock ordering on umount
2636          */
2637         if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2638                 goto out_writepages;
2639
2640         if (ext4_should_journal_data(inode)) {
2641                 struct blk_plug plug;
2642
2643                 blk_start_plug(&plug);
2644                 ret = write_cache_pages(mapping, wbc, __writepage, mapping);
2645                 blk_finish_plug(&plug);
2646                 goto out_writepages;
2647         }
2648
2649         /*
2650          * If the filesystem has aborted, it is read-only, so return
2651          * right away instead of dumping stack traces later on that
2652          * will obscure the real source of the problem.  We test
2653          * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2654          * the latter could be true if the filesystem is mounted
2655          * read-only, and in that case, ext4_writepages should
2656          * *never* be called, so if that ever happens, we would want
2657          * the stack trace.
2658          */
2659         if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED)) {
2660                 ret = -EROFS;
2661                 goto out_writepages;
2662         }
2663
2664         if (ext4_should_dioread_nolock(inode)) {
2665                 /*
2666                  * We may need to convert up to one extent per block in
2667                  * the page and we may dirty the inode.
2668                  */
2669                 rsv_blocks = 1 + (PAGE_SIZE >> inode->i_blkbits);
2670         }
2671
2672         /*
2673          * If we have inline data and arrive here, it means that
2674          * we will soon create the block for the 1st page, so
2675          * we'd better clear the inline data here.
2676          */
2677         if (ext4_has_inline_data(inode)) {
2678                 /* Just inode will be modified... */
2679                 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2680                 if (IS_ERR(handle)) {
2681                         ret = PTR_ERR(handle);
2682                         goto out_writepages;
2683                 }
2684                 BUG_ON(ext4_test_inode_state(inode,
2685                                 EXT4_STATE_MAY_INLINE_DATA));
2686                 ext4_destroy_inline_data(handle, inode);
2687                 ext4_journal_stop(handle);
2688         }
2689
2690         if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2691                 range_whole = 1;
2692
2693         if (wbc->range_cyclic) {
2694                 writeback_index = mapping->writeback_index;
2695                 if (writeback_index)
2696                         cycled = 0;
2697                 mpd.first_page = writeback_index;
2698                 mpd.last_page = -1;
2699         } else {
2700                 mpd.first_page = wbc->range_start >> PAGE_SHIFT;
2701                 mpd.last_page = wbc->range_end >> PAGE_SHIFT;
2702         }
2703
2704         mpd.inode = inode;
2705         mpd.wbc = wbc;
2706         ext4_io_submit_init(&mpd.io_submit, wbc);
2707 retry:
2708         if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2709                 tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
2710         done = false;
2711         blk_start_plug(&plug);
2712         while (!done && mpd.first_page <= mpd.last_page) {
2713                 /* For each extent of pages we use new io_end */
2714                 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2715                 if (!mpd.io_submit.io_end) {
2716                         ret = -ENOMEM;
2717                         break;
2718                 }
2719
2720                 /*
2721                  * We have two constraints: We find one extent to map and we
2722                  * must always write out whole page (makes a difference when
2723                  * blocksize < pagesize) so that we don't block on IO when we
2724                  * try to write out the rest of the page. Journalled mode is
2725                  * not supported by delalloc.
2726                  */
2727                 BUG_ON(ext4_should_journal_data(inode));
2728                 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2729
2730                 /* start a new transaction */
2731                 handle = ext4_journal_start_with_reserve(inode,
2732                                 EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
2733                 if (IS_ERR(handle)) {
2734                         ret = PTR_ERR(handle);
2735                         ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2736                                "%ld pages, ino %lu; err %d", __func__,
2737                                 wbc->nr_to_write, inode->i_ino, ret);
2738                         /* Release allocated io_end */
2739                         ext4_put_io_end(mpd.io_submit.io_end);
2740                         break;
2741                 }
2742
2743                 trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
2744                 ret = mpage_prepare_extent_to_map(&mpd);
2745                 if (!ret) {
2746                         if (mpd.map.m_len)
2747                                 ret = mpage_map_and_submit_extent(handle, &mpd,
2748                                         &give_up_on_write);
2749                         else {
2750                                 /*
2751                                  * We scanned the whole range (or exhausted
2752                                  * nr_to_write), submitted what was mapped and
2753                                  * didn't find anything needing mapping. We are
2754                                  * done.
2755                                  */
2756                                 done = true;
2757                         }
2758                 }
2759                 /*
2760                  * Caution: If the handle is synchronous,
2761                  * ext4_journal_stop() can wait for transaction commit
2762                  * to finish which may depend on writeback of pages to
2763                  * complete or on page lock to be released.  In that
2764                  * case, we have to wait until after after we have
2765                  * submitted all the IO, released page locks we hold,
2766                  * and dropped io_end reference (for extent conversion
2767                  * to be able to complete) before stopping the handle.
2768                  */
2769                 if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
2770                         ext4_journal_stop(handle);
2771                         handle = NULL;
2772                 }
2773                 /* Submit prepared bio */
2774                 ext4_io_submit(&mpd.io_submit);
2775                 /* Unlock pages we didn't use */
2776                 mpage_release_unused_pages(&mpd, give_up_on_write);
2777                 /*
2778                  * Drop our io_end reference we got from init. We have
2779                  * to be careful and use deferred io_end finishing if
2780                  * we are still holding the transaction as we can
2781                  * release the last reference to io_end which may end
2782                  * up doing unwritten extent conversion.
2783                  */
2784                 if (handle) {
2785                         ext4_put_io_end_defer(mpd.io_submit.io_end);
2786                         ext4_journal_stop(handle);
2787                 } else
2788                         ext4_put_io_end(mpd.io_submit.io_end);
2789
2790                 if (ret == -ENOSPC && sbi->s_journal) {
2791                         /*
2792                          * Commit the transaction which would
2793                          * free blocks released in the transaction
2794                          * and try again
2795                          */
2796                         jbd2_journal_force_commit_nested(sbi->s_journal);
2797                         ret = 0;
2798                         continue;
2799                 }
2800                 /* Fatal error - ENOMEM, EIO... */
2801                 if (ret)
2802                         break;
2803         }
2804         blk_finish_plug(&plug);
2805         if (!ret && !cycled && wbc->nr_to_write > 0) {
2806                 cycled = 1;
2807                 mpd.last_page = writeback_index - 1;
2808                 mpd.first_page = 0;
2809                 goto retry;
2810         }
2811
2812         /* Update index */
2813         if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2814                 /*
2815                  * Set the writeback_index so that range_cyclic
2816                  * mode will write it back later
2817                  */
2818                 mapping->writeback_index = mpd.first_page;
2819
2820 out_writepages:
2821         trace_ext4_writepages_result(inode, wbc, ret,
2822                                      nr_to_write - wbc->nr_to_write);
2823         percpu_up_read(&sbi->s_journal_flag_rwsem);
2824         return ret;
2825 }
2826
2827 static int ext4_nonda_switch(struct super_block *sb)
2828 {
2829         s64 free_clusters, dirty_clusters;
2830         struct ext4_sb_info *sbi = EXT4_SB(sb);
2831
2832         /*
2833          * switch to non delalloc mode if we are running low
2834          * on free block. The free block accounting via percpu
2835          * counters can get slightly wrong with percpu_counter_batch getting
2836          * accumulated on each CPU without updating global counters
2837          * Delalloc need an accurate free block accounting. So switch
2838          * to non delalloc when we are near to error range.
2839          */
2840         free_clusters =
2841                 percpu_counter_read_positive(&sbi->s_freeclusters_counter);
2842         dirty_clusters =
2843                 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2844         /*
2845          * Start pushing delalloc when 1/2 of free blocks are dirty.
2846          */
2847         if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
2848                 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2849
2850         if (2 * free_clusters < 3 * dirty_clusters ||
2851             free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
2852                 /*
2853                  * free block count is less than 150% of dirty blocks
2854                  * or free blocks is less than watermark
2855                  */
2856                 return 1;
2857         }
2858         return 0;
2859 }
2860
2861 /* We always reserve for an inode update; the superblock could be there too */
2862 static int ext4_da_write_credits(struct inode *inode, loff_t pos, unsigned len)
2863 {
2864         if (likely(ext4_has_feature_large_file(inode->i_sb)))
2865                 return 1;
2866
2867         if (pos + len <= 0x7fffffffULL)
2868                 return 1;
2869
2870         /* We might need to update the superblock to set LARGE_FILE */
2871         return 2;
2872 }
2873
2874 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2875                                loff_t pos, unsigned len, unsigned flags,
2876                                struct page **pagep, void **fsdata)
2877 {
2878         int ret, retries = 0;
2879         struct page *page;
2880         pgoff_t index;
2881         struct inode *inode = mapping->host;
2882         handle_t *handle;
2883
2884         index = pos >> PAGE_SHIFT;
2885
2886         if (ext4_nonda_switch(inode->i_sb)) {
2887                 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2888                 return ext4_write_begin(file, mapping, pos,
2889                                         len, flags, pagep, fsdata);
2890         }
2891         *fsdata = (void *)0;
2892         trace_ext4_da_write_begin(inode, pos, len, flags);
2893
2894         if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2895                 ret = ext4_da_write_inline_data_begin(mapping, inode,
2896                                                       pos, len, flags,
2897                                                       pagep, fsdata);
2898                 if (ret < 0)
2899                         return ret;
2900                 if (ret == 1)
2901                         return 0;
2902         }
2903
2904         /*
2905          * grab_cache_page_write_begin() can take a long time if the
2906          * system is thrashing due to memory pressure, or if the page
2907          * is being written back.  So grab it first before we start
2908          * the transaction handle.  This also allows us to allocate
2909          * the page (if needed) without using GFP_NOFS.
2910          */
2911 retry_grab:
2912         page = grab_cache_page_write_begin(mapping, index, flags);
2913         if (!page)
2914                 return -ENOMEM;
2915         unlock_page(page);
2916
2917         /*
2918          * With delayed allocation, we don't log the i_disksize update
2919          * if there is delayed block allocation. But we still need
2920          * to journalling the i_disksize update if writes to the end
2921          * of file which has an already mapped buffer.
2922          */
2923 retry_journal:
2924         handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
2925                                 ext4_da_write_credits(inode, pos, len));
2926         if (IS_ERR(handle)) {
2927                 put_page(page);
2928                 return PTR_ERR(handle);
2929         }
2930
2931         lock_page(page);
2932         if (page->mapping != mapping) {
2933                 /* The page got truncated from under us */
2934                 unlock_page(page);
2935                 put_page(page);
2936                 ext4_journal_stop(handle);
2937                 goto retry_grab;
2938         }
2939         /* In case writeback began while the page was unlocked */
2940         wait_for_stable_page(page);
2941
2942 #ifdef CONFIG_EXT4_FS_ENCRYPTION
2943         ret = ext4_block_write_begin(page, pos, len,
2944                                      ext4_da_get_block_prep);
2945 #else
2946         ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
2947 #endif
2948         if (ret < 0) {
2949                 unlock_page(page);
2950                 ext4_journal_stop(handle);
2951                 /*
2952                  * block_write_begin may have instantiated a few blocks
2953                  * outside i_size.  Trim these off again. Don't need
2954                  * i_size_read because we hold i_mutex.
2955                  */
2956                 if (pos + len > inode->i_size)
2957                         ext4_truncate_failed_write(inode);
2958
2959                 if (ret == -ENOSPC &&
2960                     ext4_should_retry_alloc(inode->i_sb, &retries))
2961                         goto retry_journal;
2962
2963                 put_page(page);
2964                 return ret;
2965         }
2966
2967         *pagep = page;
2968         return ret;
2969 }
2970
2971 /*
2972  * Check if we should update i_disksize
2973  * when write to the end of file but not require block allocation
2974  */
2975 static int ext4_da_should_update_i_disksize(struct page *page,
2976                                             unsigned long offset)
2977 {
2978         struct buffer_head *bh;
2979         struct inode *inode = page->mapping->host;
2980         unsigned int idx;
2981         int i;
2982
2983         bh = page_buffers(page);
2984         idx = offset >> inode->i_blkbits;
2985
2986         for (i = 0; i < idx; i++)
2987                 bh = bh->b_this_page;
2988
2989         if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2990                 return 0;
2991         return 1;
2992 }
2993
2994 static int ext4_da_write_end(struct file *file,
2995                              struct address_space *mapping,
2996                              loff_t pos, unsigned len, unsigned copied,
2997                              struct page *page, void *fsdata)
2998 {
2999         struct inode *inode = mapping->host;
3000         int ret = 0, ret2;
3001         handle_t *handle = ext4_journal_current_handle();
3002         loff_t new_i_size;
3003         unsigned long start, end;
3004         int write_mode = (int)(unsigned long)fsdata;
3005
3006         if (write_mode == FALL_BACK_TO_NONDELALLOC)
3007                 return ext4_write_end(file, mapping, pos,
3008                                       len, copied, page, fsdata);
3009
3010         trace_ext4_da_write_end(inode, pos, len, copied);
3011         start = pos & (PAGE_SIZE - 1);
3012         end = start + copied - 1;
3013
3014         /*
3015          * generic_write_end() will run mark_inode_dirty() if i_size
3016          * changes.  So let's piggyback the i_disksize mark_inode_dirty
3017          * into that.
3018          */
3019         new_i_size = pos + copied;
3020         if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
3021                 if (ext4_has_inline_data(inode) ||
3022                     ext4_da_should_update_i_disksize(page, end)) {
3023                         ext4_update_i_disksize(inode, new_i_size);
3024                         /* We need to mark inode dirty even if
3025                          * new_i_size is less that inode->i_size
3026                          * bu greater than i_disksize.(hint delalloc)
3027                          */
3028                         ext4_mark_inode_dirty(handle, inode);
3029                 }
3030         }
3031
3032         if (write_mode != CONVERT_INLINE_DATA &&
3033             ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
3034             ext4_has_inline_data(inode))
3035                 ret2 = ext4_da_write_inline_data_end(inode, pos, len, copied,
3036                                                      page);
3037         else
3038                 ret2 = generic_write_end(file, mapping, pos, len, copied,
3039                                                         page, fsdata);
3040
3041         copied = ret2;
3042         if (ret2 < 0)
3043                 ret = ret2;
3044         ret2 = ext4_journal_stop(handle);
3045         if (!ret)
3046                 ret = ret2;
3047
3048         return ret ? ret : copied;
3049 }
3050
3051 static void ext4_da_invalidatepage(struct page *page, unsigned int offset,
3052                                    unsigned int length)
3053 {
3054         /*
3055          * Drop reserved blocks
3056          */
3057         BUG_ON(!PageLocked(page));
3058         if (!page_has_buffers(page))
3059                 goto out;
3060
3061         ext4_da_page_release_reservation(page, offset, length);
3062
3063 out:
3064         ext4_invalidatepage(page, offset, length);
3065
3066         return;
3067 }
3068
3069 /*
3070  * Force all delayed allocation blocks to be allocated for a given inode.
3071  */
3072 int ext4_alloc_da_blocks(struct inode *inode)
3073 {
3074         trace_ext4_alloc_da_blocks(inode);
3075
3076         if (!EXT4_I(inode)->i_reserved_data_blocks)
3077                 return 0;
3078
3079         /*
3080          * We do something simple for now.  The filemap_flush() will
3081          * also start triggering a write of the data blocks, which is
3082          * not strictly speaking necessary (and for users of
3083          * laptop_mode, not even desirable).  However, to do otherwise
3084          * would require replicating code paths in:
3085          *
3086          * ext4_writepages() ->
3087          *    write_cache_pages() ---> (via passed in callback function)
3088          *        __mpage_da_writepage() -->
3089          *           mpage_add_bh_to_extent()
3090          *           mpage_da_map_blocks()
3091          *
3092          * The problem is that write_cache_pages(), located in
3093          * mm/page-writeback.c, marks pages clean in preparation for
3094          * doing I/O, which is not desirable if we're not planning on
3095          * doing I/O at all.
3096          *
3097          * We could call write_cache_pages(), and then redirty all of
3098          * the pages by calling redirty_page_for_writepage() but that
3099          * would be ugly in the extreme.  So instead we would need to
3100          * replicate parts of the code in the above functions,
3101          * simplifying them because we wouldn't actually intend to
3102          * write out the pages, but rather only collect contiguous
3103          * logical block extents, call the multi-block allocator, and
3104          * then update the buffer heads with the block allocations.
3105          *
3106          * For now, though, we'll cheat by calling filemap_flush(),
3107          * which will map the blocks, and start the I/O, but not
3108          * actually wait for the I/O to complete.
3109          */
3110         return filemap_flush(inode->i_mapping);
3111 }
3112
3113 /*
3114  * bmap() is special.  It gets used by applications such as lilo and by
3115  * the swapper to find the on-disk block of a specific piece of data.
3116  *
3117  * Naturally, this is dangerous if the block concerned is still in the
3118  * journal.  If somebody makes a swapfile on an ext4 data-journaling
3119  * filesystem and enables swap, then they may get a nasty shock when the
3120  * data getting swapped to that swapfile suddenly gets overwritten by
3121  * the original zero's written out previously to the journal and
3122  * awaiting writeback in the kernel's buffer cache.
3123  *
3124  * So, if we see any bmap calls here on a modified, data-journaled file,
3125  * take extra steps to flush any blocks which might be in the cache.
3126  */
3127 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3128 {
3129         struct inode *inode = mapping->host;
3130         journal_t *journal;
3131         int err;
3132
3133         /*
3134          * We can get here for an inline file via the FIBMAP ioctl
3135          */
3136         if (ext4_has_inline_data(inode))
3137                 return 0;
3138
3139         if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3140                         test_opt(inode->i_sb, DELALLOC)) {
3141                 /*
3142                  * With delalloc we want to sync the file
3143                  * so that we can make sure we allocate
3144                  * blocks for file
3145                  */
3146                 filemap_write_and_wait(mapping);
3147         }
3148
3149         if (EXT4_JOURNAL(inode) &&
3150             ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3151                 /*
3152                  * This is a REALLY heavyweight approach, but the use of
3153                  * bmap on dirty files is expected to be extremely rare:
3154                  * only if we run lilo or swapon on a freshly made file
3155                  * do we expect this to happen.
3156                  *
3157                  * (bmap requires CAP_SYS_RAWIO so this does not
3158                  * represent an unprivileged user DOS attack --- we'd be
3159                  * in trouble if mortal users could trigger this path at
3160                  * will.)
3161                  *
3162                  * NB. EXT4_STATE_JDATA is not set on files other than
3163                  * regular files.  If somebody wants to bmap a directory
3164                  * or symlink and gets confused because the buffer
3165                  * hasn't yet been flushed to disk, they deserve
3166                  * everything they get.
3167                  */
3168
3169                 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3170                 journal = EXT4_JOURNAL(inode);
3171                 jbd2_journal_lock_updates(journal);
3172                 err = jbd2_journal_flush(journal);
3173                 jbd2_journal_unlock_updates(journal);
3174
3175                 if (err)
3176                         return 0;
3177         }
3178
3179         return generic_block_bmap(mapping, block, ext4_get_block);
3180 }
3181
3182 static int ext4_readpage(struct file *file, struct page *page)
3183 {
3184         int ret = -EAGAIN;
3185         struct inode *inode = page->mapping->host;
3186
3187         trace_ext4_readpage(page);
3188
3189         if (ext4_has_inline_data(inode))
3190                 ret = ext4_readpage_inline(inode, page);
3191
3192         if (ret == -EAGAIN)
3193                 return ext4_mpage_readpages(page->mapping, NULL, page, 1);
3194
3195         return ret;
3196 }
3197
3198 static int
3199 ext4_readpages(struct file *file, struct address_space *mapping,
3200                 struct list_head *pages, unsigned nr_pages)
3201 {
3202         struct inode *inode = mapping->host;
3203
3204         /* If the file has inline data, no need to do readpages. */
3205         if (ext4_has_inline_data(inode))
3206                 return 0;
3207
3208         return ext4_mpage_readpages(mapping, pages, NULL, nr_pages);
3209 }
3210
3211 static void ext4_invalidatepage(struct page *page, unsigned int offset,
3212                                 unsigned int length)
3213 {
3214         trace_ext4_invalidatepage(page, offset, length);
3215
3216         /* No journalling happens on data buffers when this function is used */
3217         WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
3218
3219         block_invalidatepage(page, offset, length);
3220 }
3221
3222 static int __ext4_journalled_invalidatepage(struct page *page,
3223                                             unsigned int offset,
3224                                             unsigned int length)
3225 {
3226         journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3227
3228         trace_ext4_journalled_invalidatepage(page, offset, length);
3229
3230         /*
3231          * If it's a full truncate we just forget about the pending dirtying
3232          */
3233         if (offset == 0 && length == PAGE_SIZE)
3234                 ClearPageChecked(page);
3235
3236         return jbd2_journal_invalidatepage(journal, page, offset, length);
3237 }
3238
3239 /* Wrapper for aops... */
3240 static void ext4_journalled_invalidatepage(struct page *page,
3241                                            unsigned int offset,
3242                                            unsigned int length)
3243 {
3244         WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
3245 }
3246
3247 static int ext4_releasepage(struct page *page, gfp_t wait)
3248 {
3249         journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3250
3251         trace_ext4_releasepage(page);
3252
3253         /* Page has dirty journalled data -> cannot release */
3254         if (PageChecked(page))
3255                 return 0;
3256         if (journal)
3257                 return jbd2_journal_try_to_free_buffers(journal, page, wait);
3258         else
3259                 return try_to_free_buffers(page);
3260 }
3261
3262 #ifdef CONFIG_FS_DAX
3263 /*
3264  * Get block function for DAX IO and mmap faults. It takes care of converting
3265  * unwritten extents to written ones and initializes new / converted blocks
3266  * to zeros.
3267  */
3268 int ext4_dax_get_block(struct inode *inode, sector_t iblock,
3269                        struct buffer_head *bh_result, int create)
3270 {
3271         int ret;
3272
3273         ext4_debug("inode %lu, create flag %d\n", inode->i_ino, create);
3274         if (!create)
3275                 return _ext4_get_block(inode, iblock, bh_result, 0);
3276
3277         ret = ext4_get_block_trans(inode, iblock, bh_result,
3278                                    EXT4_GET_BLOCKS_PRE_IO |
3279                                    EXT4_GET_BLOCKS_CREATE_ZERO);
3280         if (ret < 0)
3281                 return ret;
3282
3283         if (buffer_unwritten(bh_result)) {
3284                 /*
3285                  * We are protected by i_mmap_sem or i_mutex so we know block
3286                  * cannot go away from under us even though we dropped
3287                  * i_data_sem. Convert extent to written and write zeros there.
3288                  */
3289                 ret = ext4_get_block_trans(inode, iblock, bh_result,
3290                                            EXT4_GET_BLOCKS_CONVERT |
3291                                            EXT4_GET_BLOCKS_CREATE_ZERO);
3292                 if (ret < 0)
3293                         return ret;
3294         }
3295         /*
3296          * At least for now we have to clear BH_New so that DAX code
3297          * doesn't attempt to zero blocks again in a racy way.
3298          */
3299         clear_buffer_new(bh_result);
3300         return 0;
3301 }
3302 #else
3303 /* Just define empty function, it will never get called. */
3304 int ext4_dax_get_block(struct inode *inode, sector_t iblock,
3305                        struct buffer_head *bh_result, int create)
3306 {
3307         BUG();
3308         return 0;
3309 }
3310 #endif
3311
3312 static int ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
3313                             ssize_t size, void *private)
3314 {
3315         ext4_io_end_t *io_end = private;
3316
3317         /* if not async direct IO just return */
3318         if (!io_end)
3319                 return 0;
3320
3321         ext_debug("ext4_end_io_dio(): io_end 0x%p "
3322                   "for inode %lu, iocb 0x%p, offset %llu, size %zd\n",
3323                   io_end, io_end->inode->i_ino, iocb, offset, size);
3324
3325         /*
3326          * Error during AIO DIO. We cannot convert unwritten extents as the
3327          * data was not written. Just clear the unwritten flag and drop io_end.
3328          */
3329         if (size <= 0) {
3330                 ext4_clear_io_unwritten_flag(io_end);
3331                 size = 0;
3332         }
3333         io_end->offset = offset;
3334         io_end->size = size;
3335         ext4_put_io_end(io_end);
3336
3337         return 0;
3338 }
3339
3340 /*
3341  * Handling of direct IO writes.
3342  *
3343  * For ext4 extent files, ext4 will do direct-io write even to holes,
3344  * preallocated extents, and those write extend the file, no need to
3345  * fall back to buffered IO.
3346  *
3347  * For holes, we fallocate those blocks, mark them as unwritten
3348  * If those blocks were preallocated, we mark sure they are split, but
3349  * still keep the range to write as unwritten.
3350  *
3351  * The unwritten extents will be converted to written when DIO is completed.
3352  * For async direct IO, since the IO may still pending when return, we
3353  * set up an end_io call back function, which will do the conversion
3354  * when async direct IO completed.
3355  *
3356  * If the O_DIRECT write will extend the file then add this inode to the
3357  * orphan list.  So recovery will truncate it back to the original size
3358  * if the machine crashes during the write.
3359  *
3360  */
3361 static ssize_t ext4_direct_IO_write(struct kiocb *iocb, struct iov_iter *iter)
3362 {
3363         struct file *file = iocb->ki_filp;
3364         struct inode *inode = file->f_mapping->host;
3365         struct ext4_inode_info *ei = EXT4_I(inode);
3366         ssize_t ret;
3367         loff_t offset = iocb->ki_pos;
3368         size_t count = iov_iter_count(iter);
3369         int overwrite = 0;
3370         get_block_t *get_block_func = NULL;
3371         int dio_flags = 0;
3372         loff_t final_size = offset + count;
3373         int orphan = 0;
3374         handle_t *handle;
3375
3376         if (final_size > inode->i_size) {
3377                 /* Credits for sb + inode write */
3378                 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
3379                 if (IS_ERR(handle)) {
3380                         ret = PTR_ERR(handle);
3381                         goto out;
3382                 }
3383                 ret = ext4_orphan_add(handle, inode);
3384                 if (ret) {
3385                         ext4_journal_stop(handle);
3386                         goto out;
3387                 }
3388                 orphan = 1;
3389                 ei->i_disksize = inode->i_size;
3390                 ext4_journal_stop(handle);
3391         }
3392
3393         BUG_ON(iocb->private == NULL);
3394
3395         /*
3396          * Make all waiters for direct IO properly wait also for extent
3397          * conversion. This also disallows race between truncate() and
3398          * overwrite DIO as i_dio_count needs to be incremented under i_mutex.
3399          */
3400         inode_dio_begin(inode);
3401
3402         /* If we do a overwrite dio, i_mutex locking can be released */
3403         overwrite = *((int *)iocb->private);
3404
3405         if (overwrite)
3406                 inode_unlock(inode);
3407
3408         /*
3409          * For extent mapped files we could direct write to holes and fallocate.
3410          *
3411          * Allocated blocks to fill the hole are marked as unwritten to prevent
3412          * parallel buffered read to expose the stale data before DIO complete
3413          * the data IO.
3414          *
3415          * As to previously fallocated extents, ext4 get_block will just simply
3416          * mark the buffer mapped but still keep the extents unwritten.
3417          *
3418          * For non AIO case, we will convert those unwritten extents to written
3419          * after return back from blockdev_direct_IO. That way we save us from
3420          * allocating io_end structure and also the overhead of offloading
3421          * the extent convertion to a workqueue.
3422          *
3423          * For async DIO, the conversion needs to be deferred when the
3424          * IO is completed. The ext4 end_io callback function will be
3425          * called to take care of the conversion work.  Here for async
3426          * case, we allocate an io_end structure to hook to the iocb.
3427          */
3428         iocb->private = NULL;
3429         if (overwrite)
3430                 get_block_func = ext4_dio_get_block_overwrite;
3431         else if (IS_DAX(inode)) {
3432                 /*
3433                  * We can avoid zeroing for aligned DAX writes beyond&