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