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