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