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