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