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