Merge branch 'for_linus' of git://git.kernel.org/pub/scm/linux/kernel/git/jack/linux-fs
[linux-2.6-block.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                                 /*
1342                                  * skip page if block allocation undone and
1343                                  * block is dirty
1344                                  */
1345                                 if (ext4_bh_delay_or_unwritten(NULL, bh))
1346                                         skip_page = 1;
1347                                 bh = bh->b_this_page;
1348                                 block_start += bh->b_size;
1349                                 cur_logical++;
1350                                 pblock++;
1351                         } while (bh != page_bufs);
1352
1353                         if (skip_page)
1354                                 goto skip_page;
1355
1356                         if (commit_write)
1357                                 /* mark the buffer_heads as dirty & uptodate */
1358                                 block_commit_write(page, 0, len);
1359
1360                         clear_page_dirty_for_io(page);
1361                         /*
1362                          * Delalloc doesn't support data journalling,
1363                          * but eventually maybe we'll lift this
1364                          * restriction.
1365                          */
1366                         if (unlikely(journal_data && PageChecked(page)))
1367                                 err = __ext4_journalled_writepage(page, len);
1368                         else if (test_opt(inode->i_sb, MBLK_IO_SUBMIT))
1369                                 err = ext4_bio_write_page(&io_submit, page,
1370                                                           len, mpd->wbc);
1371                         else if (buffer_uninit(page_bufs)) {
1372                                 ext4_set_bh_endio(page_bufs, inode);
1373                                 err = block_write_full_page_endio(page,
1374                                         noalloc_get_block_write,
1375                                         mpd->wbc, ext4_end_io_buffer_write);
1376                         } else
1377                                 err = block_write_full_page(page,
1378                                         noalloc_get_block_write, mpd->wbc);
1379
1380                         if (!err)
1381                                 mpd->pages_written++;
1382                         /*
1383                          * In error case, we have to continue because
1384                          * remaining pages are still locked
1385                          */
1386                         if (ret == 0)
1387                                 ret = err;
1388                 }
1389                 pagevec_release(&pvec);
1390         }
1391         ext4_io_submit(&io_submit);
1392         return ret;
1393 }
1394
1395 static void ext4_da_block_invalidatepages(struct mpage_da_data *mpd)
1396 {
1397         int nr_pages, i;
1398         pgoff_t index, end;
1399         struct pagevec pvec;
1400         struct inode *inode = mpd->inode;
1401         struct address_space *mapping = inode->i_mapping;
1402
1403         index = mpd->first_page;
1404         end   = mpd->next_page - 1;
1405         while (index <= end) {
1406                 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1407                 if (nr_pages == 0)
1408                         break;
1409                 for (i = 0; i < nr_pages; i++) {
1410                         struct page *page = pvec.pages[i];
1411                         if (page->index > end)
1412                                 break;
1413                         BUG_ON(!PageLocked(page));
1414                         BUG_ON(PageWriteback(page));
1415                         block_invalidatepage(page, 0);
1416                         ClearPageUptodate(page);
1417                         unlock_page(page);
1418                 }
1419                 index = pvec.pages[nr_pages - 1]->index + 1;
1420                 pagevec_release(&pvec);
1421         }
1422         return;
1423 }
1424
1425 static void ext4_print_free_blocks(struct inode *inode)
1426 {
1427         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1428         printk(KERN_CRIT "Total free blocks count %lld\n",
1429                EXT4_C2B(EXT4_SB(inode->i_sb),
1430                         ext4_count_free_clusters(inode->i_sb)));
1431         printk(KERN_CRIT "Free/Dirty block details\n");
1432         printk(KERN_CRIT "free_blocks=%lld\n",
1433                (long long) EXT4_C2B(EXT4_SB(inode->i_sb),
1434                 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1435         printk(KERN_CRIT "dirty_blocks=%lld\n",
1436                (long long) EXT4_C2B(EXT4_SB(inode->i_sb),
1437                 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1438         printk(KERN_CRIT "Block reservation details\n");
1439         printk(KERN_CRIT "i_reserved_data_blocks=%u\n",
1440                EXT4_I(inode)->i_reserved_data_blocks);
1441         printk(KERN_CRIT "i_reserved_meta_blocks=%u\n",
1442                EXT4_I(inode)->i_reserved_meta_blocks);
1443         return;
1444 }
1445
1446 /*
1447  * mpage_da_map_and_submit - go through given space, map them
1448  *       if necessary, and then submit them for I/O
1449  *
1450  * @mpd - bh describing space
1451  *
1452  * The function skips space we know is already mapped to disk blocks.
1453  *
1454  */
1455 static void mpage_da_map_and_submit(struct mpage_da_data *mpd)
1456 {
1457         int err, blks, get_blocks_flags;
1458         struct ext4_map_blocks map, *mapp = NULL;
1459         sector_t next = mpd->b_blocknr;
1460         unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits;
1461         loff_t disksize = EXT4_I(mpd->inode)->i_disksize;
1462         handle_t *handle = NULL;
1463
1464         /*
1465          * If the blocks are mapped already, or we couldn't accumulate
1466          * any blocks, then proceed immediately to the submission stage.
1467          */
1468         if ((mpd->b_size == 0) ||
1469             ((mpd->b_state  & (1 << BH_Mapped)) &&
1470              !(mpd->b_state & (1 << BH_Delay)) &&
1471              !(mpd->b_state & (1 << BH_Unwritten))))
1472                 goto submit_io;
1473
1474         handle = ext4_journal_current_handle();
1475         BUG_ON(!handle);
1476
1477         /*
1478          * Call ext4_map_blocks() to allocate any delayed allocation
1479          * blocks, or to convert an uninitialized extent to be
1480          * initialized (in the case where we have written into
1481          * one or more preallocated blocks).
1482          *
1483          * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to
1484          * indicate that we are on the delayed allocation path.  This
1485          * affects functions in many different parts of the allocation
1486          * call path.  This flag exists primarily because we don't
1487          * want to change *many* call functions, so ext4_map_blocks()
1488          * will set the EXT4_STATE_DELALLOC_RESERVED flag once the
1489          * inode's allocation semaphore is taken.
1490          *
1491          * If the blocks in questions were delalloc blocks, set
1492          * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting
1493          * variables are updated after the blocks have been allocated.
1494          */
1495         map.m_lblk = next;
1496         map.m_len = max_blocks;
1497         get_blocks_flags = EXT4_GET_BLOCKS_CREATE;
1498         if (ext4_should_dioread_nolock(mpd->inode))
1499                 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
1500         if (mpd->b_state & (1 << BH_Delay))
1501                 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
1502
1503         blks = ext4_map_blocks(handle, mpd->inode, &map, get_blocks_flags);
1504         if (blks < 0) {
1505                 struct super_block *sb = mpd->inode->i_sb;
1506
1507                 err = blks;
1508                 /*
1509                  * If get block returns EAGAIN or ENOSPC and there
1510                  * appears to be free blocks we will just let
1511                  * mpage_da_submit_io() unlock all of the pages.
1512                  */
1513                 if (err == -EAGAIN)
1514                         goto submit_io;
1515
1516                 if (err == -ENOSPC && ext4_count_free_clusters(sb)) {
1517                         mpd->retval = err;
1518                         goto submit_io;
1519                 }
1520
1521                 /*
1522                  * get block failure will cause us to loop in
1523                  * writepages, because a_ops->writepage won't be able
1524                  * to make progress. The page will be redirtied by
1525                  * writepage and writepages will again try to write
1526                  * the same.
1527                  */
1528                 if (!(EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)) {
1529                         ext4_msg(sb, KERN_CRIT,
1530                                  "delayed block allocation failed for inode %lu "
1531                                  "at logical offset %llu with max blocks %zd "
1532                                  "with error %d", mpd->inode->i_ino,
1533                                  (unsigned long long) next,
1534                                  mpd->b_size >> mpd->inode->i_blkbits, err);
1535                         ext4_msg(sb, KERN_CRIT,
1536                                 "This should not happen!! Data will be lost\n");
1537                         if (err == -ENOSPC)
1538                                 ext4_print_free_blocks(mpd->inode);
1539                 }
1540                 /* invalidate all the pages */
1541                 ext4_da_block_invalidatepages(mpd);
1542
1543                 /* Mark this page range as having been completed */
1544                 mpd->io_done = 1;
1545                 return;
1546         }
1547         BUG_ON(blks == 0);
1548
1549         mapp = &map;
1550         if (map.m_flags & EXT4_MAP_NEW) {
1551                 struct block_device *bdev = mpd->inode->i_sb->s_bdev;
1552                 int i;
1553
1554                 for (i = 0; i < map.m_len; i++)
1555                         unmap_underlying_metadata(bdev, map.m_pblk + i);
1556
1557                 if (ext4_should_order_data(mpd->inode)) {
1558                         err = ext4_jbd2_file_inode(handle, mpd->inode);
1559                         if (err) {
1560                                 /* Only if the journal is aborted */
1561                                 mpd->retval = err;
1562                                 goto submit_io;
1563                         }
1564                 }
1565         }
1566
1567         /*
1568          * Update on-disk size along with block allocation.
1569          */
1570         disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits;
1571         if (disksize > i_size_read(mpd->inode))
1572                 disksize = i_size_read(mpd->inode);
1573         if (disksize > EXT4_I(mpd->inode)->i_disksize) {
1574                 ext4_update_i_disksize(mpd->inode, disksize);
1575                 err = ext4_mark_inode_dirty(handle, mpd->inode);
1576                 if (err)
1577                         ext4_error(mpd->inode->i_sb,
1578                                    "Failed to mark inode %lu dirty",
1579                                    mpd->inode->i_ino);
1580         }
1581
1582 submit_io:
1583         mpage_da_submit_io(mpd, mapp);
1584         mpd->io_done = 1;
1585 }
1586
1587 #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
1588                 (1 << BH_Delay) | (1 << BH_Unwritten))
1589
1590 /*
1591  * mpage_add_bh_to_extent - try to add one more block to extent of blocks
1592  *
1593  * @mpd->lbh - extent of blocks
1594  * @logical - logical number of the block in the file
1595  * @bh - bh of the block (used to access block's state)
1596  *
1597  * the function is used to collect contig. blocks in same state
1598  */
1599 static void mpage_add_bh_to_extent(struct mpage_da_data *mpd,
1600                                    sector_t logical, size_t b_size,
1601                                    unsigned long b_state)
1602 {
1603         sector_t next;
1604         int nrblocks = mpd->b_size >> mpd->inode->i_blkbits;
1605
1606         /*
1607          * XXX Don't go larger than mballoc is willing to allocate
1608          * This is a stopgap solution.  We eventually need to fold
1609          * mpage_da_submit_io() into this function and then call
1610          * ext4_map_blocks() multiple times in a loop
1611          */
1612         if (nrblocks >= 8*1024*1024/mpd->inode->i_sb->s_blocksize)
1613                 goto flush_it;
1614
1615         /* check if thereserved journal credits might overflow */
1616         if (!(ext4_test_inode_flag(mpd->inode, EXT4_INODE_EXTENTS))) {
1617                 if (nrblocks >= EXT4_MAX_TRANS_DATA) {
1618                         /*
1619                          * With non-extent format we are limited by the journal
1620                          * credit available.  Total credit needed to insert
1621                          * nrblocks contiguous blocks is dependent on the
1622                          * nrblocks.  So limit nrblocks.
1623                          */
1624                         goto flush_it;
1625                 } else if ((nrblocks + (b_size >> mpd->inode->i_blkbits)) >
1626                                 EXT4_MAX_TRANS_DATA) {
1627                         /*
1628                          * Adding the new buffer_head would make it cross the
1629                          * allowed limit for which we have journal credit
1630                          * reserved. So limit the new bh->b_size
1631                          */
1632                         b_size = (EXT4_MAX_TRANS_DATA - nrblocks) <<
1633                                                 mpd->inode->i_blkbits;
1634                         /* we will do mpage_da_submit_io in the next loop */
1635                 }
1636         }
1637         /*
1638          * First block in the extent
1639          */
1640         if (mpd->b_size == 0) {
1641                 mpd->b_blocknr = logical;
1642                 mpd->b_size = b_size;
1643                 mpd->b_state = b_state & BH_FLAGS;
1644                 return;
1645         }
1646
1647         next = mpd->b_blocknr + nrblocks;
1648         /*
1649          * Can we merge the block to our big extent?
1650          */
1651         if (logical == next && (b_state & BH_FLAGS) == mpd->b_state) {
1652                 mpd->b_size += b_size;
1653                 return;
1654         }
1655
1656 flush_it:
1657         /*
1658          * We couldn't merge the block to our extent, so we
1659          * need to flush current  extent and start new one
1660          */
1661         mpage_da_map_and_submit(mpd);
1662         return;
1663 }
1664
1665 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1666 {
1667         return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1668 }
1669
1670 /*
1671  * This function is grabs code from the very beginning of
1672  * ext4_map_blocks, but assumes that the caller is from delayed write
1673  * time. This function looks up the requested blocks and sets the
1674  * buffer delay bit under the protection of i_data_sem.
1675  */
1676 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1677                               struct ext4_map_blocks *map,
1678                               struct buffer_head *bh)
1679 {
1680         int retval;
1681         sector_t invalid_block = ~((sector_t) 0xffff);
1682
1683         if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1684                 invalid_block = ~0;
1685
1686         map->m_flags = 0;
1687         ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
1688                   "logical block %lu\n", inode->i_ino, map->m_len,
1689                   (unsigned long) map->m_lblk);
1690         /*
1691          * Try to see if we can get the block without requesting a new
1692          * file system block.
1693          */
1694         down_read((&EXT4_I(inode)->i_data_sem));
1695         if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1696                 retval = ext4_ext_map_blocks(NULL, inode, map, 0);
1697         else
1698                 retval = ext4_ind_map_blocks(NULL, inode, map, 0);
1699
1700         if (retval == 0) {
1701                 /*
1702                  * XXX: __block_prepare_write() unmaps passed block,
1703                  * is it OK?
1704                  */
1705                 /* If the block was allocated from previously allocated cluster,
1706                  * then we dont need to reserve it again. */
1707                 if (!(map->m_flags & EXT4_MAP_FROM_CLUSTER)) {
1708                         retval = ext4_da_reserve_space(inode, iblock);
1709                         if (retval)
1710                                 /* not enough space to reserve */
1711                                 goto out_unlock;
1712                 }
1713
1714                 /* Clear EXT4_MAP_FROM_CLUSTER flag since its purpose is served
1715                  * and it should not appear on the bh->b_state.
1716                  */
1717                 map->m_flags &= ~EXT4_MAP_FROM_CLUSTER;
1718
1719                 map_bh(bh, inode->i_sb, invalid_block);
1720                 set_buffer_new(bh);
1721                 set_buffer_delay(bh);
1722         }
1723
1724 out_unlock:
1725         up_read((&EXT4_I(inode)->i_data_sem));
1726
1727         return retval;
1728 }
1729
1730 /*
1731  * This is a special get_blocks_t callback which is used by
1732  * ext4_da_write_begin().  It will either return mapped block or
1733  * reserve space for a single block.
1734  *
1735  * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1736  * We also have b_blocknr = -1 and b_bdev initialized properly
1737  *
1738  * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1739  * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1740  * initialized properly.
1741  */
1742 static int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1743                                   struct buffer_head *bh, int create)
1744 {
1745         struct ext4_map_blocks map;
1746         int ret = 0;
1747
1748         BUG_ON(create == 0);
1749         BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1750
1751         map.m_lblk = iblock;
1752         map.m_len = 1;
1753
1754         /*
1755          * first, we need to know whether the block is allocated already
1756          * preallocated blocks are unmapped but should treated
1757          * the same as allocated blocks.
1758          */
1759         ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1760         if (ret <= 0)
1761                 return ret;
1762
1763         map_bh(bh, inode->i_sb, map.m_pblk);
1764         bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
1765
1766         if (buffer_unwritten(bh)) {
1767                 /* A delayed write to unwritten bh should be marked
1768                  * new and mapped.  Mapped ensures that we don't do
1769                  * get_block multiple times when we write to the same
1770                  * offset and new ensures that we do proper zero out
1771                  * for partial write.
1772                  */
1773                 set_buffer_new(bh);
1774                 set_buffer_mapped(bh);
1775         }
1776         return 0;
1777 }
1778
1779 /*
1780  * This function is used as a standard get_block_t calback function
1781  * when there is no desire to allocate any blocks.  It is used as a
1782  * callback function for block_write_begin() and block_write_full_page().
1783  * These functions should only try to map a single block at a time.
1784  *
1785  * Since this function doesn't do block allocations even if the caller
1786  * requests it by passing in create=1, it is critically important that
1787  * any caller checks to make sure that any buffer heads are returned
1788  * by this function are either all already mapped or marked for
1789  * delayed allocation before calling  block_write_full_page().  Otherwise,
1790  * b_blocknr could be left unitialized, and the page write functions will
1791  * be taken by surprise.
1792  */
1793 static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
1794                                    struct buffer_head *bh_result, int create)
1795 {
1796         BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
1797         return _ext4_get_block(inode, iblock, bh_result, 0);
1798 }
1799
1800 static int bget_one(handle_t *handle, struct buffer_head *bh)
1801 {
1802         get_bh(bh);
1803         return 0;
1804 }
1805
1806 static int bput_one(handle_t *handle, struct buffer_head *bh)
1807 {
1808         put_bh(bh);
1809         return 0;
1810 }
1811
1812 static int __ext4_journalled_writepage(struct page *page,
1813                                        unsigned int len)
1814 {
1815         struct address_space *mapping = page->mapping;
1816         struct inode *inode = mapping->host;
1817         struct buffer_head *page_bufs;
1818         handle_t *handle = NULL;
1819         int ret = 0;
1820         int err;
1821
1822         ClearPageChecked(page);
1823         page_bufs = page_buffers(page);
1824         BUG_ON(!page_bufs);
1825         walk_page_buffers(handle, page_bufs, 0, len, NULL, bget_one);
1826         /* As soon as we unlock the page, it can go away, but we have
1827          * references to buffers so we are safe */
1828         unlock_page(page);
1829
1830         handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
1831         if (IS_ERR(handle)) {
1832                 ret = PTR_ERR(handle);
1833                 goto out;
1834         }
1835
1836         BUG_ON(!ext4_handle_valid(handle));
1837
1838         ret = walk_page_buffers(handle, page_bufs, 0, len, NULL,
1839                                 do_journal_get_write_access);
1840
1841         err = walk_page_buffers(handle, page_bufs, 0, len, NULL,
1842                                 write_end_fn);
1843         if (ret == 0)
1844                 ret = err;
1845         EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1846         err = ext4_journal_stop(handle);
1847         if (!ret)
1848                 ret = err;
1849
1850         walk_page_buffers(handle, page_bufs, 0, len, NULL, bput_one);
1851         ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1852 out:
1853         return ret;
1854 }
1855
1856 static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode);
1857 static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate);
1858
1859 /*
1860  * Note that we don't need to start a transaction unless we're journaling data
1861  * because we should have holes filled from ext4_page_mkwrite(). We even don't
1862  * need to file the inode to the transaction's list in ordered mode because if
1863  * we are writing back data added by write(), the inode is already there and if
1864  * we are writing back data modified via mmap(), no one guarantees in which
1865  * transaction the data will hit the disk. In case we are journaling data, we
1866  * cannot start transaction directly because transaction start ranks above page
1867  * lock so we have to do some magic.
1868  *
1869  * This function can get called via...
1870  *   - ext4_da_writepages after taking page lock (have journal handle)
1871  *   - journal_submit_inode_data_buffers (no journal handle)
1872  *   - shrink_page_list via pdflush (no journal handle)
1873  *   - grab_page_cache when doing write_begin (have journal handle)
1874  *
1875  * We don't do any block allocation in this function. If we have page with
1876  * multiple blocks we need to write those buffer_heads that are mapped. This
1877  * is important for mmaped based write. So if we do with blocksize 1K
1878  * truncate(f, 1024);
1879  * a = mmap(f, 0, 4096);
1880  * a[0] = 'a';
1881  * truncate(f, 4096);
1882  * we have in the page first buffer_head mapped via page_mkwrite call back
1883  * but other buffer_heads would be unmapped but dirty (dirty done via the
1884  * do_wp_page). So writepage should write the first block. If we modify
1885  * the mmap area beyond 1024 we will again get a page_fault and the
1886  * page_mkwrite callback will do the block allocation and mark the
1887  * buffer_heads mapped.
1888  *
1889  * We redirty the page if we have any buffer_heads that is either delay or
1890  * unwritten in the page.
1891  *
1892  * We can get recursively called as show below.
1893  *
1894  *      ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
1895  *              ext4_writepage()
1896  *
1897  * But since we don't do any block allocation we should not deadlock.
1898  * Page also have the dirty flag cleared so we don't get recurive page_lock.
1899  */
1900 static int ext4_writepage(struct page *page,
1901                           struct writeback_control *wbc)
1902 {
1903         int ret = 0, commit_write = 0;
1904         loff_t size;
1905         unsigned int len;
1906         struct buffer_head *page_bufs = NULL;
1907         struct inode *inode = page->mapping->host;
1908
1909         trace_ext4_writepage(page);
1910         size = i_size_read(inode);
1911         if (page->index == size >> PAGE_CACHE_SHIFT)
1912                 len = size & ~PAGE_CACHE_MASK;
1913         else
1914                 len = PAGE_CACHE_SIZE;
1915
1916         /*
1917          * If the page does not have buffers (for whatever reason),
1918          * try to create them using __block_write_begin.  If this
1919          * fails, redirty the page and move on.
1920          */
1921         if (!page_has_buffers(page)) {
1922                 if (__block_write_begin(page, 0, len,
1923                                         noalloc_get_block_write)) {
1924                 redirty_page:
1925                         redirty_page_for_writepage(wbc, page);
1926                         unlock_page(page);
1927                         return 0;
1928                 }
1929                 commit_write = 1;
1930         }
1931         page_bufs = page_buffers(page);
1932         if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
1933                               ext4_bh_delay_or_unwritten)) {
1934                 /*
1935                  * We don't want to do block allocation, so redirty
1936                  * the page and return.  We may reach here when we do
1937                  * a journal commit via journal_submit_inode_data_buffers.
1938                  * We can also reach here via shrink_page_list but it
1939                  * should never be for direct reclaim so warn if that
1940                  * happens
1941                  */
1942                 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD)) ==
1943                                                                 PF_MEMALLOC);
1944                 goto redirty_page;
1945         }
1946         if (commit_write)
1947                 /* now mark the buffer_heads as dirty and uptodate */
1948                 block_commit_write(page, 0, len);
1949
1950         if (PageChecked(page) && ext4_should_journal_data(inode))
1951                 /*
1952                  * It's mmapped pagecache.  Add buffers and journal it.  There
1953                  * doesn't seem much point in redirtying the page here.
1954                  */
1955                 return __ext4_journalled_writepage(page, len);
1956
1957         if (buffer_uninit(page_bufs)) {
1958                 ext4_set_bh_endio(page_bufs, inode);
1959                 ret = block_write_full_page_endio(page, noalloc_get_block_write,
1960                                             wbc, ext4_end_io_buffer_write);
1961         } else
1962                 ret = block_write_full_page(page, noalloc_get_block_write,
1963                                             wbc);
1964
1965         return ret;
1966 }
1967
1968 /*
1969  * This is called via ext4_da_writepages() to
1970  * calculate the total number of credits to reserve to fit
1971  * a single extent allocation into a single transaction,
1972  * ext4_da_writpeages() will loop calling this before
1973  * the block allocation.
1974  */
1975
1976 static int ext4_da_writepages_trans_blocks(struct inode *inode)
1977 {
1978         int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
1979
1980         /*
1981          * With non-extent format the journal credit needed to
1982          * insert nrblocks contiguous block is dependent on
1983          * number of contiguous block. So we will limit
1984          * number of contiguous block to a sane value
1985          */
1986         if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) &&
1987             (max_blocks > EXT4_MAX_TRANS_DATA))
1988                 max_blocks = EXT4_MAX_TRANS_DATA;
1989
1990         return ext4_chunk_trans_blocks(inode, max_blocks);
1991 }
1992
1993 /*
1994  * write_cache_pages_da - walk the list of dirty pages of the given
1995  * address space and accumulate pages that need writing, and call
1996  * mpage_da_map_and_submit to map a single contiguous memory region
1997  * and then write them.
1998  */
1999 static int write_cache_pages_da(struct address_space *mapping,
2000                                 struct writeback_control *wbc,
2001                                 struct mpage_da_data *mpd,
2002                                 pgoff_t *done_index)
2003 {
2004         struct buffer_head      *bh, *head;
2005         struct inode            *inode = mapping->host;
2006         struct pagevec          pvec;
2007         unsigned int            nr_pages;
2008         sector_t                logical;
2009         pgoff_t                 index, end;
2010         long                    nr_to_write = wbc->nr_to_write;
2011         int                     i, tag, ret = 0;
2012
2013         memset(mpd, 0, sizeof(struct mpage_da_data));
2014         mpd->wbc = wbc;
2015         mpd->inode = inode;
2016         pagevec_init(&pvec, 0);
2017         index = wbc->range_start >> PAGE_CACHE_SHIFT;
2018         end = wbc->range_end >> PAGE_CACHE_SHIFT;
2019
2020         if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2021                 tag = PAGECACHE_TAG_TOWRITE;
2022         else
2023                 tag = PAGECACHE_TAG_DIRTY;
2024
2025         *done_index = index;
2026         while (index <= end) {
2027                 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
2028                               min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
2029                 if (nr_pages == 0)
2030                         return 0;
2031
2032                 for (i = 0; i < nr_pages; i++) {
2033                         struct page *page = pvec.pages[i];
2034
2035                         /*
2036                          * At this point, the page may be truncated or
2037                          * invalidated (changing page->mapping to NULL), or
2038                          * even swizzled back from swapper_space to tmpfs file
2039                          * mapping. However, page->index will not change
2040                          * because we have a reference on the page.
2041                          */
2042                         if (page->index > end)
2043                                 goto out;
2044
2045                         *done_index = page->index + 1;
2046
2047                         /*
2048                          * If we can't merge this page, and we have
2049                          * accumulated an contiguous region, write it
2050                          */
2051                         if ((mpd->next_page != page->index) &&
2052                             (mpd->next_page != mpd->first_page)) {
2053                                 mpage_da_map_and_submit(mpd);
2054                                 goto ret_extent_tail;
2055                         }
2056
2057                         lock_page(page);
2058
2059                         /*
2060                          * If the page is no longer dirty, or its
2061                          * mapping no longer corresponds to inode we
2062                          * are writing (which means it has been
2063                          * truncated or invalidated), or the page is
2064                          * already under writeback and we are not
2065                          * doing a data integrity writeback, skip the page
2066                          */
2067                         if (!PageDirty(page) ||
2068                             (PageWriteback(page) &&
2069                              (wbc->sync_mode == WB_SYNC_NONE)) ||
2070                             unlikely(page->mapping != mapping)) {
2071                                 unlock_page(page);
2072                                 continue;
2073                         }
2074
2075                         wait_on_page_writeback(page);
2076                         BUG_ON(PageWriteback(page));
2077
2078                         if (mpd->next_page != page->index)
2079                                 mpd->first_page = page->index;
2080                         mpd->next_page = page->index + 1;
2081                         logical = (sector_t) page->index <<
2082                                 (PAGE_CACHE_SHIFT - inode->i_blkbits);
2083
2084                         if (!page_has_buffers(page)) {
2085                                 mpage_add_bh_to_extent(mpd, logical,
2086                                                        PAGE_CACHE_SIZE,
2087                                                        (1 << BH_Dirty) | (1 << BH_Uptodate));
2088                                 if (mpd->io_done)
2089                                         goto ret_extent_tail;
2090                         } else {
2091                                 /*
2092                                  * Page with regular buffer heads,
2093                                  * just add all dirty ones
2094                                  */
2095                                 head = page_buffers(page);
2096                                 bh = head;
2097                                 do {
2098                                         BUG_ON(buffer_locked(bh));
2099                                         /*
2100                                          * We need to try to allocate
2101                                          * unmapped blocks in the same page.
2102                                          * Otherwise we won't make progress
2103                                          * with the page in ext4_writepage
2104                                          */
2105                                         if (ext4_bh_delay_or_unwritten(NULL, bh)) {
2106                                                 mpage_add_bh_to_extent(mpd, logical,
2107                                                                        bh->b_size,
2108                                                                        bh->b_state);
2109                                                 if (mpd->io_done)
2110                                                         goto ret_extent_tail;
2111                                         } else if (buffer_dirty(bh) && (buffer_mapped(bh))) {
2112                                                 /*
2113                                                  * mapped dirty buffer. We need
2114                                                  * to update the b_state
2115                                                  * because we look at b_state
2116                                                  * in mpage_da_map_blocks.  We
2117                                                  * don't update b_size because
2118                                                  * if we find an unmapped
2119                                                  * buffer_head later we need to
2120                                                  * use the b_state flag of that
2121                                                  * buffer_head.
2122                                                  */
2123                                                 if (mpd->b_size == 0)
2124                                                         mpd->b_state = bh->b_state & BH_FLAGS;
2125                                         }
2126                                         logical++;
2127                                 } while ((bh = bh->b_this_page) != head);
2128                         }
2129
2130                         if (nr_to_write > 0) {
2131                                 nr_to_write--;
2132                                 if (nr_to_write == 0 &&
2133                                     wbc->sync_mode == WB_SYNC_NONE)
2134                                         /*
2135                                          * We stop writing back only if we are
2136                                          * not doing integrity sync. In case of
2137                                          * integrity sync we have to keep going
2138                                          * because someone may be concurrently
2139                                          * dirtying pages, and we might have
2140                                          * synced a lot of newly appeared dirty
2141                                          * pages, but have not synced all of the
2142                                          * old dirty pages.
2143                                          */
2144                                         goto out;
2145                         }
2146                 }
2147                 pagevec_release(&pvec);
2148                 cond_resched();
2149         }
2150         return 0;
2151 ret_extent_tail:
2152         ret = MPAGE_DA_EXTENT_TAIL;
2153 out:
2154         pagevec_release(&pvec);
2155         cond_resched();
2156         return ret;
2157 }
2158
2159
2160 static int ext4_da_writepages(struct address_space *mapping,
2161                               struct writeback_control *wbc)
2162 {
2163         pgoff_t index;
2164         int range_whole = 0;
2165         handle_t *handle = NULL;
2166         struct mpage_da_data mpd;
2167         struct inode *inode = mapping->host;
2168         int pages_written = 0;
2169         unsigned int max_pages;
2170         int range_cyclic, cycled = 1, io_done = 0;
2171         int needed_blocks, ret = 0;
2172         long desired_nr_to_write, nr_to_writebump = 0;
2173         loff_t range_start = wbc->range_start;
2174         struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2175         pgoff_t done_index = 0;
2176         pgoff_t end;
2177         struct blk_plug plug;
2178
2179         trace_ext4_da_writepages(inode, wbc);
2180
2181         /*
2182          * No pages to write? This is mainly a kludge to avoid starting
2183          * a transaction for special inodes like journal inode on last iput()
2184          * because that could violate lock ordering on umount
2185          */
2186         if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2187                 return 0;
2188
2189         /*
2190          * If the filesystem has aborted, it is read-only, so return
2191          * right away instead of dumping stack traces later on that
2192          * will obscure the real source of the problem.  We test
2193          * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2194          * the latter could be true if the filesystem is mounted
2195          * read-only, and in that case, ext4_da_writepages should
2196          * *never* be called, so if that ever happens, we would want
2197          * the stack trace.
2198          */
2199         if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED))
2200                 return -EROFS;
2201
2202         if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2203                 range_whole = 1;
2204
2205         range_cyclic = wbc->range_cyclic;
2206         if (wbc->range_cyclic) {
2207                 index = mapping->writeback_index;
2208                 if (index)
2209                         cycled = 0;
2210                 wbc->range_start = index << PAGE_CACHE_SHIFT;
2211                 wbc->range_end  = LLONG_MAX;
2212                 wbc->range_cyclic = 0;
2213                 end = -1;
2214         } else {
2215                 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2216                 end = wbc->range_end >> PAGE_CACHE_SHIFT;
2217         }
2218
2219         /*
2220          * This works around two forms of stupidity.  The first is in
2221          * the writeback code, which caps the maximum number of pages
2222          * written to be 1024 pages.  This is wrong on multiple
2223          * levels; different architectues have a different page size,
2224          * which changes the maximum amount of data which gets
2225          * written.  Secondly, 4 megabytes is way too small.  XFS
2226          * forces this value to be 16 megabytes by multiplying
2227          * nr_to_write parameter by four, and then relies on its
2228          * allocator to allocate larger extents to make them
2229          * contiguous.  Unfortunately this brings us to the second
2230          * stupidity, which is that ext4's mballoc code only allocates
2231          * at most 2048 blocks.  So we force contiguous writes up to
2232          * the number of dirty blocks in the inode, or
2233          * sbi->max_writeback_mb_bump whichever is smaller.
2234          */
2235         max_pages = sbi->s_max_writeback_mb_bump << (20 - PAGE_CACHE_SHIFT);
2236         if (!range_cyclic && range_whole) {
2237                 if (wbc->nr_to_write == LONG_MAX)
2238                         desired_nr_to_write = wbc->nr_to_write;
2239                 else
2240                         desired_nr_to_write = wbc->nr_to_write * 8;
2241         } else
2242                 desired_nr_to_write = ext4_num_dirty_pages(inode, index,
2243                                                            max_pages);
2244         if (desired_nr_to_write > max_pages)
2245                 desired_nr_to_write = max_pages;
2246
2247         if (wbc->nr_to_write < desired_nr_to_write) {
2248                 nr_to_writebump = desired_nr_to_write - wbc->nr_to_write;
2249                 wbc->nr_to_write = desired_nr_to_write;
2250         }
2251
2252 retry:
2253         if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2254                 tag_pages_for_writeback(mapping, index, end);
2255
2256         blk_start_plug(&plug);
2257         while (!ret && wbc->nr_to_write > 0) {
2258
2259                 /*
2260                  * we  insert one extent at a time. So we need
2261                  * credit needed for single extent allocation.
2262                  * journalled mode is currently not supported
2263                  * by delalloc
2264                  */
2265                 BUG_ON(ext4_should_journal_data(inode));
2266                 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2267
2268                 /* start a new transaction*/
2269                 handle = ext4_journal_start(inode, needed_blocks);
2270                 if (IS_ERR(handle)) {
2271                         ret = PTR_ERR(handle);
2272                         ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2273                                "%ld pages, ino %lu; err %d", __func__,
2274                                 wbc->nr_to_write, inode->i_ino, ret);
2275                         blk_finish_plug(&plug);
2276                         goto out_writepages;
2277                 }
2278
2279                 /*
2280                  * Now call write_cache_pages_da() to find the next
2281                  * contiguous region of logical blocks that need
2282                  * blocks to be allocated by ext4 and submit them.
2283                  */
2284                 ret = write_cache_pages_da(mapping, wbc, &mpd, &done_index);
2285                 /*
2286                  * If we have a contiguous extent of pages and we
2287                  * haven't done the I/O yet, map the blocks and submit
2288                  * them for I/O.
2289                  */
2290                 if (!mpd.io_done && mpd.next_page != mpd.first_page) {
2291                         mpage_da_map_and_submit(&mpd);
2292                         ret = MPAGE_DA_EXTENT_TAIL;
2293                 }
2294                 trace_ext4_da_write_pages(inode, &mpd);
2295                 wbc->nr_to_write -= mpd.pages_written;
2296
2297                 ext4_journal_stop(handle);
2298
2299                 if ((mpd.retval == -ENOSPC) && sbi->s_journal) {
2300                         /* commit the transaction which would
2301                          * free blocks released in the transaction
2302                          * and try again
2303                          */
2304                         jbd2_journal_force_commit_nested(sbi->s_journal);
2305                         ret = 0;
2306                 } else if (ret == MPAGE_DA_EXTENT_TAIL) {
2307                         /*
2308                          * Got one extent now try with rest of the pages.
2309                          * If mpd.retval is set -EIO, journal is aborted.
2310                          * So we don't need to write any more.
2311                          */
2312                         pages_written += mpd.pages_written;
2313                         ret = mpd.retval;
2314                         io_done = 1;
2315                 } else if (wbc->nr_to_write)
2316                         /*
2317                          * There is no more writeout needed
2318                          * or we requested for a noblocking writeout
2319                          * and we found the device congested
2320                          */
2321                         break;
2322         }
2323         blk_finish_plug(&plug);
2324         if (!io_done && !cycled) {
2325                 cycled = 1;
2326                 index = 0;
2327                 wbc->range_start = index << PAGE_CACHE_SHIFT;
2328                 wbc->range_end  = mapping->writeback_index - 1;
2329                 goto retry;
2330         }
2331
2332         /* Update index */
2333         wbc->range_cyclic = range_cyclic;
2334         if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2335                 /*
2336                  * set the writeback_index so that range_cyclic
2337                  * mode will write it back later
2338                  */
2339                 mapping->writeback_index = done_index;
2340
2341 out_writepages:
2342         wbc->nr_to_write -= nr_to_writebump;
2343         wbc->range_start = range_start;
2344         trace_ext4_da_writepages_result(inode, wbc, ret, pages_written);
2345         return ret;
2346 }
2347
2348 #define FALL_BACK_TO_NONDELALLOC 1
2349 static int ext4_nonda_switch(struct super_block *sb)
2350 {
2351         s64 free_blocks, dirty_blocks;
2352         struct ext4_sb_info *sbi = EXT4_SB(sb);
2353
2354         /*
2355          * switch to non delalloc mode if we are running low
2356          * on free block. The free block accounting via percpu
2357          * counters can get slightly wrong with percpu_counter_batch getting
2358          * accumulated on each CPU without updating global counters
2359          * Delalloc need an accurate free block accounting. So switch
2360          * to non delalloc when we are near to error range.
2361          */
2362         free_blocks  = EXT4_C2B(sbi,
2363                 percpu_counter_read_positive(&sbi->s_freeclusters_counter));
2364         dirty_blocks = percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2365         if (2 * free_blocks < 3 * dirty_blocks ||
2366                 free_blocks < (dirty_blocks + EXT4_FREECLUSTERS_WATERMARK)) {
2367                 /*
2368                  * free block count is less than 150% of dirty blocks
2369                  * or free blocks is less than watermark
2370                  */
2371                 return 1;
2372         }
2373         /*
2374          * Even if we don't switch but are nearing capacity,
2375          * start pushing delalloc when 1/2 of free blocks are dirty.
2376          */
2377         if (free_blocks < 2 * dirty_blocks)
2378                 writeback_inodes_sb_if_idle(sb, WB_REASON_FS_FREE_SPACE);
2379
2380         return 0;
2381 }
2382
2383 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2384                                loff_t pos, unsigned len, unsigned flags,
2385                                struct page **pagep, void **fsdata)
2386 {
2387         int ret, retries = 0;
2388         struct page *page;
2389         pgoff_t index;
2390         struct inode *inode = mapping->host;
2391         handle_t *handle;
2392
2393         index = pos >> PAGE_CACHE_SHIFT;
2394
2395         if (ext4_nonda_switch(inode->i_sb)) {
2396                 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2397                 return ext4_write_begin(file, mapping, pos,
2398                                         len, flags, pagep, fsdata);
2399         }
2400         *fsdata = (void *)0;
2401         trace_ext4_da_write_begin(inode, pos, len, flags);
2402 retry:
2403         /*
2404          * With delayed allocation, we don't log the i_disksize update
2405          * if there is delayed block allocation. But we still need
2406          * to journalling the i_disksize update if writes to the end
2407          * of file which has an already mapped buffer.
2408          */
2409         handle = ext4_journal_start(inode, 1);
2410         if (IS_ERR(handle)) {
2411                 ret = PTR_ERR(handle);
2412                 goto out;
2413         }
2414         /* We cannot recurse into the filesystem as the transaction is already
2415          * started */
2416         flags |= AOP_FLAG_NOFS;
2417
2418         page = grab_cache_page_write_begin(mapping, index, flags);
2419         if (!page) {
2420                 ext4_journal_stop(handle);
2421                 ret = -ENOMEM;
2422                 goto out;
2423         }
2424         *pagep = page;
2425
2426         ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
2427         if (ret < 0) {
2428                 unlock_page(page);
2429                 ext4_journal_stop(handle);
2430                 page_cache_release(page);
2431                 /*
2432                  * block_write_begin may have instantiated a few blocks
2433                  * outside i_size.  Trim these off again. Don't need
2434                  * i_size_read because we hold i_mutex.
2435                  */
2436                 if (pos + len > inode->i_size)
2437                         ext4_truncate_failed_write(inode);
2438         }
2439
2440         if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
2441                 goto retry;
2442 out:
2443         return ret;
2444 }
2445
2446 /*
2447  * Check if we should update i_disksize
2448  * when write to the end of file but not require block allocation
2449  */
2450 static int ext4_da_should_update_i_disksize(struct page *page,
2451                                             unsigned long offset)
2452 {
2453         struct buffer_head *bh;
2454         struct inode *inode = page->mapping->host;
2455         unsigned int idx;
2456         int i;
2457
2458         bh = page_buffers(page);
2459         idx = offset >> inode->i_blkbits;
2460
2461         for (i = 0; i < idx; i++)
2462                 bh = bh->b_this_page;
2463
2464         if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2465                 return 0;
2466         return 1;
2467 }
2468
2469 static int ext4_da_write_end(struct file *file,
2470                              struct address_space *mapping,
2471                              loff_t pos, unsigned len, unsigned copied,
2472                              struct page *page, void *fsdata)
2473 {
2474         struct inode *inode = mapping->host;
2475         int ret = 0, ret2;
2476         handle_t *handle = ext4_journal_current_handle();
2477         loff_t new_i_size;
2478         unsigned long start, end;
2479         int write_mode = (int)(unsigned long)fsdata;
2480
2481         if (write_mode == FALL_BACK_TO_NONDELALLOC) {
2482                 if (ext4_should_order_data(inode)) {
2483                         return ext4_ordered_write_end(file, mapping, pos,
2484                                         len, copied, page, fsdata);
2485                 } else if (ext4_should_writeback_data(inode)) {
2486                         return ext4_writeback_write_end(file, mapping, pos,
2487                                         len, copied, page, fsdata);
2488                 } else {
2489                         BUG();
2490                 }
2491         }
2492
2493         trace_ext4_da_write_end(inode, pos, len, copied);
2494         start = pos & (PAGE_CACHE_SIZE - 1);
2495         end = start + copied - 1;
2496
2497         /*
2498          * generic_write_end() will run mark_inode_dirty() if i_size
2499          * changes.  So let's piggyback the i_disksize mark_inode_dirty
2500          * into that.
2501          */
2502
2503         new_i_size = pos + copied;
2504         if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
2505                 if (ext4_da_should_update_i_disksize(page, end)) {
2506                         down_write(&EXT4_I(inode)->i_data_sem);
2507                         if (new_i_size > EXT4_I(inode)->i_disksize) {
2508                                 /*
2509                                  * Updating i_disksize when extending file
2510                                  * without needing block allocation
2511                                  */
2512                                 if (ext4_should_order_data(inode))
2513                                         ret = ext4_jbd2_file_inode(handle,
2514                                                                    inode);
2515
2516                                 EXT4_I(inode)->i_disksize = new_i_size;
2517                         }
2518                         up_write(&EXT4_I(inode)->i_data_sem);
2519                         /* We need to mark inode dirty even if
2520                          * new_i_size is less that inode->i_size
2521                          * bu greater than i_disksize.(hint delalloc)
2522                          */
2523                         ext4_mark_inode_dirty(handle, inode);
2524                 }
2525         }
2526         ret2 = generic_write_end(file, mapping, pos, len, copied,
2527                                                         page, fsdata);
2528         copied = ret2;
2529         if (ret2 < 0)
2530                 ret = ret2;
2531         ret2 = ext4_journal_stop(handle);
2532         if (!ret)
2533                 ret = ret2;
2534
2535         return ret ? ret : copied;
2536 }
2537
2538 static void ext4_da_invalidatepage(struct page *page, unsigned long offset)
2539 {
2540         /*
2541          * Drop reserved blocks
2542          */
2543         BUG_ON(!PageLocked(page));
2544         if (!page_has_buffers(page))
2545                 goto out;
2546
2547         ext4_da_page_release_reservation(page, offset);
2548
2549 out:
2550         ext4_invalidatepage(page, offset);
2551
2552         return;
2553 }
2554
2555 /*
2556  * Force all delayed allocation blocks to be allocated for a given inode.
2557  */
2558 int ext4_alloc_da_blocks(struct inode *inode)
2559 {
2560         trace_ext4_alloc_da_blocks(inode);
2561
2562         if (!EXT4_I(inode)->i_reserved_data_blocks &&
2563             !EXT4_I(inode)->i_reserved_meta_blocks)
2564                 return 0;
2565
2566         /*
2567          * We do something simple for now.  The filemap_flush() will
2568          * also start triggering a write of the data blocks, which is
2569          * not strictly speaking necessary (and for users of
2570          * laptop_mode, not even desirable).  However, to do otherwise
2571          * would require replicating code paths in:
2572          *
2573          * ext4_da_writepages() ->
2574          *    write_cache_pages() ---> (via passed in callback function)
2575          *        __mpage_da_writepage() -->
2576          *           mpage_add_bh_to_extent()
2577          *           mpage_da_map_blocks()
2578          *
2579          * The problem is that write_cache_pages(), located in
2580          * mm/page-writeback.c, marks pages clean in preparation for
2581          * doing I/O, which is not desirable if we're not planning on
2582          * doing I/O at all.
2583          *
2584          * We could call write_cache_pages(), and then redirty all of
2585          * the pages by calling redirty_page_for_writepage() but that
2586          * would be ugly in the extreme.  So instead we would need to
2587          * replicate parts of the code in the above functions,
2588          * simplifying them because we wouldn't actually intend to
2589          * write out the pages, but rather only collect contiguous
2590          * logical block extents, call the multi-block allocator, and
2591          * then update the buffer heads with the block allocations.
2592          *
2593          * For now, though, we'll cheat by calling filemap_flush(),
2594          * which will map the blocks, and start the I/O, but not
2595          * actually wait for the I/O to complete.
2596          */
2597         return filemap_flush(inode->i_mapping);
2598 }
2599
2600 /*
2601  * bmap() is special.  It gets used by applications such as lilo and by
2602  * the swapper to find the on-disk block of a specific piece of data.
2603  *
2604  * Naturally, this is dangerous if the block concerned is still in the
2605  * journal.  If somebody makes a swapfile on an ext4 data-journaling
2606  * filesystem and enables swap, then they may get a nasty shock when the
2607  * data getting swapped to that swapfile suddenly gets overwritten by
2608  * the original zero's written out previously to the journal and
2609  * awaiting writeback in the kernel's buffer cache.
2610  *
2611  * So, if we see any bmap calls here on a modified, data-journaled file,
2612  * take extra steps to flush any blocks which might be in the cache.
2613  */
2614 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
2615 {
2616         struct inode *inode = mapping->host;
2617         journal_t *journal;
2618         int err;
2619
2620         if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
2621                         test_opt(inode->i_sb, DELALLOC)) {
2622                 /*
2623                  * With delalloc we want to sync the file
2624                  * so that we can make sure we allocate
2625                  * blocks for file
2626                  */
2627                 filemap_write_and_wait(mapping);
2628         }
2629
2630         if (EXT4_JOURNAL(inode) &&
2631             ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
2632                 /*
2633                  * This is a REALLY heavyweight approach, but the use of
2634                  * bmap on dirty files is expected to be extremely rare:
2635                  * only if we run lilo or swapon on a freshly made file
2636                  * do we expect this to happen.
2637                  *
2638                  * (bmap requires CAP_SYS_RAWIO so this does not
2639                  * represent an unprivileged user DOS attack --- we'd be
2640                  * in trouble if mortal users could trigger this path at
2641                  * will.)
2642                  *
2643                  * NB. EXT4_STATE_JDATA is not set on files other than
2644                  * regular files.  If somebody wants to bmap a directory
2645                  * or symlink and gets confused because the buffer
2646                  * hasn't yet been flushed to disk, they deserve
2647                  * everything they get.
2648                  */
2649
2650                 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
2651                 journal = EXT4_JOURNAL(inode);
2652                 jbd2_journal_lock_updates(journal);
2653                 err = jbd2_journal_flush(journal);
2654                 jbd2_journal_unlock_updates(journal);
2655
2656                 if (err)
2657                         return 0;
2658         }
2659
2660         return generic_block_bmap(mapping, block, ext4_get_block);
2661 }
2662
2663 static int ext4_readpage(struct file *file, struct page *page)
2664 {
2665         trace_ext4_readpage(page);
2666         return mpage_readpage(page, ext4_get_block);
2667 }
2668
2669 static int
2670 ext4_readpages(struct file *file, struct address_space *mapping,
2671                 struct list_head *pages, unsigned nr_pages)
2672 {
2673         return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
2674 }
2675
2676 static void ext4_invalidatepage_free_endio(struct page *page, unsigned long offset)
2677 {
2678         struct buffer_head *head, *bh;
2679         unsigned int curr_off = 0;
2680
2681         if (!page_has_buffers(page))
2682                 return;
2683         head = bh = page_buffers(page);
2684         do {
2685                 if (offset <= curr_off && test_clear_buffer_uninit(bh)
2686                                         && bh->b_private) {
2687                         ext4_free_io_end(bh->b_private);
2688                         bh->b_private = NULL;
2689                         bh->b_end_io = NULL;
2690                 }
2691                 curr_off = curr_off + bh->b_size;
2692                 bh = bh->b_this_page;
2693         } while (bh != head);
2694 }
2695
2696 static void ext4_invalidatepage(struct page *page, unsigned long offset)
2697 {
2698         journal_t *journal = EXT4_JOURNAL(page->mapping->host);
2699
2700         trace_ext4_invalidatepage(page, offset);
2701
2702         /*
2703          * free any io_end structure allocated for buffers to be discarded
2704          */
2705         if (ext4_should_dioread_nolock(page->mapping->host))
2706                 ext4_invalidatepage_free_endio(page, offset);
2707         /*
2708          * If it's a full truncate we just forget about the pending dirtying
2709          */
2710         if (offset == 0)
2711                 ClearPageChecked(page);
2712
2713         if (journal)
2714                 jbd2_journal_invalidatepage(journal, page, offset);
2715         else
2716                 block_invalidatepage(page, offset);
2717 }
2718
2719 static int ext4_releasepage(struct page *page, gfp_t wait)
2720 {
2721         journal_t *journal = EXT4_JOURNAL(page->mapping->host);
2722
2723         trace_ext4_releasepage(page);
2724
2725         WARN_ON(PageChecked(page));
2726         if (!page_has_buffers(page))
2727                 return 0;
2728         if (journal)
2729                 return jbd2_journal_try_to_free_buffers(journal, page, wait);
2730         else
2731                 return try_to_free_buffers(page);
2732 }
2733
2734 /*
2735  * ext4_get_block used when preparing for a DIO write or buffer write.
2736  * We allocate an uinitialized extent if blocks haven't been allocated.
2737  * The extent will be converted to initialized after the IO is complete.
2738  */
2739 static int ext4_get_block_write(struct inode *inode, sector_t iblock,
2740                    struct buffer_head *bh_result, int create)
2741 {
2742         ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
2743                    inode->i_ino, create);
2744         return _ext4_get_block(inode, iblock, bh_result,
2745                                EXT4_GET_BLOCKS_IO_CREATE_EXT);
2746 }
2747
2748 static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
2749                             ssize_t size, void *private, int ret,
2750                             bool is_async)
2751 {
2752         struct inode *inode = iocb->ki_filp->f_path.dentry->d_inode;
2753         ext4_io_end_t *io_end = iocb->private;
2754         struct workqueue_struct *wq;
2755         unsigned long flags;
2756         struct ext4_inode_info *ei;
2757
2758         /* if not async direct IO or dio with 0 bytes write, just return */
2759         if (!io_end || !size)
2760                 goto out;
2761
2762         ext_debug("ext4_end_io_dio(): io_end 0x%p"
2763                   "for inode %lu, iocb 0x%p, offset %llu, size %llu\n",
2764                   iocb->private, io_end->inode->i_ino, iocb, offset,
2765                   size);
2766
2767         iocb->private = NULL;
2768
2769         /* if not aio dio with unwritten extents, just free io and return */
2770         if (!(io_end->flag & EXT4_IO_END_UNWRITTEN)) {
2771                 ext4_free_io_end(io_end);
2772 out:
2773                 if (is_async)
2774                         aio_complete(iocb, ret, 0);
2775                 inode_dio_done(inode);
2776                 return;
2777         }
2778
2779         io_end->offset = offset;
2780         io_end->size = size;
2781         if (is_async) {
2782                 io_end->iocb = iocb;
2783                 io_end->result = ret;
2784         }
2785         wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;
2786
2787         /* Add the io_end to per-inode completed aio dio list*/
2788         ei = EXT4_I(io_end->inode);
2789         spin_lock_irqsave(&ei->i_completed_io_lock, flags);
2790         list_add_tail(&io_end->list, &ei->i_completed_io_list);
2791         spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
2792
2793         /* queue the work to convert unwritten extents to written */
2794         queue_work(wq, &io_end->work);
2795
2796         /* XXX: probably should move into the real I/O completion handler */
2797         inode_dio_done(inode);
2798 }
2799
2800 static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate)
2801 {
2802         ext4_io_end_t *io_end = bh->b_private;
2803         struct workqueue_struct *wq;
2804         struct inode *inode;
2805         unsigned long flags;
2806
2807         if (!test_clear_buffer_uninit(bh) || !io_end)
2808                 goto out;
2809
2810         if (!(io_end->inode->i_sb->s_flags & MS_ACTIVE)) {
2811                 printk("sb umounted, discard end_io request for inode %lu\n",
2812                         io_end->inode->i_ino);
2813                 ext4_free_io_end(io_end);
2814                 goto out;
2815         }
2816
2817         /*
2818          * It may be over-defensive here to check EXT4_IO_END_UNWRITTEN now,
2819          * but being more careful is always safe for the future change.
2820          */
2821         inode = io_end->inode;
2822         ext4_set_io_unwritten_flag(inode, io_end);
2823
2824         /* Add the io_end to per-inode completed io list*/
2825         spin_lock_irqsave(&EXT4_I(inode)->i_completed_io_lock, flags);
2826         list_add_tail(&io_end->list, &EXT4_I(inode)->i_completed_io_list);
2827         spin_unlock_irqrestore(&EXT4_I(inode)->i_completed_io_lock, flags);
2828
2829         wq = EXT4_SB(inode->i_sb)->dio_unwritten_wq;
2830         /* queue the work to convert unwritten extents to written */
2831         queue_work(wq, &io_end->work);
2832 out:
2833         bh->b_private = NULL;
2834         bh->b_end_io = NULL;
2835         clear_buffer_uninit(bh);
2836         end_buffer_async_write(bh, uptodate);
2837 }
2838
2839 static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode)
2840 {
2841         ext4_io_end_t *io_end;
2842         struct page *page = bh->b_page;
2843         loff_t offset = (sector_t)page->index << PAGE_CACHE_SHIFT;
2844         size_t size = bh->b_size;
2845
2846 retry:
2847         io_end = ext4_init_io_end(inode, GFP_ATOMIC);
2848         if (!io_end) {
2849                 pr_warn_ratelimited("%s: allocation fail\n", __func__);
2850                 schedule();
2851                 goto retry;
2852         }
2853         io_end->offset = offset;
2854         io_end->size = size;
2855         /*
2856          * We need to hold a reference to the page to make sure it
2857          * doesn't get evicted before ext4_end_io_work() has a chance
2858          * to convert the extent from written to unwritten.
2859          */
2860         io_end->page = page;
2861         get_page(io_end->page);
2862
2863         bh->b_private = io_end;
2864         bh->b_end_io = ext4_end_io_buffer_write;
2865         return 0;
2866 }
2867
2868 /*
2869  * For ext4 extent files, ext4 will do direct-io write to holes,
2870  * preallocated extents, and those write extend the file, no need to
2871  * fall back to buffered IO.
2872  *
2873  * For holes, we fallocate those blocks, mark them as uninitialized
2874  * If those blocks were preallocated, we mark sure they are splited, but
2875  * still keep the range to write as uninitialized.
2876  *
2877  * The unwrritten extents will be converted to written when DIO is completed.
2878  * For async direct IO, since the IO may still pending when return, we
2879  * set up an end_io call back function, which will do the conversion
2880  * when async direct IO completed.
2881  *
2882  * If the O_DIRECT write will extend the file then add this inode to the
2883  * orphan list.  So recovery will truncate it back to the original size
2884  * if the machine crashes during the write.
2885  *
2886  */
2887 static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
2888                               const struct iovec *iov, loff_t offset,
2889                               unsigned long nr_segs)
2890 {
2891         struct file *file = iocb->ki_filp;
2892         struct inode *inode = file->f_mapping->host;
2893         ssize_t ret;
2894         size_t count = iov_length(iov, nr_segs);
2895
2896         loff_t final_size = offset + count;
2897         if (rw == WRITE && final_size <= inode->i_size) {
2898                 /*
2899                  * We could direct write to holes and fallocate.
2900                  *
2901                  * Allocated blocks to fill the hole are marked as uninitialized
2902                  * to prevent parallel buffered read to expose the stale data
2903                  * before DIO complete the data IO.
2904                  *
2905                  * As to previously fallocated extents, ext4 get_block
2906                  * will just simply mark the buffer mapped but still
2907                  * keep the extents uninitialized.
2908                  *
2909                  * for non AIO case, we will convert those unwritten extents
2910                  * to written after return back from blockdev_direct_IO.
2911                  *
2912                  * for async DIO, the conversion needs to be defered when
2913                  * the IO is completed. The ext4 end_io callback function
2914                  * will be called to take care of the conversion work.
2915                  * Here for async case, we allocate an io_end structure to
2916                  * hook to the iocb.
2917                  */
2918                 iocb->private = NULL;
2919                 EXT4_I(inode)->cur_aio_dio = NULL;
2920                 if (!is_sync_kiocb(iocb)) {
2921                         iocb->private = ext4_init_io_end(inode, GFP_NOFS);
2922                         if (!iocb->private)
2923                                 return -ENOMEM;
2924                         /*
2925                          * we save the io structure for current async
2926                          * direct IO, so that later ext4_map_blocks()
2927                          * could flag the io structure whether there
2928                          * is a unwritten extents needs to be converted
2929                          * when IO is completed.
2930                          */
2931                         EXT4_I(inode)->cur_aio_dio = iocb->private;
2932                 }
2933
2934                 ret = __blockdev_direct_IO(rw, iocb, inode,
2935                                          inode->i_sb->s_bdev, iov,
2936                                          offset, nr_segs,
2937                                          ext4_get_block_write,
2938                                          ext4_end_io_dio,
2939                                          NULL,
2940                                          DIO_LOCKING | DIO_SKIP_HOLES);
2941                 if (iocb->private)
2942                         EXT4_I(inode)->cur_aio_dio = NULL;
2943                 /*
2944                  * The io_end structure takes a reference to the inode,
2945                  * that structure needs to be destroyed and the
2946                  * reference to the inode need to be dropped, when IO is
2947                  * complete, even with 0 byte write, or failed.
2948                  *
2949                  * In the successful AIO DIO case, the io_end structure will be
2950                  * desctroyed and the reference to the inode will be dropped
2951                  * after the end_io call back function is called.
2952                  *
2953                  * In the case there is 0 byte write, or error case, since
2954                  * VFS direct IO won't invoke the end_io call back function,
2955                  * we need to free the end_io structure here.
2956                  */
2957                 if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) {
2958                         ext4_free_io_end(iocb->private);
2959                         iocb->private = NULL;
2960                 } else if (ret > 0 && ext4_test_inode_state(inode,
2961                                                 EXT4_STATE_DIO_UNWRITTEN)) {
2962                         int err;
2963                         /*
2964                          * for non AIO case, since the IO is already
2965                          * completed, we could do the conversion right here
2966                          */
2967                         err = ext4_convert_unwritten_extents(inode,
2968                                                              offset, ret);
2969                         if (err < 0)
2970                                 ret = err;
2971                         ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
2972                 }
2973                 return ret;
2974         }
2975
2976         /* for write the the end of file case, we fall back to old way */
2977         return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
2978 }
2979
2980 static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
2981                               const struct iovec *iov, loff_t offset,
2982                               unsigned long nr_segs)
2983 {
2984         struct file *file = iocb->ki_filp;
2985         struct inode *inode = file->f_mapping->host;
2986         ssize_t ret;
2987
2988         /*
2989          * If we are doing data journalling we don't support O_DIRECT
2990          */
2991         if (ext4_should_journal_data(inode))
2992                 return 0;
2993
2994         trace_ext4_direct_IO_enter(inode, offset, iov_length(iov, nr_segs), rw);
2995         if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
2996                 ret = ext4_ext_direct_IO(rw, iocb, iov, offset, nr_segs);
2997         else
2998                 ret = ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
2999         trace_ext4_direct_IO_exit(inode, offset,
3000                                 iov_length(iov, nr_segs), rw, ret);
3001         return ret;
3002 }
3003
3004 /*
3005  * Pages can be marked dirty completely asynchronously from ext4's journalling
3006  * activity.  By filemap_sync_pte(), try_to_unmap_one(), etc.  We cannot do
3007  * much here because ->set_page_dirty is called under VFS locks.  The page is
3008  * not necessarily locked.
3009  *
3010  * We cannot just dirty the page and leave attached buffers clean, because the
3011  * buffers' dirty state is "definitive".  We cannot just set the buffers dirty
3012  * or jbddirty because all the journalling code will explode.
3013  *
3014  * So what we do is to mark the page "pending dirty" and next time writepage
3015  * is called, propagate that into the buffers appropriately.
3016  */
3017 static int ext4_journalled_set_page_dirty(struct page *page)
3018 {
3019         SetPageChecked(page);
3020         return __set_page_dirty_nobuffers(page);
3021 }
3022
3023 static const struct address_space_operations ext4_ordered_aops = {
3024         .readpage               = ext4_readpage,
3025         .readpages              = ext4_readpages,
3026         .writepage              = ext4_writepage,
3027         .write_begin            = ext4_write_begin,
3028         .write_end              = ext4_ordered_write_end,
3029         .bmap                   = ext4_bmap,
3030         .invalidatepage         = ext4_invalidatepage,
3031         .releasepage            = ext4_releasepage,
3032         .direct_IO              = ext4_direct_IO,
3033         .migratepage            = buffer_migrate_page,
3034         .is_partially_uptodate  = block_is_partially_uptodate,
3035         .error_remove_page      = generic_error_remove_page,
3036 };
3037
3038 static const struct address_space_operations ext4_writeback_aops = {
3039         .readpage               = ext4_readpage,
3040         .readpages              = ext4_readpages,
3041         .writepage              = ext4_writepage,
3042         .write_begin            = ext4_write_begin,
3043         .write_end              = ext4_writeback_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_journalled_aops = {
3054         .readpage               = ext4_readpage,
3055         .readpages              = ext4_readpages,
3056         .writepage              = ext4_writepage,
3057         .write_begin            = ext4_write_begin,
3058         .write_end              = ext4_journalled_write_end,
3059         .set_page_dirty         = ext4_journalled_set_page_dirty,
3060         .bmap                   = ext4_bmap,
3061         .invalidatepage         = ext4_invalidatepage,
3062         .releasepage            = ext4_releasepage,
3063         .direct_IO              = ext4_direct_IO,
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_da_aops = {
3069         .readpage               = ext4_readpage,
3070         .readpages              = ext4_readpages,
3071         .writepage              = ext4_writepage,
3072         .writepages             = ext4_da_writepages,
3073         .write_begin            = ext4_da_write_begin,
3074         .write_end              = ext4_da_write_end,
3075         .bmap                   = ext4_bmap,
3076         .invalidatepage         = ext4_da_invalidatepage,
3077         .releasepage            = ext4_releasepage,
3078         .direct_IO              = ext4_direct_IO,
3079         .migratepage            = buffer_migrate_page,
3080         .is_partially_uptodate  = block_is_partially_uptodate,
3081         .error_remove_page      = generic_error_remove_page,
3082 };
3083
3084 void ext4_set_aops(struct inode *inode)
3085 {
3086         if (ext4_should_order_data(inode) &&
3087                 test_opt(inode->i_sb, DELALLOC))
3088                 inode->i_mapping->a_ops = &ext4_da_aops;
3089         else if (ext4_should_order_data(inode))
3090                 inode->i_mapping->a_ops = &ext4_ordered_aops;
3091         else if (ext4_should_writeback_data(inode) &&
3092                  test_opt(inode->i_sb, DELALLOC))
3093                 inode->i_mapping->a_ops = &ext4_da_aops;
3094         else if (ext4_should_writeback_data(inode))
3095                 inode->i_mapping->a_ops = &ext4_writeback_aops;
3096         else
3097                 inode->i_mapping->a_ops = &ext4_journalled_aops;
3098 }
3099
3100
3101 /*
3102  * ext4_discard_partial_page_buffers()
3103  * Wrapper function for ext4_discard_partial_page_buffers_no_lock.
3104  * This function finds and locks the page containing the offset
3105  * "from" and passes it to ext4_discard_partial_page_buffers_no_lock.
3106  * Calling functions that already have the page locked should call
3107  * ext4_discard_partial_page_buffers_no_lock directly.
3108  */
3109 int ext4_discard_partial_page_buffers(handle_t *handle,
3110                 struct address_space *mapping, loff_t from,
3111                 loff_t length, int flags)
3112 {
3113         struct inode *inode = mapping->host;
3114         struct page *page;
3115         int err = 0;
3116
3117         page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3118                                    mapping_gfp_mask(mapping) & ~__GFP_FS);
3119         if (!page)
3120                 return -ENOMEM;
3121
3122         err = ext4_discard_partial_page_buffers_no_lock(handle, inode, page,
3123                 from, length, flags);
3124
3125         unlock_page(page);
3126         page_cache_release(page);
3127         return err;
3128 }
3129
3130 /*
3131  * ext4_discard_partial_page_buffers_no_lock()
3132  * Zeros a page range of length 'length' starting from offset 'from'.
3133  * Buffer heads that correspond to the block aligned regions of the
3134  * zeroed range will be unmapped.  Unblock aligned regions
3135  * will have the corresponding buffer head mapped if needed so that
3136  * that region of the page can be updated with the partial zero out.
3137  *
3138  * This function assumes that the page has already been  locked.  The
3139  * The range to be discarded must be contained with in the given page.
3140  * If the specified range exceeds the end of the page it will be shortened
3141  * to the end of the page that corresponds to 'from'.  This function is
3142  * appropriate for updating a page and it buffer heads to be unmapped and
3143  * zeroed for blocks that have been either released, or are going to be
3144  * released.
3145  *
3146  * handle: The journal handle
3147  * inode:  The files inode
3148  * page:   A locked page that contains the offset "from"
3149  * from:   The starting byte offset (from the begining of the file)
3150  *         to begin discarding
3151  * len:    The length of bytes to discard
3152  * flags:  Optional flags that may be used:
3153  *
3154  *         EXT4_DISCARD_PARTIAL_PG_ZERO_UNMAPPED
3155  *         Only zero the regions of the page whose buffer heads
3156  *         have already been unmapped.  This flag is appropriate
3157  *         for updateing the contents of a page whose blocks may
3158  *         have already been released, and we only want to zero
3159  *         out the regions that correspond to those released blocks.
3160  *
3161  * Returns zero on sucess or negative on failure.
3162  */
3163 int ext4_discard_partial_page_buffers_no_lock(handle_t *handle,
3164                 struct inode *inode, struct page *page, loff_t from,
3165                 loff_t length, int flags)
3166 {
3167         ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3168         unsigned int offset = from & (PAGE_CACHE_SIZE-1);
3169         unsigned int blocksize, max, pos;
3170         ext4_lblk_t iblock;
3171         struct buffer_head *bh;
3172         int err = 0;
3173
3174         blocksize = inode->i_sb->s_blocksize;
3175         max = PAGE_CACHE_SIZE - offset;
3176
3177         if (index != page->index)
3178                 return -EINVAL;
3179
3180         /*
3181          * correct length if it does not fall between
3182          * 'from' and the end of the page
3183          */
3184         if (length > max || length < 0)
3185                 length = max;
3186
3187         iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3188
3189         if (!page_has_buffers(page))
3190                 create_empty_buffers(page, blocksize, 0);
3191
3192         /* Find the buffer that contains "offset" */
3193         bh = page_buffers(page);
3194         pos = blocksize;
3195         while (offset >= pos) {
3196                 bh = bh->b_this_page;
3197                 iblock++;
3198                 pos += blocksize;
3199         }
3200
3201         pos = offset;
3202         while (pos < offset + length) {
3203                 unsigned int end_of_block, range_to_discard;
3204
3205                 err = 0;
3206
3207                 /* The length of space left to zero and unmap */
3208                 range_to_discard = offset + length - pos;
3209
3210                 /* The length of space until the end of the block */
3211                 end_of_block = blocksize - (pos & (blocksize-1));
3212
3213                 /*
3214                  * Do not unmap or zero past end of block
3215                  * for this buffer head
3216                  */
3217                 if (range_to_discard > end_of_block)
3218                         range_to_discard = end_of_block;
3219
3220
3221                 /*
3222                  * Skip this buffer head if we are only zeroing unampped
3223                  * regions of the page
3224                  */
3225                 if (flags & EXT4_DISCARD_PARTIAL_PG_ZERO_UNMAPPED &&
3226                         buffer_mapped(bh))
3227                                 goto next;
3228
3229                 /* If the range is block aligned, unmap */
3230                 if (range_to_discard == blocksize) {
3231                         clear_buffer_dirty(bh);
3232                         bh->b_bdev = NULL;
3233                         clear_buffer_mapped(bh);
3234                         clear_buffer_req(bh);
3235                         clear_buffer_new(bh);
3236                         clear_buffer_delay(bh);
3237                         clear_buffer_unwritten(bh);
3238                         clear_buffer_uptodate(bh);
3239                         zero_user(page, pos, range_to_discard);
3240                         BUFFER_TRACE(bh, "Buffer discarded");
3241                         goto next;
3242                 }
3243
3244                 /*
3245                  * If this block is not completely contained in the range
3246                  * to be discarded, then it is not going to be released. Because
3247                  * we need to keep this block, we need to make sure this part
3248                  * of the page is uptodate before we modify it by writeing
3249                  * partial zeros on it.
3250                  */
3251                 if (!buffer_mapped(bh)) {
3252                         /*
3253                          * Buffer head must be mapped before we can read
3254                          * from the block
3255                          */
3256                         BUFFER_TRACE(bh, "unmapped");
3257                         ext4_get_block(inode, iblock, bh, 0);
3258                         /* unmapped? It's a hole - nothing to do */
3259                         if (!buffer_mapped(bh)) {
3260                                 BUFFER_TRACE(bh, "still unmapped");
3261                                 goto next;
3262                         }
3263                 }
3264
3265                 /* Ok, it's mapped. Make sure it's up-to-date */
3266                 if (PageUptodate(page))
3267                         set_buffer_uptodate(bh);
3268
3269                 if (!buffer_uptodate(bh)) {
3270                         err = -EIO;
3271                         ll_rw_block(READ, 1, &bh);
3272                         wait_on_buffer(bh);
3273                         /* Uhhuh. Read error. Complain and punt.*/
3274                         if (!buffer_uptodate(bh))
3275                                 goto next;
3276                 }
3277
3278                 if (ext4_should_journal_data(inode)) {
3279                         BUFFER_TRACE(bh, "get write access");
3280                         err = ext4_journal_get_write_access(handle, bh);
3281                         if (err)
3282                                 goto next;
3283                 }
3284
3285                 zero_user(page, pos, range_to_discard);
3286
3287                 err = 0;
3288                 if (ext4_should_journal_data(inode)) {
3289                         err = ext4_handle_dirty_metadata(handle, inode, bh);
3290                 } else
3291                         mark_buffer_dirty(bh);
3292
3293                 BUFFER_TRACE(bh, "Partial buffer zeroed");
3294 next:
3295                 bh = bh->b_this_page;
3296                 iblock++;
3297                 pos += range_to_discard;
3298         }
3299
3300         return err;
3301 }
3302
3303 /*
3304  * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3305  * up to the end of the block which corresponds to `from'.
3306  * This required during truncate. We need to physically zero the tail end
3307  * of that block so it doesn't yield old data if the file is later grown.
3308  */
3309 int ext4_block_truncate_page(handle_t *handle,
3310                 struct address_space *mapping, loff_t from)
3311 {
3312         unsigned offset = from & (PAGE_CACHE_SIZE-1);
3313         unsigned length;
3314         unsigned blocksize;
3315         struct inode *inode = mapping->host;
3316
3317         blocksize = inode->i_sb->s_blocksize;
3318         length = blocksize - (offset & (blocksize - 1));
3319
3320         return ext4_block_zero_page_range(handle, mapping, from, length);
3321 }
3322
3323 /*
3324  * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3325  * starting from file offset 'from'.  The range to be zero'd must
3326  * be contained with in one block.  If the specified range exceeds
3327  * the end of the block it will be shortened to end of the block
3328  * that cooresponds to 'from'
3329  */
3330 int ext4_block_zero_page_range(handle_t *handle,
3331                 struct address_space *mapping, loff_t from, loff_t length)
3332 {
3333         ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3334         unsigned offset = from & (PAGE_CACHE_SIZE-1);
3335         unsigned blocksize, max, pos;
3336         ext4_lblk_t iblock;
3337         struct inode *inode = mapping->host;
3338         struct buffer_head *bh;
3339         struct page *page;
3340         int err = 0;
3341
3342         page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3343                                    mapping_gfp_mask(mapping) & ~__GFP_FS);
3344         if (!page)
3345                 return -ENOMEM;
3346
3347         blocksize = inode->i_sb->s_blocksize;
3348         max = blocksize - (offset & (blocksize - 1));
3349
3350         /*
3351          * correct length if it does not fall between
3352          * 'from' and the end of the block
3353          */
3354         if (length > max || length < 0)
3355                 length = max;
3356
3357         iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3358
3359         if (!page_has_buffers(page))
3360                 create_empty_buffers(page, blocksize, 0);
3361
3362         /* Find the buffer that contains "offset" */
3363         bh = page_buffers(page);
3364         pos = blocksize;
3365         while (offset >= pos) {
3366                 bh = bh->b_this_page;
3367                 iblock++;
3368                 pos += blocksize;
3369         }
3370
3371         err = 0;
3372         if (buffer_freed(bh)) {
3373                 BUFFER_TRACE(bh, "freed: skip");
3374                 goto unlock;
3375         }
3376
3377         if (!buffer_mapped(bh)) {
3378                 BUFFER_TRACE(bh, "unmapped");
3379                 ext4_get_block(inode, iblock, bh, 0);
3380                 /* unmapped? It's a hole - nothing to do */
3381                 if (!buffer_mapped(bh)) {
3382                         BUFFER_TRACE(bh, "still unmapped");
3383                         goto unlock;
3384                 }
3385         }
3386
3387         /* Ok, it's mapped. Make sure it's up-to-date */
3388         if (PageUptodate(page))
3389                 set_buffer_uptodate(bh);
3390
3391         if (!buffer_uptodate(bh)) {
3392                 err = -EIO;
3393                 ll_rw_block(READ, 1, &bh);
3394                 wait_on_buffer(bh);
3395                 /* Uhhuh. Read error. Complain and punt. */
3396                 if (!buffer_uptodate(bh))
3397                         goto unlock;
3398         }
3399
3400         if (ext4_should_journal_data(inode)) {
3401                 BUFFER_TRACE(bh, "get write access");
3402                 err = ext4_journal_get_write_access(handle, bh);
3403                 if (err)
3404                         goto unlock;
3405         }
3406
3407         zero_user(page, offset, length);
3408
3409         BUFFER_TRACE(bh, "zeroed end of block");
3410
3411         err = 0;
3412         if (ext4_should_journal_data(inode)) {
3413                 err = ext4_handle_dirty_metadata(handle, inode, bh);
3414         } else
3415                 mark_buffer_dirty(bh);
3416
3417 unlock:
3418         unlock_page(page);
3419         page_cache_release(page);
3420         return err;
3421 }
3422
3423 int ext4_can_truncate(struct inode *inode)
3424 {
3425         if (S_ISREG(inode->i_mode))
3426                 return 1;
3427         if (S_ISDIR(inode->i_mode))
3428                 return 1;
3429         if (S_ISLNK(inode->i_mode))
3430                 return !ext4_inode_is_fast_symlink(inode);
3431         return 0;
3432 }
3433
3434 /*
3435  * ext4_punch_hole: punches a hole in a file by releaseing the blocks
3436  * associated with the given offset and length
3437  *
3438  * @inode:  File inode
3439  * @offset: The offset where the hole will begin
3440  * @len:    The length of the hole
3441  *
3442  * Returns: 0 on sucess or negative on failure
3443  */
3444
3445 int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
3446 {
3447         struct inode *inode = file->f_path.dentry->d_inode;
3448         if (!S_ISREG(inode->i_mode))
3449                 return -ENOTSUPP;
3450
3451         if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
3452                 /* TODO: Add support for non extent hole punching */
3453                 return -ENOTSUPP;
3454         }
3455
3456         if (EXT4_SB(inode->i_sb)->s_cluster_ratio > 1) {
3457                 /* TODO: Add support for bigalloc file systems */
3458                 return -ENOTSUPP;
3459         }
3460
3461         return ext4_ext_punch_hole(file, offset, length);
3462 }
3463
3464 /*
3465  * ext4_truncate()
3466  *
3467  * We block out ext4_get_block() block instantiations across the entire
3468  * transaction, and VFS/VM ensures that ext4_truncate() cannot run
3469  * simultaneously on behalf of the same inode.
3470  *
3471  * As we work through the truncate and commit bits of it to the journal there
3472  * is one core, guiding principle: the file's tree must always be consistent on
3473  * disk.  We must be able to restart the truncate after a crash.
3474  *
3475  * The file's tree may be transiently inconsistent in memory (although it
3476  * probably isn't), but whenever we close off and commit a journal transaction,
3477  * the contents of (the filesystem + the journal) must be consistent and
3478  * restartable.  It's pretty simple, really: bottom up, right to left (although
3479  * left-to-right works OK too).
3480  *
3481  * Note that at recovery time, journal replay occurs *before* the restart of
3482  * truncate against the orphan inode list.
3483  *
3484  * The committed inode has the new, desired i_size (which is the same as
3485  * i_disksize in this case).  After a crash, ext4_orphan_cleanup() will see
3486  * that this inode's truncate did not complete and it will again call
3487  * ext4_truncate() to have another go.  So there will be instantiated blocks
3488  * to the right of the truncation point in a crashed ext4 filesystem.  But
3489  * that's fine - as long as they are linked from the inode, the post-crash
3490  * ext4_truncate() run will find them and release them.
3491  */
3492 void ext4_truncate(struct inode *inode)
3493 {
3494         trace_ext4_truncate_enter(inode);
3495
3496         if (!ext4_can_truncate(inode))
3497                 return;
3498
3499         ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3500
3501         if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
3502                 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
3503
3504         if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3505                 ext4_ext_truncate(inode);
3506         else
3507                 ext4_ind_truncate(inode);
3508
3509         trace_ext4_truncate_exit(inode);
3510 }
3511
3512 /*
3513  * ext4_get_inode_loc returns with an extra refcount against the inode's
3514  * underlying buffer_head on success. If 'in_mem' is true, we have all
3515  * data in memory that is needed to recreate the on-disk version of this
3516  * inode.
3517  */
3518 static int __ext4_get_inode_loc(struct inode *inode,
3519                                 struct ext4_iloc *iloc, int in_mem)
3520 {
3521         struct ext4_group_desc  *gdp;
3522         struct buffer_head      *bh;
3523         struct super_block      *sb = inode->i_sb;
3524         ext4_fsblk_t            block;
3525         int                     inodes_per_block, inode_offset;
3526
3527         iloc->bh = NULL;
3528         if (!ext4_valid_inum(sb, inode->i_ino))
3529                 return -EIO;
3530
3531         iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
3532         gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
3533         if (!gdp)
3534                 return -EIO;
3535
3536         /*
3537          * Figure out the offset within the block group inode table
3538          */
3539         inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
3540         inode_offset = ((inode->i_ino - 1) %
3541                         EXT4_INODES_PER_GROUP(sb));
3542         block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
3543         iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
3544
3545         bh = sb_getblk(sb, block);
3546         if (!bh) {
3547                 EXT4_ERROR_INODE_BLOCK(inode, block,
3548                                        "unable to read itable block");
3549                 return -EIO;
3550         }
3551         if (!buffer_uptodate(bh)) {
3552                 lock_buffer(bh);
3553
3554                 /*
3555                  * If the buffer has the write error flag, we have failed
3556                  * to write out another inode in the same block.  In this
3557                  * case, we don't have to read the block because we may
3558                  * read the old inode data successfully.
3559                  */
3560                 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
3561                         set_buffer_uptodate(bh);
3562
3563                 if (buffer_uptodate(bh)) {
3564                         /* someone brought it uptodate while we waited */
3565                         unlock_buffer(bh);
3566                         goto has_buffer;
3567                 }
3568
3569                 /*
3570                  * If we have all information of the inode in memory and this
3571                  * is the only valid inode in the block, we need not read the
3572                  * block.
3573                  */
3574                 if (in_mem) {
3575                         struct buffer_head *bitmap_bh;
3576                         int i, start;
3577
3578                         start = inode_offset & ~(inodes_per_block - 1);
3579
3580                         /* Is the inode bitmap in cache? */
3581                         bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
3582                         if (!bitmap_bh)
3583                                 goto make_io;
3584
3585                         /*
3586                          * If the inode bitmap isn't in cache then the
3587                          * optimisation may end up performing two reads instead
3588                          * of one, so skip it.
3589                          */
3590                         if (!buffer_uptodate(bitmap_bh)) {
3591                                 brelse(bitmap_bh);
3592                                 goto make_io;
3593                         }
3594                         for (i = start; i < start + inodes_per_block; i++) {
3595                                 if (i == inode_offset)
3596                                         continue;
3597                                 if (ext4_test_bit(i, bitmap_bh->b_data))
3598                                         break;
3599                         }
3600                         brelse(bitmap_bh);
3601                         if (i == start + inodes_per_block) {
3602                                 /* all other inodes are free, so skip I/O */
3603                                 memset(bh->b_data, 0, bh->b_size);
3604                                 set_buffer_uptodate(bh);
3605                                 unlock_buffer(bh);
3606                                 goto has_buffer;
3607                         }
3608                 }
3609
3610 make_io:
3611                 /*
3612                  * If we need to do any I/O, try to pre-readahead extra
3613                  * blocks from the inode table.
3614                  */
3615                 if (EXT4_SB(sb)->s_inode_readahead_blks) {
3616                         ext4_fsblk_t b, end, table;
3617                         unsigned num;
3618
3619                         table = ext4_inode_table(sb, gdp);
3620                         /* s_inode_readahead_blks is always a power of 2 */
3621                         b = block & ~(EXT4_SB(sb)->s_inode_readahead_blks-1);
3622                         if (table > b)
3623                                 b = table;
3624                         end = b + EXT4_SB(sb)->s_inode_readahead_blks;
3625                         num = EXT4_INODES_PER_GROUP(sb);
3626                         if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
3627                                        EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
3628                                 num -= ext4_itable_unused_count(sb, gdp);
3629                         table += num / inodes_per_block;
3630                         if (end > table)
3631                                 end = table;
3632                         while (b <= end)
3633                                 sb_breadahead(sb, b++);
3634                 }
3635
3636                 /*
3637                  * There are other valid inodes in the buffer, this inode
3638                  * has in-inode xattrs, or we don't have this inode in memory.
3639                  * Read the block from disk.
3640                  */
3641                 trace_ext4_load_inode(inode);
3642                 get_bh(bh);
3643                 bh->b_end_io = end_buffer_read_sync;
3644                 submit_bh(READ | REQ_META | REQ_PRIO, bh);
3645                 wait_on_buffer(bh);
3646                 if (!buffer_uptodate(bh)) {
3647                         EXT4_ERROR_INODE_BLOCK(inode, block,
3648                                                "unable to read itable block");
3649                         brelse(bh);
3650                         return -EIO;
3651                 }
3652         }
3653 has_buffer:
3654         iloc->bh = bh;
3655         return 0;
3656 }
3657
3658 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
3659 {
3660         /* We have all inode data except xattrs in memory here. */
3661         return __ext4_get_inode_loc(inode, iloc,
3662                 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
3663 }
3664
3665 void ext4_set_inode_flags(struct inode *inode)
3666 {
3667         unsigned int flags = EXT4_I(inode)->i_flags;
3668
3669         inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
3670         if (flags & EXT4_SYNC_FL)
3671                 inode->i_flags |= S_SYNC;
3672         if (flags & EXT4_APPEND_FL)
3673                 inode->i_flags |= S_APPEND;
3674         if (flags & EXT4_IMMUTABLE_FL)
3675                 inode->i_flags |= S_IMMUTABLE;
3676         if (flags & EXT4_NOATIME_FL)
3677                 inode->i_flags |= S_NOATIME;
3678         if (flags & EXT4_DIRSYNC_FL)
3679                 inode->i_flags |= S_DIRSYNC;
3680 }
3681
3682 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
3683 void ext4_get_inode_flags(struct ext4_inode_info *ei)
3684 {
3685         unsigned int vfs_fl;
3686         unsigned long old_fl, new_fl;
3687
3688         do {
3689                 vfs_fl = ei->vfs_inode.i_flags;
3690                 old_fl = ei->i_flags;
3691                 new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
3692                                 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
3693                                 EXT4_DIRSYNC_FL);
3694                 if (vfs_fl & S_SYNC)
3695                         new_fl |= EXT4_SYNC_FL;
3696                 if (vfs_fl & S_APPEND)
3697                         new_fl |= EXT4_APPEND_FL;
3698                 if (vfs_fl & S_IMMUTABLE)
3699                         new_fl |= EXT4_IMMUTABLE_FL;
3700                 if (vfs_fl & S_NOATIME)
3701                         new_fl |= EXT4_NOATIME_FL;
3702                 if (vfs_fl & S_DIRSYNC)
3703                         new_fl |= EXT4_DIRSYNC_FL;
3704         } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
3705 }
3706
3707 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
3708                                   struct ext4_inode_info *ei)
3709 {
3710         blkcnt_t i_blocks ;
3711         struct inode *inode = &(ei->vfs_inode);
3712         struct super_block *sb = inode->i_sb;
3713
3714         if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
3715                                 EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
3716                 /* we are using combined 48 bit field */
3717                 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
3718                                         le32_to_cpu(raw_inode->i_blocks_lo);
3719                 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
3720                         /* i_blocks represent file system block size */
3721                         return i_blocks  << (inode->i_blkbits - 9);
3722                 } else {
3723                         return i_blocks;
3724                 }
3725         } else {
3726                 return le32_to_cpu(raw_inode->i_blocks_lo);
3727         }
3728 }
3729
3730 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
3731 {
3732         struct ext4_iloc iloc;
3733         struct ext4_inode *raw_inode;
3734         struct ext4_inode_info *ei;
3735         struct inode *inode;
3736         journal_t *journal = EXT4_SB(sb)->s_journal;
3737         long ret;
3738         int block;
3739
3740         inode = iget_locked(sb, ino);
3741         if (!inode)
3742                 return ERR_PTR(-ENOMEM);
3743         if (!(inode->i_state & I_NEW))
3744                 return inode;
3745
3746         ei = EXT4_I(inode);
3747         iloc.bh = NULL;
3748
3749         ret = __ext4_get_inode_loc(inode, &iloc, 0);
3750         if (ret < 0)
3751                 goto bad_inode;
3752         raw_inode = ext4_raw_inode(&iloc);
3753         inode->i_mode = le16_to_cpu(raw_inode->i_mode);
3754         inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
3755         inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
3756         if (!(test_opt(inode->i_sb, NO_UID32))) {
3757                 inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
3758                 inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
3759         }
3760         set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
3761
3762         ext4_clear_state_flags(ei);     /* Only relevant on 32-bit archs */
3763         ei->i_dir_start_lookup = 0;
3764         ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
3765         /* We now have enough fields to check if the inode was active or not.
3766          * This is needed because nfsd might try to access dead inodes
3767          * the test is that same one that e2fsck uses
3768          * NeilBrown 1999oct15
3769          */
3770         if (inode->i_nlink == 0) {
3771                 if (inode->i_mode == 0 ||
3772                     !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) {
3773                         /* this inode is deleted */
3774                         ret = -ESTALE;
3775                         goto bad_inode;
3776                 }
3777                 /* The only unlinked inodes we let through here have
3778                  * valid i_mode and are being read by the orphan
3779                  * recovery code: that's fine, we're about to complete
3780                  * the process of deleting those. */
3781         }
3782         ei->i_flags = le32_to_cpu(raw_inode->i_flags);
3783         inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
3784         ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
3785         if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
3786                 ei->i_file_acl |=
3787                         ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
3788         inode->i_size = ext4_isize(raw_inode);
3789         ei->i_disksize = inode->i_size;
3790 #ifdef CONFIG_QUOTA
3791         ei->i_reserved_quota = 0;
3792 #endif
3793         inode->i_generation = le32_to_cpu(raw_inode->i_generation);
3794         ei->i_block_group = iloc.block_group;
3795         ei->i_last_alloc_group = ~0;
3796         /*
3797          * NOTE! The in-memory inode i_data array is in little-endian order
3798          * even on big-endian machines: we do NOT byteswap the block numbers!
3799          */
3800         for (block = 0; block < EXT4_N_BLOCKS; block++)
3801                 ei->i_data[block] = raw_inode->i_block[block];
3802         INIT_LIST_HEAD(&ei->i_orphan);
3803
3804         /*
3805          * Set transaction id's of transactions that have to be committed
3806          * to finish f[data]sync. We set them to currently running transaction
3807          * as we cannot be sure that the inode or some of its metadata isn't
3808          * part of the transaction - the inode could have been reclaimed and
3809          * now it is reread from disk.
3810          */
3811         if (journal) {
3812                 transaction_t *transaction;
3813                 tid_t tid;
3814
3815                 read_lock(&journal->j_state_lock);
3816                 if (journal->j_running_transaction)
3817                         transaction = journal->j_running_transaction;
3818                 else
3819                         transaction = journal->j_committing_transaction;
3820                 if (transaction)
3821                         tid = transaction->t_tid;
3822                 else
3823                         tid = journal->j_commit_sequence;
3824                 read_unlock(&journal->j_state_lock);
3825                 ei->i_sync_tid = tid;
3826                 ei->i_datasync_tid = tid;
3827         }
3828
3829         if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
3830                 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
3831                 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
3832                     EXT4_INODE_SIZE(inode->i_sb)) {
3833                         ret = -EIO;
3834                         goto bad_inode;
3835                 }
3836                 if (ei->i_extra_isize == 0) {
3837                         /* The extra space is currently unused. Use it. */
3838                         ei->i_extra_isize = sizeof(struct ext4_inode) -
3839                                             EXT4_GOOD_OLD_INODE_SIZE;
3840                 } else {
3841                         __le32 *magic = (void *)raw_inode +
3842                                         EXT4_GOOD_OLD_INODE_SIZE +
3843                                         ei->i_extra_isize;
3844                         if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC))
3845                                 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
3846                 }
3847         } else
3848                 ei->i_extra_isize = 0;
3849
3850         EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
3851         EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
3852         EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
3853         EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
3854
3855         inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
3856         if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
3857                 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
3858                         inode->i_version |=
3859                         (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
3860         }
3861
3862         ret = 0;
3863         if (ei->i_file_acl &&
3864             !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
3865                 EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
3866                                  ei->i_file_acl);
3867                 ret = -EIO;
3868                 goto bad_inode;
3869         } else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
3870                 if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
3871                     (S_ISLNK(inode->i_mode) &&
3872                      !ext4_inode_is_fast_symlink(inode)))
3873                         /* Validate extent which is part of inode */
3874                         ret = ext4_ext_check_inode(inode);
3875         } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
3876                    (S_ISLNK(inode->i_mode) &&
3877                     !ext4_inode_is_fast_symlink(inode))) {
3878                 /* Validate block references which are part of inode */
3879                 ret = ext4_ind_check_inode(inode);
3880         }
3881         if (ret)
3882                 goto bad_inode;
3883
3884         if (S_ISREG(inode->i_mode)) {
3885                 inode->i_op = &ext4_file_inode_operations;
3886                 inode->i_fop = &ext4_file_operations;
3887                 ext4_set_aops(inode);
3888         } else if (S_ISDIR(inode->i_mode)) {
3889                 inode->i_op = &ext4_dir_inode_operations;
3890                 inode->i_fop = &ext4_dir_operations;
3891         } else if (S_ISLNK(inode->i_mode)) {
3892                 if (ext4_inode_is_fast_symlink(inode)) {
3893                         inode->i_op = &ext4_fast_symlink_inode_operations;
3894                         nd_terminate_link(ei->i_data, inode->i_size,
3895                                 sizeof(ei->i_data) - 1);
3896                 } else {
3897                         inode->i_op = &ext4_symlink_inode_operations;
3898                         ext4_set_aops(inode);
3899                 }
3900         } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
3901               S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
3902                 inode->i_op = &ext4_special_inode_operations;
3903                 if (raw_inode->i_block[0])
3904                         init_special_inode(inode, inode->i_mode,
3905                            old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
3906                 else
3907                         init_special_inode(inode, inode->i_mode,
3908                            new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
3909         } else {
3910                 ret = -EIO;
3911                 EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
3912                 goto bad_inode;
3913         }
3914         brelse(iloc.bh);
3915         ext4_set_inode_flags(inode);
3916         unlock_new_inode(inode);
3917         return inode;
3918
3919 bad_inode:
3920         brelse(iloc.bh);
3921         iget_failed(inode);
3922         return ERR_PTR(ret);
3923 }
3924
3925 static int ext4_inode_blocks_set(handle_t *handle,
3926                                 struct ext4_inode *raw_inode,
3927                                 struct ext4_inode_info *ei)
3928 {
3929         struct inode *inode = &(ei->vfs_inode);
3930         u64 i_blocks = inode->i_blocks;
3931         struct super_block *sb = inode->i_sb;
3932
3933         if (i_blocks <= ~0U) {
3934                 /*
3935                  * i_blocks can be represnted in a 32 bit variable
3936                  * as multiple of 512 bytes
3937                  */
3938                 raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
3939                 raw_inode->i_blocks_high = 0;
3940                 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
3941                 return 0;
3942         }
3943         if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
3944                 return -EFBIG;
3945
3946         if (i_blocks <= 0xffffffffffffULL) {
3947                 /*
3948                  * i_blocks can be represented in a 48 bit variable
3949                  * as multiple of 512 bytes
3950                  */
3951                 raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
3952                 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
3953                 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
3954         } else {
3955                 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
3956                 /* i_block is stored in file system block size */
3957                 i_blocks = i_blocks >> (inode->i_blkbits - 9);
3958                 raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
3959                 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
3960         }
3961         return 0;
3962 }
3963
3964 /*
3965  * Post the struct inode info into an on-disk inode location in the
3966  * buffer-cache.  This gobbles the caller's reference to the
3967  * buffer_head in the inode location struct.
3968  *
3969  * The caller must have write access to iloc->bh.
3970  */
3971 static int ext4_do_update_inode(handle_t *handle,
3972                                 struct inode *inode,
3973                                 struct ext4_iloc *iloc)
3974 {
3975         struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
3976         struct ext4_inode_info *ei = EXT4_I(inode);
3977         struct buffer_head *bh = iloc->bh;
3978         int err = 0, rc, block;
3979
3980         /* For fields not not tracking in the in-memory inode,
3981          * initialise them to zero for new inodes. */
3982         if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
3983                 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
3984
3985         ext4_get_inode_flags(ei);
3986         raw_inode->i_mode = cpu_to_le16(inode->i_mode);
3987         if (!(test_opt(inode->i_sb, NO_UID32))) {
3988                 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
3989                 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
3990 /*
3991  * Fix up interoperability with old kernels. Otherwise, old inodes get
3992  * re-used with the upper 16 bits of the uid/gid intact
3993  */
3994                 if (!ei->i_dtime) {
3995                         raw_inode->i_uid_high =
3996                                 cpu_to_le16(high_16_bits(inode->i_uid));
3997                         raw_inode->i_gid_high =
3998                                 cpu_to_le16(high_16_bits(inode->i_gid));
3999                 } else {
4000                         raw_inode->i_uid_high = 0;
4001                         raw_inode->i_gid_high = 0;
4002                 }
4003         } else {
4004                 raw_inode->i_uid_low =
4005                         cpu_to_le16(fs_high2lowuid(inode->i_uid));
4006                 raw_inode->i_gid_low =
4007                         cpu_to_le16(fs_high2lowgid(inode->i_gid));
4008                 raw_inode->i_uid_high = 0;
4009                 raw_inode->i_gid_high = 0;
4010         }
4011         raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4012
4013         EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4014         EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4015         EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4016         EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4017
4018         if (ext4_inode_blocks_set(handle, raw_inode, ei))
4019                 goto out_brelse;
4020         raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4021         raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4022         if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
4023             cpu_to_le32(EXT4_OS_HURD))
4024                 raw_inode->i_file_acl_high =
4025                         cpu_to_le16(ei->i_file_acl >> 32);
4026         raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4027         ext4_isize_set(raw_inode, ei->i_disksize);
4028         if (ei->i_disksize > 0x7fffffffULL) {
4029                 struct super_block *sb = inode->i_sb;
4030                 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
4031                                 EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
4032                                 EXT4_SB(sb)->s_es->s_rev_level ==
4033                                 cpu_to_le32(EXT4_GOOD_OLD_REV)) {
4034                         /* If this is the first large file
4035                          * created, add a flag to the superblock.
4036                          */
4037                         err = ext4_journal_get_write_access(handle,
4038                                         EXT4_SB(sb)->s_sbh);
4039                         if (err)
4040                                 goto out_brelse;
4041                         ext4_update_dynamic_rev(sb);
4042                         EXT4_SET_RO_COMPAT_FEATURE(sb,
4043                                         EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
4044                         sb->s_dirt = 1;
4045                         ext4_handle_sync(handle);
4046                         err = ext4_handle_dirty_metadata(handle, NULL,
4047                                         EXT4_SB(sb)->s_sbh);
4048                 }
4049         }
4050         raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4051         if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4052                 if (old_valid_dev(inode->i_rdev)) {
4053                         raw_inode->i_block[0] =
4054                                 cpu_to_le32(old_encode_dev(inode->i_rdev));
4055                         raw_inode->i_block[1] = 0;
4056                 } else {
4057                         raw_inode->i_block[0] = 0;
4058                         raw_inode->i_block[1] =
4059                                 cpu_to_le32(new_encode_dev(inode->i_rdev));
4060                         raw_inode->i_block[2] = 0;
4061                 }
4062         } else
4063                 for (block = 0; block < EXT4_N_BLOCKS; block++)
4064                         raw_inode->i_block[block] = ei->i_data[block];
4065
4066         raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
4067         if (ei->i_extra_isize) {
4068                 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4069                         raw_inode->i_version_hi =
4070                         cpu_to_le32(inode->i_version >> 32);
4071                 raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
4072         }
4073
4074         BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4075         rc = ext4_handle_dirty_metadata(handle, NULL, bh);
4076         if (!err)
4077                 err = rc;
4078         ext4_clear_inode_state(inode, EXT4_STATE_NEW);
4079
4080         ext4_update_inode_fsync_trans(handle, inode, 0);
4081 out_brelse:
4082         brelse(bh);
4083         ext4_std_error(inode->i_sb, err);
4084         return err;
4085 }
4086
4087 /*
4088  * ext4_write_inode()
4089  *
4090  * We are called from a few places:
4091  *
4092  * - Within generic_file_write() for O_SYNC files.
4093  *   Here, there will be no transaction running. We wait for any running
4094  *   trasnaction to commit.
4095  *
4096  * - Within sys_sync(), kupdate and such.
4097  *   We wait on commit, if tol to.
4098  *
4099  * - Within prune_icache() (PF_MEMALLOC == true)
4100  *   Here we simply return.  We can't afford to block kswapd on the
4101  *   journal commit.
4102  *
4103  * In all cases it is actually safe for us to return without doing anything,
4104  * because the inode has been copied into a raw inode buffer in
4105  * ext4_mark_inode_dirty().  This is a correctness thing for O_SYNC and for
4106  * knfsd.
4107  *
4108  * Note that we are absolutely dependent upon all inode dirtiers doing the
4109  * right thing: they *must* call mark_inode_dirty() after dirtying info in
4110  * which we are interested.
4111  *
4112  * It would be a bug for them to not do this.  The code:
4113  *
4114  *      mark_inode_dirty(inode)
4115  *      stuff();
4116  *      inode->i_size = expr;
4117  *
4118  * is in error because a kswapd-driven write_inode() could occur while
4119  * `stuff()' is running, and the new i_size will be lost.  Plus the inode
4120  * will no longer be on the superblock's dirty inode list.
4121  */
4122 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
4123 {
4124         int err;
4125
4126         if (current->flags & PF_MEMALLOC)
4127                 return 0;
4128
4129         if (EXT4_SB(inode->i_sb)->s_journal) {
4130                 if (ext4_journal_current_handle()) {
4131                         jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4132                         dump_stack();
4133                         return -EIO;
4134                 }
4135
4136                 if (wbc->sync_mode != WB_SYNC_ALL)
4137                         return 0;
4138
4139                 err = ext4_force_commit(inode->i_sb);
4140         } else {
4141                 struct ext4_iloc iloc;
4142
4143                 err = __ext4_get_inode_loc(inode, &iloc, 0);
4144                 if (err)
4145                         return err;
4146                 if (wbc->sync_mode == WB_SYNC_ALL)
4147                         sync_dirty_buffer(iloc.bh);
4148                 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
4149                         EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
4150                                          "IO error syncing inode");
4151                         err = -EIO;
4152                 }
4153                 brelse(iloc.bh);
4154         }
4155         return err;
4156 }
4157
4158 /*
4159  * ext4_setattr()
4160  *
4161  * Called from notify_change.
4162  *
4163  * We want to trap VFS attempts to truncate the file as soon as
4164  * possible.  In particular, we want to make sure that when the VFS
4165  * shrinks i_size, we put the inode on the orphan list and modify
4166  * i_disksize immediately, so that during the subsequent flushing of
4167  * dirty pages and freeing of disk blocks, we can guarantee that any
4168  * commit will leave the blocks being flushed in an unused state on
4169  * disk.  (On recovery, the inode will get truncated and the blocks will
4170  * be freed, so we have a strong guarantee that no future commit will
4171  * leave these blocks visible to the user.)
4172  *
4173  * Another thing we have to assure is that if we are in ordered mode
4174  * and inode is still attached to the committing transaction, we must
4175  * we start writeout of all the dirty pages which are being truncated.
4176  * This way we are sure that all the data written in the previous
4177  * transaction are already on disk (truncate waits for pages under
4178  * writeback).
4179  *
4180  * Called with inode->i_mutex down.
4181  */
4182 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
4183 {
4184         struct inode *inode = dentry->d_inode;
4185         int error, rc = 0;
4186         int orphan = 0;
4187         const unsigned int ia_valid = attr->ia_valid;
4188
4189         error = inode_change_ok(inode, attr);
4190         if (error)
4191                 return error;
4192
4193         if (is_quota_modification(inode, attr))
4194                 dquot_initialize(inode);
4195         if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
4196                 (ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
4197                 handle_t *handle;
4198
4199                 /* (user+group)*(old+new) structure, inode write (sb,
4200                  * inode block, ? - but truncate inode update has it) */
4201                 handle = ext4_journal_start(inode, (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb)+
4202                                         EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb))+3);
4203                 if (IS_ERR(handle)) {
4204                         error = PTR_ERR(handle);
4205                         goto err_out;
4206                 }
4207                 error = dquot_transfer(inode, attr);
4208                 if (error) {
4209                         ext4_journal_stop(handle);
4210                         return error;
4211                 }
4212                 /* Update corresponding info in inode so that everything is in
4213                  * one transaction */
4214                 if (attr->ia_valid & ATTR_UID)
4215                         inode->i_uid = attr->ia_uid;
4216                 if (attr->ia_valid & ATTR_GID)
4217                         inode->i_gid = attr->ia_gid;
4218                 error = ext4_mark_inode_dirty(handle, inode);
4219                 ext4_journal_stop(handle);
4220         }
4221
4222         if (attr->ia_valid & ATTR_SIZE) {
4223                 inode_dio_wait(inode);
4224
4225                 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4226                         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4227
4228                         if (attr->ia_size > sbi->s_bitmap_maxbytes)
4229                                 return -EFBIG;
4230                 }
4231         }
4232
4233         if (S_ISREG(inode->i_mode) &&
4234             attr->ia_valid & ATTR_SIZE &&
4235             (attr->ia_size < inode->i_size)) {
4236                 handle_t *handle;
4237
4238                 handle = ext4_journal_start(inode, 3);
4239                 if (IS_ERR(handle)) {
4240                         error = PTR_ERR(handle);
4241                         goto err_out;
4242                 }
4243                 if (ext4_handle_valid(handle)) {
4244                         error = ext4_orphan_add(handle, inode);
4245                         orphan = 1;
4246                 }
4247                 EXT4_I(inode)->i_disksize = attr->ia_size;
4248                 rc = ext4_mark_inode_dirty(handle, inode);
4249                 if (!error)
4250                         error = rc;
4251                 ext4_journal_stop(handle);
4252
4253                 if (ext4_should_order_data(inode)) {
4254                         error = ext4_begin_ordered_truncate(inode,
4255                                                             attr->ia_size);
4256                         if (error) {
4257                                 /* Do as much error cleanup as possible */
4258                                 handle = ext4_journal_start(inode, 3);
4259                                 if (IS_ERR(handle)) {
4260                                         ext4_orphan_del(NULL, inode);
4261                                         goto err_out;
4262                                 }
4263                                 ext4_orphan_del(handle, inode);
4264                                 orphan = 0;
4265                                 ext4_journal_stop(handle);
4266                                 goto err_out;
4267                         }
4268                 }
4269         }
4270
4271         if (attr->ia_valid & ATTR_SIZE) {
4272                 if (attr->ia_size != i_size_read(inode)) {
4273                         truncate_setsize(inode, attr->ia_size);
4274                         ext4_truncate(inode);
4275                 } else if (ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
4276                         ext4_truncate(inode);
4277         }
4278
4279         if (!rc) {
4280                 setattr_copy(inode, attr);
4281                 mark_inode_dirty(inode);
4282         }
4283
4284         /*
4285          * If the call to ext4_truncate failed to get a transaction handle at
4286          * all, we need to clean up the in-core orphan list manually.
4287          */
4288         if (orphan && inode->i_nlink)
4289                 ext4_orphan_del(NULL, inode);
4290
4291         if (!rc && (ia_valid & ATTR_MODE))
4292                 rc = ext4_acl_chmod(inode);
4293
4294 err_out:
4295         ext4_std_error(inode->i_sb, error);
4296         if (!error)
4297                 error = rc;
4298         return error;
4299 }
4300
4301 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
4302                  struct kstat *stat)
4303 {
4304         struct inode *inode;
4305         unsigned long delalloc_blocks;
4306
4307         inode = dentry->d_inode;
4308         generic_fillattr(inode, stat);
4309
4310         /*
4311          * We can't update i_blocks if the block allocation is delayed
4312          * otherwise in the case of system crash before the real block
4313          * allocation is done, we will have i_blocks inconsistent with
4314          * on-disk file blocks.
4315          * We always keep i_blocks updated together with real
4316          * allocation. But to not confuse with user, stat
4317          * will return the blocks that include the delayed allocation
4318          * blocks for this file.
4319          */
4320         delalloc_blocks = EXT4_I(inode)->i_reserved_data_blocks;
4321
4322         stat->blocks += (delalloc_blocks << inode->i_sb->s_blocksize_bits)>>9;
4323         return 0;
4324 }
4325
4326 static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4327 {
4328         if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
4329                 return ext4_ind_trans_blocks(inode, nrblocks, chunk);
4330         return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
4331 }
4332
4333 /*
4334  * Account for index blocks, block groups bitmaps and block group
4335  * descriptor blocks if modify datablocks and index blocks
4336  * worse case, the indexs blocks spread over different block groups
4337  *
4338  * If datablocks are discontiguous, they are possible to spread over
4339  * different block groups too. If they are contiuguous, with flexbg,
4340  * they could still across block group boundary.
4341  *
4342  * Also account for superblock, inode, quota and xattr blocks
4343  */
4344 static int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4345 {
4346         ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
4347         int gdpblocks;
4348         int idxblocks;
4349         int ret = 0;
4350
4351         /*
4352          * How many index blocks need to touch to modify nrblocks?
4353          * The "Chunk" flag indicating whether the nrblocks is
4354          * physically contiguous on disk
4355          *
4356          * For Direct IO and fallocate, they calls get_block to allocate
4357          * one single extent at a time, so they could set the "Chunk" flag
4358          */
4359         idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
4360
4361         ret = idxblocks;
4362
4363         /*
4364          * Now let's see how many group bitmaps and group descriptors need
4365          * to account
4366          */
4367         groups = idxblocks;
4368         if (chunk)
4369                 groups += 1;
4370         else
4371                 groups += nrblocks;
4372
4373         gdpblocks = groups;
4374         if (groups > ngroups)
4375                 groups = ngroups;
4376         if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
4377                 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
4378
4379         /* bitmaps and block group descriptor blocks */
4380         ret += groups + gdpblocks;
4381
4382         /* Blocks for super block, inode, quota and xattr blocks */
4383         ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
4384
4385         return ret;
4386 }
4387
4388 /*
4389  * Calculate the total number of credits to reserve to fit
4390  * the modification of a single pages into a single transaction,
4391  * which may include multiple chunks of block allocations.
4392  *
4393  * This could be called via ext4_write_begin()
4394  *
4395  * We need to consider the worse case, when
4396  * one new block per extent.
4397  */
4398 int ext4_writepage_trans_blocks(struct inode *inode)
4399 {
4400         int bpp = ext4_journal_blocks_per_page(inode);
4401         int ret;
4402
4403         ret = ext4_meta_trans_blocks(inode, bpp, 0);
4404
4405         /* Account for data blocks for journalled mode */
4406         if (ext4_should_journal_data(inode))
4407                 ret += bpp;
4408         return ret;
4409 }
4410
4411 /*
4412  * Calculate the journal credits for a chunk of data modification.
4413  *
4414  * This is called from DIO, fallocate or whoever calling
4415  * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
4416  *
4417  * journal buffers for data blocks are not included here, as DIO
4418  * and fallocate do no need to journal data buffers.
4419  */
4420 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
4421 {
4422         return ext4_meta_trans_blocks(inode, nrblocks, 1);
4423 }
4424
4425 /*
4426  * The caller must have previously called ext4_reserve_inode_write().
4427  * Give this, we know that the caller already has write access to iloc->bh.
4428  */
4429 int ext4_mark_iloc_dirty(handle_t *handle,
4430                          struct inode *inode, struct ext4_iloc *iloc)
4431 {
4432         int err = 0;
4433
4434         if (test_opt(inode->i_sb, I_VERSION))
4435                 inode_inc_iversion(inode);
4436
4437         /* the do_update_inode consumes one bh->b_count */
4438         get_bh(iloc->bh);
4439
4440         /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
4441         err = ext4_do_update_inode(handle, inode, iloc);
4442         put_bh(iloc->bh);
4443         return err;
4444 }
4445
4446 /*
4447  * On success, We end up with an outstanding reference count against
4448  * iloc->bh.  This _must_ be cleaned up later.
4449  */
4450
4451 int
4452 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
4453                          struct ext4_iloc *iloc)
4454 {
4455         int err;
4456
4457         err = ext4_get_inode_loc(inode, iloc);
4458         if (!err) {
4459                 BUFFER_TRACE(iloc->bh, "get_write_access");
4460                 err = ext4_journal_get_write_access(handle, iloc->bh);
4461                 if (err) {
4462                         brelse(iloc->bh);
4463                         iloc->bh = NULL;
4464                 }
4465         }
4466         ext4_std_error(inode->i_sb, err);
4467         return err;
4468 }
4469
4470 /*
4471  * Expand an inode by new_extra_isize bytes.
4472  * Returns 0 on success or negative error number on failure.
4473  */
4474 static int ext4_expand_extra_isize(struct inode *inode,
4475                                    unsigned int new_extra_isize,
4476                                    struct ext4_iloc iloc,
4477                                    handle_t *handle)
4478 {
4479         struct ext4_inode *raw_inode;
4480         struct ext4_xattr_ibody_header *header;
4481
4482         if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
4483                 return 0;
4484
4485         raw_inode = ext4_raw_inode(&iloc);
4486
4487         header = IHDR(inode, raw_inode);
4488
4489         /* No extended attributes present */
4490         if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
4491             header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
4492                 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
4493                         new_extra_isize);
4494                 EXT4_I(inode)->i_extra_isize = new_extra_isize;
4495                 return 0;
4496         }
4497
4498         /* try to expand with EAs present */
4499         return ext4_expand_extra_isize_ea(inode, new_extra_isize,
4500                                           raw_inode, handle);
4501 }
4502
4503 /*
4504  * What we do here is to mark the in-core inode as clean with respect to inode
4505  * dirtiness (it may still be data-dirty).
4506  * This means that the in-core inode may be reaped by prune_icache
4507  * without having to perform any I/O.  This is a very good thing,
4508  * because *any* task may call prune_icache - even ones which
4509  * have a transaction open against a different journal.
4510  *
4511  * Is this cheating?  Not really.  Sure, we haven't written the
4512  * inode out, but prune_icache isn't a user-visible syncing function.
4513  * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
4514  * we start and wait on commits.
4515  *
4516  * Is this efficient/effective?  Well, we're being nice to the system
4517  * by cleaning up our inodes proactively so they can be reaped
4518  * without I/O.  But we are potentially leaving up to five seconds'
4519  * worth of inodes floating about which prune_icache wants us to
4520  * write out.  One way to fix that would be to get prune_icache()
4521  * to do a write_super() to free up some memory.  It has the desired
4522  * effect.
4523  */
4524 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
4525 {
4526         struct ext4_iloc iloc;
4527         struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4528         static unsigned int mnt_count;
4529         int err, ret;
4530
4531         might_sleep();
4532         trace_ext4_mark_inode_dirty(inode, _RET_IP_);
4533         err = ext4_reserve_inode_write(handle, inode, &iloc);
4534         if (ext4_handle_valid(handle) &&
4535             EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
4536             !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
4537                 /*
4538                  * We need extra buffer credits since we may write into EA block
4539                  * with this same handle. If journal_extend fails, then it will
4540                  * only result in a minor loss of functionality for that inode.
4541                  * If this is felt to be critical, then e2fsck should be run to
4542                  * force a large enough s_min_extra_isize.
4543                  */
4544                 if ((jbd2_journal_extend(handle,
4545                              EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
4546                         ret = ext4_expand_extra_isize(inode,
4547                                                       sbi->s_want_extra_isize,
4548                                                       iloc, handle);
4549                         if (ret) {
4550                                 ext4_set_inode_state(inode,
4551                                                      EXT4_STATE_NO_EXPAND);
4552                                 if (mnt_count !=
4553                                         le16_to_cpu(sbi->s_es->s_mnt_count)) {
4554                                         ext4_warning(inode->i_sb,
4555                                         "Unable to expand inode %lu. Delete"
4556                                         " some EAs or run e2fsck.",
4557                                         inode->i_ino);
4558                                         mnt_count =
4559                                           le16_to_cpu(sbi->s_es->s_mnt_count);
4560                                 }
4561                         }
4562                 }
4563         }
4564         if (!err)
4565                 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
4566         return err;
4567 }
4568
4569 /*
4570  * ext4_dirty_inode() is called from __mark_inode_dirty()
4571  *
4572  * We're really interested in the case where a file is being extended.
4573  * i_size has been changed by generic_commit_write() and we thus need
4574  * to include the updated inode in the current transaction.
4575  *
4576  * Also, dquot_alloc_block() will always dirty the inode when blocks
4577  * are allocated to the file.
4578  *
4579  * If the inode is marked synchronous, we don't honour that here - doing
4580  * so would cause a commit on atime updates, which we don't bother doing.
4581  * We handle synchronous inodes at the highest possible level.
4582  */
4583 void ext4_dirty_inode(struct inode *inode, int flags)
4584 {
4585         handle_t *handle;
4586
4587         handle = ext4_journal_start(inode, 2);
4588         if (IS_ERR(handle))
4589                 goto out;
4590
4591         ext4_mark_inode_dirty(handle, inode);
4592
4593         ext4_journal_stop(handle);
4594 out:
4595         return;
4596 }
4597
4598 #if 0
4599 /*
4600  * Bind an inode's backing buffer_head into this transaction, to prevent
4601  * it from being flushed to disk early.  Unlike
4602  * ext4_reserve_inode_write, this leaves behind no bh reference and
4603  * returns no iloc structure, so the caller needs to repeat the iloc
4604  * lookup to mark the inode dirty later.
4605  */
4606 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
4607 {
4608         struct ext4_iloc iloc;
4609
4610         int err = 0;
4611         if (handle) {
4612                 err = ext4_get_inode_loc(inode, &iloc);
4613                 if (!err) {
4614                         BUFFER_TRACE(iloc.bh, "get_write_access");
4615                         err = jbd2_journal_get_write_access(handle, iloc.bh);
4616                         if (!err)
4617                                 err = ext4_handle_dirty_metadata(handle,
4618                                                                  NULL,
4619                                                                  iloc.bh);
4620                         brelse(iloc.bh);
4621                 }
4622         }
4623         ext4_std_error(inode->i_sb, err);
4624         return err;
4625 }
4626 #endif
4627
4628 int ext4_change_inode_journal_flag(struct inode *inode, int val)
4629 {
4630         journal_t *journal;
4631         handle_t *handle;
4632         int err;
4633
4634         /*
4635          * We have to be very careful here: changing a data block's
4636          * journaling status dynamically is dangerous.  If we write a
4637          * data block to the journal, change the status and then delete
4638          * that block, we risk forgetting to revoke the old log record
4639          * from the journal and so a subsequent replay can corrupt data.
4640          * So, first we make sure that the journal is empty and that
4641          * nobody is changing anything.
4642          */
4643
4644         journal = EXT4_JOURNAL(inode);
4645         if (!journal)
4646                 return 0;
4647         if (is_journal_aborted(journal))
4648                 return -EROFS;
4649
4650         jbd2_journal_lock_updates(journal);
4651         jbd2_journal_flush(journal);
4652
4653         /*
4654          * OK, there are no updates running now, and all cached data is
4655          * synced to disk.  We are now in a completely consistent state
4656          * which doesn't have anything in the journal, and we know that
4657          * no filesystem updates are running, so it is safe to modify
4658          * the inode's in-core data-journaling state flag now.
4659          */
4660
4661         if (val)
4662                 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
4663         else
4664                 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
4665         ext4_set_aops(inode);
4666
4667         jbd2_journal_unlock_updates(journal);
4668
4669         /* Finally we can mark the inode as dirty. */
4670
4671         handle = ext4_journal_start(inode, 1);
4672         if (IS_ERR(handle))
4673                 return PTR_ERR(handle);
4674
4675         err = ext4_mark_inode_dirty(handle, inode);
4676         ext4_handle_sync(handle);
4677         ext4_journal_stop(handle);
4678         ext4_std_error(inode->i_sb, err);
4679
4680         return err;
4681 }
4682
4683 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
4684 {
4685         return !buffer_mapped(bh);
4686 }
4687
4688 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
4689 {
4690         struct page *page = vmf->page;
4691         loff_t size;
4692         unsigned long len;
4693         int ret;
4694         struct file *file = vma->vm_file;
4695         struct inode *inode = file->f_path.dentry->d_inode;
4696         struct address_space *mapping = inode->i_mapping;
4697         handle_t *handle;
4698         get_block_t *get_block;
4699         int retries = 0;
4700
4701         /*
4702          * This check is racy but catches the common case. We rely on
4703          * __block_page_mkwrite() to do a reliable check.
4704          */
4705         vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
4706         /* Delalloc case is easy... */
4707         if (test_opt(inode->i_sb, DELALLOC) &&
4708             !ext4_should_journal_data(inode) &&
4709             !ext4_nonda_switch(inode->i_sb)) {
4710                 do {
4711                         ret = __block_page_mkwrite(vma, vmf,
4712                                                    ext4_da_get_block_prep);
4713                 } while (ret == -ENOSPC &&
4714                        ext4_should_retry_alloc(inode->i_sb, &retries));
4715                 goto out_ret;
4716         }
4717
4718         lock_page(page);
4719         size = i_size_read(inode);
4720         /* Page got truncated from under us? */
4721         if (page->mapping != mapping || page_offset(page) > size) {
4722                 unlock_page(page);
4723                 ret = VM_FAULT_NOPAGE;
4724                 goto out;
4725         }
4726
4727         if (page->index == size >> PAGE_CACHE_SHIFT)
4728                 len = size & ~PAGE_CACHE_MASK;
4729         else
4730                 len = PAGE_CACHE_SIZE;
4731         /*
4732          * Return if we have all the buffers mapped. This avoids the need to do
4733          * journal_start/journal_stop which can block and take a long time
4734          */
4735         if (page_has_buffers(page)) {
4736                 if (!walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
4737                                         ext4_bh_unmapped)) {
4738                         /* Wait so that we don't change page under IO */
4739                         wait_on_page_writeback(page);
4740                         ret = VM_FAULT_LOCKED;
4741                         goto out;
4742                 }
4743         }
4744         unlock_page(page);
4745         /* OK, we need to fill the hole... */
4746         if (ext4_should_dioread_nolock(inode))
4747                 get_block = ext4_get_block_write;
4748         else
4749                 get_block = ext4_get_block;
4750 retry_alloc:
4751         handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
4752         if (IS_ERR(handle)) {
4753                 ret = VM_FAULT_SIGBUS;
4754                 goto out;
4755         }
4756         ret = __block_page_mkwrite(vma, vmf, get_block);
4757         if (!ret && ext4_should_journal_data(inode)) {
4758                 if (walk_page_buffers(handle, page_buffers(page), 0,
4759                           PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) {
4760                         unlock_page(page);
4761                         ret = VM_FAULT_SIGBUS;
4762                         ext4_journal_stop(handle);
4763                         goto out;
4764                 }
4765                 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
4766         }
4767         ext4_journal_stop(handle);
4768         if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
4769                 goto retry_alloc;
4770 out_ret:
4771         ret = block_page_mkwrite_return(ret);
4772 out:
4773         return ret;
4774 }