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