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