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