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