Merge branch 'integration' into for-linus
[pandora-kernel.git] / fs / btrfs / inode.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
23 #include <linux/fs.h>
24 #include <linux/pagemap.h>
25 #include <linux/highmem.h>
26 #include <linux/time.h>
27 #include <linux/init.h>
28 #include <linux/string.h>
29 #include <linux/backing-dev.h>
30 #include <linux/mpage.h>
31 #include <linux/swap.h>
32 #include <linux/writeback.h>
33 #include <linux/statfs.h>
34 #include <linux/compat.h>
35 #include <linux/bit_spinlock.h>
36 #include <linux/xattr.h>
37 #include <linux/posix_acl.h>
38 #include <linux/falloc.h>
39 #include <linux/slab.h>
40 #include <linux/ratelimit.h>
41 #include "compat.h"
42 #include "ctree.h"
43 #include "disk-io.h"
44 #include "transaction.h"
45 #include "btrfs_inode.h"
46 #include "ioctl.h"
47 #include "print-tree.h"
48 #include "volumes.h"
49 #include "ordered-data.h"
50 #include "xattr.h"
51 #include "tree-log.h"
52 #include "compression.h"
53 #include "locking.h"
54 #include "free-space-cache.h"
55 #include "inode-map.h"
56
57 struct btrfs_iget_args {
58         u64 ino;
59         struct btrfs_root *root;
60 };
61
62 static const struct inode_operations btrfs_dir_inode_operations;
63 static const struct inode_operations btrfs_symlink_inode_operations;
64 static const struct inode_operations btrfs_dir_ro_inode_operations;
65 static const struct inode_operations btrfs_special_inode_operations;
66 static const struct inode_operations btrfs_file_inode_operations;
67 static const struct address_space_operations btrfs_aops;
68 static const struct address_space_operations btrfs_symlink_aops;
69 static const struct file_operations btrfs_dir_file_operations;
70 static struct extent_io_ops btrfs_extent_io_ops;
71
72 static struct kmem_cache *btrfs_inode_cachep;
73 struct kmem_cache *btrfs_trans_handle_cachep;
74 struct kmem_cache *btrfs_transaction_cachep;
75 struct kmem_cache *btrfs_path_cachep;
76 struct kmem_cache *btrfs_free_space_cachep;
77
78 #define S_SHIFT 12
79 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
80         [S_IFREG >> S_SHIFT]    = BTRFS_FT_REG_FILE,
81         [S_IFDIR >> S_SHIFT]    = BTRFS_FT_DIR,
82         [S_IFCHR >> S_SHIFT]    = BTRFS_FT_CHRDEV,
83         [S_IFBLK >> S_SHIFT]    = BTRFS_FT_BLKDEV,
84         [S_IFIFO >> S_SHIFT]    = BTRFS_FT_FIFO,
85         [S_IFSOCK >> S_SHIFT]   = BTRFS_FT_SOCK,
86         [S_IFLNK >> S_SHIFT]    = BTRFS_FT_SYMLINK,
87 };
88
89 static int btrfs_setsize(struct inode *inode, loff_t newsize);
90 static int btrfs_truncate(struct inode *inode);
91 static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end);
92 static noinline int cow_file_range(struct inode *inode,
93                                    struct page *locked_page,
94                                    u64 start, u64 end, int *page_started,
95                                    unsigned long *nr_written, int unlock);
96
97 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
98                                      struct inode *inode,  struct inode *dir,
99                                      const struct qstr *qstr)
100 {
101         int err;
102
103         err = btrfs_init_acl(trans, inode, dir);
104         if (!err)
105                 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
106         return err;
107 }
108
109 /*
110  * this does all the hard work for inserting an inline extent into
111  * the btree.  The caller should have done a btrfs_drop_extents so that
112  * no overlapping inline items exist in the btree
113  */
114 static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
115                                 struct btrfs_root *root, struct inode *inode,
116                                 u64 start, size_t size, size_t compressed_size,
117                                 int compress_type,
118                                 struct page **compressed_pages)
119 {
120         struct btrfs_key key;
121         struct btrfs_path *path;
122         struct extent_buffer *leaf;
123         struct page *page = NULL;
124         char *kaddr;
125         unsigned long ptr;
126         struct btrfs_file_extent_item *ei;
127         int err = 0;
128         int ret;
129         size_t cur_size = size;
130         size_t datasize;
131         unsigned long offset;
132
133         if (compressed_size && compressed_pages)
134                 cur_size = compressed_size;
135
136         path = btrfs_alloc_path();
137         if (!path)
138                 return -ENOMEM;
139
140         path->leave_spinning = 1;
141
142         key.objectid = btrfs_ino(inode);
143         key.offset = start;
144         btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
145         datasize = btrfs_file_extent_calc_inline_size(cur_size);
146
147         inode_add_bytes(inode, size);
148         ret = btrfs_insert_empty_item(trans, root, path, &key,
149                                       datasize);
150         BUG_ON(ret);
151         if (ret) {
152                 err = ret;
153                 goto fail;
154         }
155         leaf = path->nodes[0];
156         ei = btrfs_item_ptr(leaf, path->slots[0],
157                             struct btrfs_file_extent_item);
158         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
159         btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
160         btrfs_set_file_extent_encryption(leaf, ei, 0);
161         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
162         btrfs_set_file_extent_ram_bytes(leaf, ei, size);
163         ptr = btrfs_file_extent_inline_start(ei);
164
165         if (compress_type != BTRFS_COMPRESS_NONE) {
166                 struct page *cpage;
167                 int i = 0;
168                 while (compressed_size > 0) {
169                         cpage = compressed_pages[i];
170                         cur_size = min_t(unsigned long, compressed_size,
171                                        PAGE_CACHE_SIZE);
172
173                         kaddr = kmap_atomic(cpage, KM_USER0);
174                         write_extent_buffer(leaf, kaddr, ptr, cur_size);
175                         kunmap_atomic(kaddr, KM_USER0);
176
177                         i++;
178                         ptr += cur_size;
179                         compressed_size -= cur_size;
180                 }
181                 btrfs_set_file_extent_compression(leaf, ei,
182                                                   compress_type);
183         } else {
184                 page = find_get_page(inode->i_mapping,
185                                      start >> PAGE_CACHE_SHIFT);
186                 btrfs_set_file_extent_compression(leaf, ei, 0);
187                 kaddr = kmap_atomic(page, KM_USER0);
188                 offset = start & (PAGE_CACHE_SIZE - 1);
189                 write_extent_buffer(leaf, kaddr + offset, ptr, size);
190                 kunmap_atomic(kaddr, KM_USER0);
191                 page_cache_release(page);
192         }
193         btrfs_mark_buffer_dirty(leaf);
194         btrfs_free_path(path);
195
196         /*
197          * we're an inline extent, so nobody can
198          * extend the file past i_size without locking
199          * a page we already have locked.
200          *
201          * We must do any isize and inode updates
202          * before we unlock the pages.  Otherwise we
203          * could end up racing with unlink.
204          */
205         BTRFS_I(inode)->disk_i_size = inode->i_size;
206         btrfs_update_inode(trans, root, inode);
207
208         return 0;
209 fail:
210         btrfs_free_path(path);
211         return err;
212 }
213
214
215 /*
216  * conditionally insert an inline extent into the file.  This
217  * does the checks required to make sure the data is small enough
218  * to fit as an inline extent.
219  */
220 static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
221                                  struct btrfs_root *root,
222                                  struct inode *inode, u64 start, u64 end,
223                                  size_t compressed_size, int compress_type,
224                                  struct page **compressed_pages)
225 {
226         u64 isize = i_size_read(inode);
227         u64 actual_end = min(end + 1, isize);
228         u64 inline_len = actual_end - start;
229         u64 aligned_end = (end + root->sectorsize - 1) &
230                         ~((u64)root->sectorsize - 1);
231         u64 hint_byte;
232         u64 data_len = inline_len;
233         int ret;
234
235         if (compressed_size)
236                 data_len = compressed_size;
237
238         if (start > 0 ||
239             actual_end >= PAGE_CACHE_SIZE ||
240             data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
241             (!compressed_size &&
242             (actual_end & (root->sectorsize - 1)) == 0) ||
243             end + 1 < isize ||
244             data_len > root->fs_info->max_inline) {
245                 return 1;
246         }
247
248         ret = btrfs_drop_extents(trans, inode, start, aligned_end,
249                                  &hint_byte, 1);
250         BUG_ON(ret);
251
252         if (isize > actual_end)
253                 inline_len = min_t(u64, isize, actual_end);
254         ret = insert_inline_extent(trans, root, inode, start,
255                                    inline_len, compressed_size,
256                                    compress_type, compressed_pages);
257         BUG_ON(ret);
258         btrfs_delalloc_release_metadata(inode, end + 1 - start);
259         btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
260         return 0;
261 }
262
263 struct async_extent {
264         u64 start;
265         u64 ram_size;
266         u64 compressed_size;
267         struct page **pages;
268         unsigned long nr_pages;
269         int compress_type;
270         struct list_head list;
271 };
272
273 struct async_cow {
274         struct inode *inode;
275         struct btrfs_root *root;
276         struct page *locked_page;
277         u64 start;
278         u64 end;
279         struct list_head extents;
280         struct btrfs_work work;
281 };
282
283 static noinline int add_async_extent(struct async_cow *cow,
284                                      u64 start, u64 ram_size,
285                                      u64 compressed_size,
286                                      struct page **pages,
287                                      unsigned long nr_pages,
288                                      int compress_type)
289 {
290         struct async_extent *async_extent;
291
292         async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
293         BUG_ON(!async_extent);
294         async_extent->start = start;
295         async_extent->ram_size = ram_size;
296         async_extent->compressed_size = compressed_size;
297         async_extent->pages = pages;
298         async_extent->nr_pages = nr_pages;
299         async_extent->compress_type = compress_type;
300         list_add_tail(&async_extent->list, &cow->extents);
301         return 0;
302 }
303
304 /*
305  * we create compressed extents in two phases.  The first
306  * phase compresses a range of pages that have already been
307  * locked (both pages and state bits are locked).
308  *
309  * This is done inside an ordered work queue, and the compression
310  * is spread across many cpus.  The actual IO submission is step
311  * two, and the ordered work queue takes care of making sure that
312  * happens in the same order things were put onto the queue by
313  * writepages and friends.
314  *
315  * If this code finds it can't get good compression, it puts an
316  * entry onto the work queue to write the uncompressed bytes.  This
317  * makes sure that both compressed inodes and uncompressed inodes
318  * are written in the same order that pdflush sent them down.
319  */
320 static noinline int compress_file_range(struct inode *inode,
321                                         struct page *locked_page,
322                                         u64 start, u64 end,
323                                         struct async_cow *async_cow,
324                                         int *num_added)
325 {
326         struct btrfs_root *root = BTRFS_I(inode)->root;
327         struct btrfs_trans_handle *trans;
328         u64 num_bytes;
329         u64 blocksize = root->sectorsize;
330         u64 actual_end;
331         u64 isize = i_size_read(inode);
332         int ret = 0;
333         struct page **pages = NULL;
334         unsigned long nr_pages;
335         unsigned long nr_pages_ret = 0;
336         unsigned long total_compressed = 0;
337         unsigned long total_in = 0;
338         unsigned long max_compressed = 128 * 1024;
339         unsigned long max_uncompressed = 128 * 1024;
340         int i;
341         int will_compress;
342         int compress_type = root->fs_info->compress_type;
343
344         /* if this is a small write inside eof, kick off a defragbot */
345         if (end <= BTRFS_I(inode)->disk_i_size && (end - start + 1) < 16 * 1024)
346                 btrfs_add_inode_defrag(NULL, inode);
347
348         actual_end = min_t(u64, isize, end + 1);
349 again:
350         will_compress = 0;
351         nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
352         nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
353
354         /*
355          * we don't want to send crud past the end of i_size through
356          * compression, that's just a waste of CPU time.  So, if the
357          * end of the file is before the start of our current
358          * requested range of bytes, we bail out to the uncompressed
359          * cleanup code that can deal with all of this.
360          *
361          * It isn't really the fastest way to fix things, but this is a
362          * very uncommon corner.
363          */
364         if (actual_end <= start)
365                 goto cleanup_and_bail_uncompressed;
366
367         total_compressed = actual_end - start;
368
369         /* we want to make sure that amount of ram required to uncompress
370          * an extent is reasonable, so we limit the total size in ram
371          * of a compressed extent to 128k.  This is a crucial number
372          * because it also controls how easily we can spread reads across
373          * cpus for decompression.
374          *
375          * We also want to make sure the amount of IO required to do
376          * a random read is reasonably small, so we limit the size of
377          * a compressed extent to 128k.
378          */
379         total_compressed = min(total_compressed, max_uncompressed);
380         num_bytes = (end - start + blocksize) & ~(blocksize - 1);
381         num_bytes = max(blocksize,  num_bytes);
382         total_in = 0;
383         ret = 0;
384
385         /*
386          * we do compression for mount -o compress and when the
387          * inode has not been flagged as nocompress.  This flag can
388          * change at any time if we discover bad compression ratios.
389          */
390         if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
391             (btrfs_test_opt(root, COMPRESS) ||
392              (BTRFS_I(inode)->force_compress) ||
393              (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
394                 WARN_ON(pages);
395                 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
396                 BUG_ON(!pages);
397
398                 if (BTRFS_I(inode)->force_compress)
399                         compress_type = BTRFS_I(inode)->force_compress;
400
401                 ret = btrfs_compress_pages(compress_type,
402                                            inode->i_mapping, start,
403                                            total_compressed, pages,
404                                            nr_pages, &nr_pages_ret,
405                                            &total_in,
406                                            &total_compressed,
407                                            max_compressed);
408
409                 if (!ret) {
410                         unsigned long offset = total_compressed &
411                                 (PAGE_CACHE_SIZE - 1);
412                         struct page *page = pages[nr_pages_ret - 1];
413                         char *kaddr;
414
415                         /* zero the tail end of the last page, we might be
416                          * sending it down to disk
417                          */
418                         if (offset) {
419                                 kaddr = kmap_atomic(page, KM_USER0);
420                                 memset(kaddr + offset, 0,
421                                        PAGE_CACHE_SIZE - offset);
422                                 kunmap_atomic(kaddr, KM_USER0);
423                         }
424                         will_compress = 1;
425                 }
426         }
427         if (start == 0) {
428                 trans = btrfs_join_transaction(root);
429                 BUG_ON(IS_ERR(trans));
430                 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
431
432                 /* lets try to make an inline extent */
433                 if (ret || total_in < (actual_end - start)) {
434                         /* we didn't compress the entire range, try
435                          * to make an uncompressed inline extent.
436                          */
437                         ret = cow_file_range_inline(trans, root, inode,
438                                                     start, end, 0, 0, NULL);
439                 } else {
440                         /* try making a compressed inline extent */
441                         ret = cow_file_range_inline(trans, root, inode,
442                                                     start, end,
443                                                     total_compressed,
444                                                     compress_type, pages);
445                 }
446                 if (ret == 0) {
447                         /*
448                          * inline extent creation worked, we don't need
449                          * to create any more async work items.  Unlock
450                          * and free up our temp pages.
451                          */
452                         extent_clear_unlock_delalloc(inode,
453                              &BTRFS_I(inode)->io_tree,
454                              start, end, NULL,
455                              EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
456                              EXTENT_CLEAR_DELALLOC |
457                              EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK);
458
459                         btrfs_end_transaction(trans, root);
460                         goto free_pages_out;
461                 }
462                 btrfs_end_transaction(trans, root);
463         }
464
465         if (will_compress) {
466                 /*
467                  * we aren't doing an inline extent round the compressed size
468                  * up to a block size boundary so the allocator does sane
469                  * things
470                  */
471                 total_compressed = (total_compressed + blocksize - 1) &
472                         ~(blocksize - 1);
473
474                 /*
475                  * one last check to make sure the compression is really a
476                  * win, compare the page count read with the blocks on disk
477                  */
478                 total_in = (total_in + PAGE_CACHE_SIZE - 1) &
479                         ~(PAGE_CACHE_SIZE - 1);
480                 if (total_compressed >= total_in) {
481                         will_compress = 0;
482                 } else {
483                         num_bytes = total_in;
484                 }
485         }
486         if (!will_compress && pages) {
487                 /*
488                  * the compression code ran but failed to make things smaller,
489                  * free any pages it allocated and our page pointer array
490                  */
491                 for (i = 0; i < nr_pages_ret; i++) {
492                         WARN_ON(pages[i]->mapping);
493                         page_cache_release(pages[i]);
494                 }
495                 kfree(pages);
496                 pages = NULL;
497                 total_compressed = 0;
498                 nr_pages_ret = 0;
499
500                 /* flag the file so we don't compress in the future */
501                 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
502                     !(BTRFS_I(inode)->force_compress)) {
503                         BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
504                 }
505         }
506         if (will_compress) {
507                 *num_added += 1;
508
509                 /* the async work queues will take care of doing actual
510                  * allocation on disk for these compressed pages,
511                  * and will submit them to the elevator.
512                  */
513                 add_async_extent(async_cow, start, num_bytes,
514                                  total_compressed, pages, nr_pages_ret,
515                                  compress_type);
516
517                 if (start + num_bytes < end) {
518                         start += num_bytes;
519                         pages = NULL;
520                         cond_resched();
521                         goto again;
522                 }
523         } else {
524 cleanup_and_bail_uncompressed:
525                 /*
526                  * No compression, but we still need to write the pages in
527                  * the file we've been given so far.  redirty the locked
528                  * page if it corresponds to our extent and set things up
529                  * for the async work queue to run cow_file_range to do
530                  * the normal delalloc dance
531                  */
532                 if (page_offset(locked_page) >= start &&
533                     page_offset(locked_page) <= end) {
534                         __set_page_dirty_nobuffers(locked_page);
535                         /* unlocked later on in the async handlers */
536                 }
537                 add_async_extent(async_cow, start, end - start + 1,
538                                  0, NULL, 0, BTRFS_COMPRESS_NONE);
539                 *num_added += 1;
540         }
541
542 out:
543         return 0;
544
545 free_pages_out:
546         for (i = 0; i < nr_pages_ret; i++) {
547                 WARN_ON(pages[i]->mapping);
548                 page_cache_release(pages[i]);
549         }
550         kfree(pages);
551
552         goto out;
553 }
554
555 /*
556  * phase two of compressed writeback.  This is the ordered portion
557  * of the code, which only gets called in the order the work was
558  * queued.  We walk all the async extents created by compress_file_range
559  * and send them down to the disk.
560  */
561 static noinline int submit_compressed_extents(struct inode *inode,
562                                               struct async_cow *async_cow)
563 {
564         struct async_extent *async_extent;
565         u64 alloc_hint = 0;
566         struct btrfs_trans_handle *trans;
567         struct btrfs_key ins;
568         struct extent_map *em;
569         struct btrfs_root *root = BTRFS_I(inode)->root;
570         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
571         struct extent_io_tree *io_tree;
572         int ret = 0;
573
574         if (list_empty(&async_cow->extents))
575                 return 0;
576
577
578         while (!list_empty(&async_cow->extents)) {
579                 async_extent = list_entry(async_cow->extents.next,
580                                           struct async_extent, list);
581                 list_del(&async_extent->list);
582
583                 io_tree = &BTRFS_I(inode)->io_tree;
584
585 retry:
586                 /* did the compression code fall back to uncompressed IO? */
587                 if (!async_extent->pages) {
588                         int page_started = 0;
589                         unsigned long nr_written = 0;
590
591                         lock_extent(io_tree, async_extent->start,
592                                          async_extent->start +
593                                          async_extent->ram_size - 1, GFP_NOFS);
594
595                         /* allocate blocks */
596                         ret = cow_file_range(inode, async_cow->locked_page,
597                                              async_extent->start,
598                                              async_extent->start +
599                                              async_extent->ram_size - 1,
600                                              &page_started, &nr_written, 0);
601
602                         /*
603                          * if page_started, cow_file_range inserted an
604                          * inline extent and took care of all the unlocking
605                          * and IO for us.  Otherwise, we need to submit
606                          * all those pages down to the drive.
607                          */
608                         if (!page_started && !ret)
609                                 extent_write_locked_range(io_tree,
610                                                   inode, async_extent->start,
611                                                   async_extent->start +
612                                                   async_extent->ram_size - 1,
613                                                   btrfs_get_extent,
614                                                   WB_SYNC_ALL);
615                         kfree(async_extent);
616                         cond_resched();
617                         continue;
618                 }
619
620                 lock_extent(io_tree, async_extent->start,
621                             async_extent->start + async_extent->ram_size - 1,
622                             GFP_NOFS);
623
624                 trans = btrfs_join_transaction(root);
625                 BUG_ON(IS_ERR(trans));
626                 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
627                 ret = btrfs_reserve_extent(trans, root,
628                                            async_extent->compressed_size,
629                                            async_extent->compressed_size,
630                                            0, alloc_hint,
631                                            (u64)-1, &ins, 1);
632                 btrfs_end_transaction(trans, root);
633
634                 if (ret) {
635                         int i;
636                         for (i = 0; i < async_extent->nr_pages; i++) {
637                                 WARN_ON(async_extent->pages[i]->mapping);
638                                 page_cache_release(async_extent->pages[i]);
639                         }
640                         kfree(async_extent->pages);
641                         async_extent->nr_pages = 0;
642                         async_extent->pages = NULL;
643                         unlock_extent(io_tree, async_extent->start,
644                                       async_extent->start +
645                                       async_extent->ram_size - 1, GFP_NOFS);
646                         goto retry;
647                 }
648
649                 /*
650                  * here we're doing allocation and writeback of the
651                  * compressed pages
652                  */
653                 btrfs_drop_extent_cache(inode, async_extent->start,
654                                         async_extent->start +
655                                         async_extent->ram_size - 1, 0);
656
657                 em = alloc_extent_map();
658                 BUG_ON(!em);
659                 em->start = async_extent->start;
660                 em->len = async_extent->ram_size;
661                 em->orig_start = em->start;
662
663                 em->block_start = ins.objectid;
664                 em->block_len = ins.offset;
665                 em->bdev = root->fs_info->fs_devices->latest_bdev;
666                 em->compress_type = async_extent->compress_type;
667                 set_bit(EXTENT_FLAG_PINNED, &em->flags);
668                 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
669
670                 while (1) {
671                         write_lock(&em_tree->lock);
672                         ret = add_extent_mapping(em_tree, em);
673                         write_unlock(&em_tree->lock);
674                         if (ret != -EEXIST) {
675                                 free_extent_map(em);
676                                 break;
677                         }
678                         btrfs_drop_extent_cache(inode, async_extent->start,
679                                                 async_extent->start +
680                                                 async_extent->ram_size - 1, 0);
681                 }
682
683                 ret = btrfs_add_ordered_extent_compress(inode,
684                                                 async_extent->start,
685                                                 ins.objectid,
686                                                 async_extent->ram_size,
687                                                 ins.offset,
688                                                 BTRFS_ORDERED_COMPRESSED,
689                                                 async_extent->compress_type);
690                 BUG_ON(ret);
691
692                 /*
693                  * clear dirty, set writeback and unlock the pages.
694                  */
695                 extent_clear_unlock_delalloc(inode,
696                                 &BTRFS_I(inode)->io_tree,
697                                 async_extent->start,
698                                 async_extent->start +
699                                 async_extent->ram_size - 1,
700                                 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
701                                 EXTENT_CLEAR_UNLOCK |
702                                 EXTENT_CLEAR_DELALLOC |
703                                 EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
704
705                 ret = btrfs_submit_compressed_write(inode,
706                                     async_extent->start,
707                                     async_extent->ram_size,
708                                     ins.objectid,
709                                     ins.offset, async_extent->pages,
710                                     async_extent->nr_pages);
711
712                 BUG_ON(ret);
713                 alloc_hint = ins.objectid + ins.offset;
714                 kfree(async_extent);
715                 cond_resched();
716         }
717
718         return 0;
719 }
720
721 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
722                                       u64 num_bytes)
723 {
724         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
725         struct extent_map *em;
726         u64 alloc_hint = 0;
727
728         read_lock(&em_tree->lock);
729         em = search_extent_mapping(em_tree, start, num_bytes);
730         if (em) {
731                 /*
732                  * if block start isn't an actual block number then find the
733                  * first block in this inode and use that as a hint.  If that
734                  * block is also bogus then just don't worry about it.
735                  */
736                 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
737                         free_extent_map(em);
738                         em = search_extent_mapping(em_tree, 0, 0);
739                         if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
740                                 alloc_hint = em->block_start;
741                         if (em)
742                                 free_extent_map(em);
743                 } else {
744                         alloc_hint = em->block_start;
745                         free_extent_map(em);
746                 }
747         }
748         read_unlock(&em_tree->lock);
749
750         return alloc_hint;
751 }
752
753 /*
754  * when extent_io.c finds a delayed allocation range in the file,
755  * the call backs end up in this code.  The basic idea is to
756  * allocate extents on disk for the range, and create ordered data structs
757  * in ram to track those extents.
758  *
759  * locked_page is the page that writepage had locked already.  We use
760  * it to make sure we don't do extra locks or unlocks.
761  *
762  * *page_started is set to one if we unlock locked_page and do everything
763  * required to start IO on it.  It may be clean and already done with
764  * IO when we return.
765  */
766 static noinline int cow_file_range(struct inode *inode,
767                                    struct page *locked_page,
768                                    u64 start, u64 end, int *page_started,
769                                    unsigned long *nr_written,
770                                    int unlock)
771 {
772         struct btrfs_root *root = BTRFS_I(inode)->root;
773         struct btrfs_trans_handle *trans;
774         u64 alloc_hint = 0;
775         u64 num_bytes;
776         unsigned long ram_size;
777         u64 disk_num_bytes;
778         u64 cur_alloc_size;
779         u64 blocksize = root->sectorsize;
780         struct btrfs_key ins;
781         struct extent_map *em;
782         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
783         int ret = 0;
784
785         BUG_ON(btrfs_is_free_space_inode(root, inode));
786         trans = btrfs_join_transaction(root);
787         BUG_ON(IS_ERR(trans));
788         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
789
790         num_bytes = (end - start + blocksize) & ~(blocksize - 1);
791         num_bytes = max(blocksize,  num_bytes);
792         disk_num_bytes = num_bytes;
793         ret = 0;
794
795         /* if this is a small write inside eof, kick off defrag */
796         if (end <= BTRFS_I(inode)->disk_i_size && num_bytes < 64 * 1024)
797                 btrfs_add_inode_defrag(trans, inode);
798
799         if (start == 0) {
800                 /* lets try to make an inline extent */
801                 ret = cow_file_range_inline(trans, root, inode,
802                                             start, end, 0, 0, NULL);
803                 if (ret == 0) {
804                         extent_clear_unlock_delalloc(inode,
805                                      &BTRFS_I(inode)->io_tree,
806                                      start, end, NULL,
807                                      EXTENT_CLEAR_UNLOCK_PAGE |
808                                      EXTENT_CLEAR_UNLOCK |
809                                      EXTENT_CLEAR_DELALLOC |
810                                      EXTENT_CLEAR_DIRTY |
811                                      EXTENT_SET_WRITEBACK |
812                                      EXTENT_END_WRITEBACK);
813
814                         *nr_written = *nr_written +
815                              (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
816                         *page_started = 1;
817                         ret = 0;
818                         goto out;
819                 }
820         }
821
822         BUG_ON(disk_num_bytes >
823                btrfs_super_total_bytes(&root->fs_info->super_copy));
824
825         alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
826         btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
827
828         while (disk_num_bytes > 0) {
829                 unsigned long op;
830
831                 cur_alloc_size = disk_num_bytes;
832                 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
833                                            root->sectorsize, 0, alloc_hint,
834                                            (u64)-1, &ins, 1);
835                 BUG_ON(ret);
836
837                 em = alloc_extent_map();
838                 BUG_ON(!em);
839                 em->start = start;
840                 em->orig_start = em->start;
841                 ram_size = ins.offset;
842                 em->len = ins.offset;
843
844                 em->block_start = ins.objectid;
845                 em->block_len = ins.offset;
846                 em->bdev = root->fs_info->fs_devices->latest_bdev;
847                 set_bit(EXTENT_FLAG_PINNED, &em->flags);
848
849                 while (1) {
850                         write_lock(&em_tree->lock);
851                         ret = add_extent_mapping(em_tree, em);
852                         write_unlock(&em_tree->lock);
853                         if (ret != -EEXIST) {
854                                 free_extent_map(em);
855                                 break;
856                         }
857                         btrfs_drop_extent_cache(inode, start,
858                                                 start + ram_size - 1, 0);
859                 }
860
861                 cur_alloc_size = ins.offset;
862                 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
863                                                ram_size, cur_alloc_size, 0);
864                 BUG_ON(ret);
865
866                 if (root->root_key.objectid ==
867                     BTRFS_DATA_RELOC_TREE_OBJECTID) {
868                         ret = btrfs_reloc_clone_csums(inode, start,
869                                                       cur_alloc_size);
870                         BUG_ON(ret);
871                 }
872
873                 if (disk_num_bytes < cur_alloc_size)
874                         break;
875
876                 /* we're not doing compressed IO, don't unlock the first
877                  * page (which the caller expects to stay locked), don't
878                  * clear any dirty bits and don't set any writeback bits
879                  *
880                  * Do set the Private2 bit so we know this page was properly
881                  * setup for writepage
882                  */
883                 op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0;
884                 op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
885                         EXTENT_SET_PRIVATE2;
886
887                 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
888                                              start, start + ram_size - 1,
889                                              locked_page, op);
890                 disk_num_bytes -= cur_alloc_size;
891                 num_bytes -= cur_alloc_size;
892                 alloc_hint = ins.objectid + ins.offset;
893                 start += cur_alloc_size;
894         }
895 out:
896         ret = 0;
897         btrfs_end_transaction(trans, root);
898
899         return ret;
900 }
901
902 /*
903  * work queue call back to started compression on a file and pages
904  */
905 static noinline void async_cow_start(struct btrfs_work *work)
906 {
907         struct async_cow *async_cow;
908         int num_added = 0;
909         async_cow = container_of(work, struct async_cow, work);
910
911         compress_file_range(async_cow->inode, async_cow->locked_page,
912                             async_cow->start, async_cow->end, async_cow,
913                             &num_added);
914         if (num_added == 0)
915                 async_cow->inode = NULL;
916 }
917
918 /*
919  * work queue call back to submit previously compressed pages
920  */
921 static noinline void async_cow_submit(struct btrfs_work *work)
922 {
923         struct async_cow *async_cow;
924         struct btrfs_root *root;
925         unsigned long nr_pages;
926
927         async_cow = container_of(work, struct async_cow, work);
928
929         root = async_cow->root;
930         nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
931                 PAGE_CACHE_SHIFT;
932
933         atomic_sub(nr_pages, &root->fs_info->async_delalloc_pages);
934
935         if (atomic_read(&root->fs_info->async_delalloc_pages) <
936             5 * 1042 * 1024 &&
937             waitqueue_active(&root->fs_info->async_submit_wait))
938                 wake_up(&root->fs_info->async_submit_wait);
939
940         if (async_cow->inode)
941                 submit_compressed_extents(async_cow->inode, async_cow);
942 }
943
944 static noinline void async_cow_free(struct btrfs_work *work)
945 {
946         struct async_cow *async_cow;
947         async_cow = container_of(work, struct async_cow, work);
948         kfree(async_cow);
949 }
950
951 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
952                                 u64 start, u64 end, int *page_started,
953                                 unsigned long *nr_written)
954 {
955         struct async_cow *async_cow;
956         struct btrfs_root *root = BTRFS_I(inode)->root;
957         unsigned long nr_pages;
958         u64 cur_end;
959         int limit = 10 * 1024 * 1042;
960
961         clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
962                          1, 0, NULL, GFP_NOFS);
963         while (start < end) {
964                 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
965                 BUG_ON(!async_cow);
966                 async_cow->inode = inode;
967                 async_cow->root = root;
968                 async_cow->locked_page = locked_page;
969                 async_cow->start = start;
970
971                 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
972                         cur_end = end;
973                 else
974                         cur_end = min(end, start + 512 * 1024 - 1);
975
976                 async_cow->end = cur_end;
977                 INIT_LIST_HEAD(&async_cow->extents);
978
979                 async_cow->work.func = async_cow_start;
980                 async_cow->work.ordered_func = async_cow_submit;
981                 async_cow->work.ordered_free = async_cow_free;
982                 async_cow->work.flags = 0;
983
984                 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
985                         PAGE_CACHE_SHIFT;
986                 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
987
988                 btrfs_queue_worker(&root->fs_info->delalloc_workers,
989                                    &async_cow->work);
990
991                 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
992                         wait_event(root->fs_info->async_submit_wait,
993                            (atomic_read(&root->fs_info->async_delalloc_pages) <
994                             limit));
995                 }
996
997                 while (atomic_read(&root->fs_info->async_submit_draining) &&
998                       atomic_read(&root->fs_info->async_delalloc_pages)) {
999                         wait_event(root->fs_info->async_submit_wait,
1000                           (atomic_read(&root->fs_info->async_delalloc_pages) ==
1001                            0));
1002                 }
1003
1004                 *nr_written += nr_pages;
1005                 start = cur_end + 1;
1006         }
1007         *page_started = 1;
1008         return 0;
1009 }
1010
1011 static noinline int csum_exist_in_range(struct btrfs_root *root,
1012                                         u64 bytenr, u64 num_bytes)
1013 {
1014         int ret;
1015         struct btrfs_ordered_sum *sums;
1016         LIST_HEAD(list);
1017
1018         ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1019                                        bytenr + num_bytes - 1, &list, 0);
1020         if (ret == 0 && list_empty(&list))
1021                 return 0;
1022
1023         while (!list_empty(&list)) {
1024                 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1025                 list_del(&sums->list);
1026                 kfree(sums);
1027         }
1028         return 1;
1029 }
1030
1031 /*
1032  * when nowcow writeback call back.  This checks for snapshots or COW copies
1033  * of the extents that exist in the file, and COWs the file as required.
1034  *
1035  * If no cow copies or snapshots exist, we write directly to the existing
1036  * blocks on disk
1037  */
1038 static noinline int run_delalloc_nocow(struct inode *inode,
1039                                        struct page *locked_page,
1040                               u64 start, u64 end, int *page_started, int force,
1041                               unsigned long *nr_written)
1042 {
1043         struct btrfs_root *root = BTRFS_I(inode)->root;
1044         struct btrfs_trans_handle *trans;
1045         struct extent_buffer *leaf;
1046         struct btrfs_path *path;
1047         struct btrfs_file_extent_item *fi;
1048         struct btrfs_key found_key;
1049         u64 cow_start;
1050         u64 cur_offset;
1051         u64 extent_end;
1052         u64 extent_offset;
1053         u64 disk_bytenr;
1054         u64 num_bytes;
1055         int extent_type;
1056         int ret;
1057         int type;
1058         int nocow;
1059         int check_prev = 1;
1060         bool nolock;
1061         u64 ino = btrfs_ino(inode);
1062
1063         path = btrfs_alloc_path();
1064         BUG_ON(!path);
1065
1066         nolock = btrfs_is_free_space_inode(root, inode);
1067
1068         if (nolock)
1069                 trans = btrfs_join_transaction_nolock(root);
1070         else
1071                 trans = btrfs_join_transaction(root);
1072
1073         BUG_ON(IS_ERR(trans));
1074         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1075
1076         cow_start = (u64)-1;
1077         cur_offset = start;
1078         while (1) {
1079                 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1080                                                cur_offset, 0);
1081                 BUG_ON(ret < 0);
1082                 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1083                         leaf = path->nodes[0];
1084                         btrfs_item_key_to_cpu(leaf, &found_key,
1085                                               path->slots[0] - 1);
1086                         if (found_key.objectid == ino &&
1087                             found_key.type == BTRFS_EXTENT_DATA_KEY)
1088                                 path->slots[0]--;
1089                 }
1090                 check_prev = 0;
1091 next_slot:
1092                 leaf = path->nodes[0];
1093                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1094                         ret = btrfs_next_leaf(root, path);
1095                         if (ret < 0)
1096                                 BUG_ON(1);
1097                         if (ret > 0)
1098                                 break;
1099                         leaf = path->nodes[0];
1100                 }
1101
1102                 nocow = 0;
1103                 disk_bytenr = 0;
1104                 num_bytes = 0;
1105                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1106
1107                 if (found_key.objectid > ino ||
1108                     found_key.type > BTRFS_EXTENT_DATA_KEY ||
1109                     found_key.offset > end)
1110                         break;
1111
1112                 if (found_key.offset > cur_offset) {
1113                         extent_end = found_key.offset;
1114                         extent_type = 0;
1115                         goto out_check;
1116                 }
1117
1118                 fi = btrfs_item_ptr(leaf, path->slots[0],
1119                                     struct btrfs_file_extent_item);
1120                 extent_type = btrfs_file_extent_type(leaf, fi);
1121
1122                 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1123                     extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1124                         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1125                         extent_offset = btrfs_file_extent_offset(leaf, fi);
1126                         extent_end = found_key.offset +
1127                                 btrfs_file_extent_num_bytes(leaf, fi);
1128                         if (extent_end <= start) {
1129                                 path->slots[0]++;
1130                                 goto next_slot;
1131                         }
1132                         if (disk_bytenr == 0)
1133                                 goto out_check;
1134                         if (btrfs_file_extent_compression(leaf, fi) ||
1135                             btrfs_file_extent_encryption(leaf, fi) ||
1136                             btrfs_file_extent_other_encoding(leaf, fi))
1137                                 goto out_check;
1138                         if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1139                                 goto out_check;
1140                         if (btrfs_extent_readonly(root, disk_bytenr))
1141                                 goto out_check;
1142                         if (btrfs_cross_ref_exist(trans, root, ino,
1143                                                   found_key.offset -
1144                                                   extent_offset, disk_bytenr))
1145                                 goto out_check;
1146                         disk_bytenr += extent_offset;
1147                         disk_bytenr += cur_offset - found_key.offset;
1148                         num_bytes = min(end + 1, extent_end) - cur_offset;
1149                         /*
1150                          * force cow if csum exists in the range.
1151                          * this ensure that csum for a given extent are
1152                          * either valid or do not exist.
1153                          */
1154                         if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1155                                 goto out_check;
1156                         nocow = 1;
1157                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1158                         extent_end = found_key.offset +
1159                                 btrfs_file_extent_inline_len(leaf, fi);
1160                         extent_end = ALIGN(extent_end, root->sectorsize);
1161                 } else {
1162                         BUG_ON(1);
1163                 }
1164 out_check:
1165                 if (extent_end <= start) {
1166                         path->slots[0]++;
1167                         goto next_slot;
1168                 }
1169                 if (!nocow) {
1170                         if (cow_start == (u64)-1)
1171                                 cow_start = cur_offset;
1172                         cur_offset = extent_end;
1173                         if (cur_offset > end)
1174                                 break;
1175                         path->slots[0]++;
1176                         goto next_slot;
1177                 }
1178
1179                 btrfs_release_path(path);
1180                 if (cow_start != (u64)-1) {
1181                         ret = cow_file_range(inode, locked_page, cow_start,
1182                                         found_key.offset - 1, page_started,
1183                                         nr_written, 1);
1184                         BUG_ON(ret);
1185                         cow_start = (u64)-1;
1186                 }
1187
1188                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1189                         struct extent_map *em;
1190                         struct extent_map_tree *em_tree;
1191                         em_tree = &BTRFS_I(inode)->extent_tree;
1192                         em = alloc_extent_map();
1193                         BUG_ON(!em);
1194                         em->start = cur_offset;
1195                         em->orig_start = em->start;
1196                         em->len = num_bytes;
1197                         em->block_len = num_bytes;
1198                         em->block_start = disk_bytenr;
1199                         em->bdev = root->fs_info->fs_devices->latest_bdev;
1200                         set_bit(EXTENT_FLAG_PINNED, &em->flags);
1201                         while (1) {
1202                                 write_lock(&em_tree->lock);
1203                                 ret = add_extent_mapping(em_tree, em);
1204                                 write_unlock(&em_tree->lock);
1205                                 if (ret != -EEXIST) {
1206                                         free_extent_map(em);
1207                                         break;
1208                                 }
1209                                 btrfs_drop_extent_cache(inode, em->start,
1210                                                 em->start + em->len - 1, 0);
1211                         }
1212                         type = BTRFS_ORDERED_PREALLOC;
1213                 } else {
1214                         type = BTRFS_ORDERED_NOCOW;
1215                 }
1216
1217                 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1218                                                num_bytes, num_bytes, type);
1219                 BUG_ON(ret);
1220
1221                 if (root->root_key.objectid ==
1222                     BTRFS_DATA_RELOC_TREE_OBJECTID) {
1223                         ret = btrfs_reloc_clone_csums(inode, cur_offset,
1224                                                       num_bytes);
1225                         BUG_ON(ret);
1226                 }
1227
1228                 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
1229                                 cur_offset, cur_offset + num_bytes - 1,
1230                                 locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
1231                                 EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
1232                                 EXTENT_SET_PRIVATE2);
1233                 cur_offset = extent_end;
1234                 if (cur_offset > end)
1235                         break;
1236         }
1237         btrfs_release_path(path);
1238
1239         if (cur_offset <= end && cow_start == (u64)-1)
1240                 cow_start = cur_offset;
1241         if (cow_start != (u64)-1) {
1242                 ret = cow_file_range(inode, locked_page, cow_start, end,
1243                                      page_started, nr_written, 1);
1244                 BUG_ON(ret);
1245         }
1246
1247         if (nolock) {
1248                 ret = btrfs_end_transaction_nolock(trans, root);
1249                 BUG_ON(ret);
1250         } else {
1251                 ret = btrfs_end_transaction(trans, root);
1252                 BUG_ON(ret);
1253         }
1254         btrfs_free_path(path);
1255         return 0;
1256 }
1257
1258 /*
1259  * extent_io.c call back to do delayed allocation processing
1260  */
1261 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1262                               u64 start, u64 end, int *page_started,
1263                               unsigned long *nr_written)
1264 {
1265         int ret;
1266         struct btrfs_root *root = BTRFS_I(inode)->root;
1267
1268         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)
1269                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1270                                          page_started, 1, nr_written);
1271         else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC)
1272                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1273                                          page_started, 0, nr_written);
1274         else if (!btrfs_test_opt(root, COMPRESS) &&
1275                  !(BTRFS_I(inode)->force_compress) &&
1276                  !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))
1277                 ret = cow_file_range(inode, locked_page, start, end,
1278                                       page_started, nr_written, 1);
1279         else
1280                 ret = cow_file_range_async(inode, locked_page, start, end,
1281                                            page_started, nr_written);
1282         return ret;
1283 }
1284
1285 static int btrfs_split_extent_hook(struct inode *inode,
1286                                    struct extent_state *orig, u64 split)
1287 {
1288         /* not delalloc, ignore it */
1289         if (!(orig->state & EXTENT_DELALLOC))
1290                 return 0;
1291
1292         spin_lock(&BTRFS_I(inode)->lock);
1293         BTRFS_I(inode)->outstanding_extents++;
1294         spin_unlock(&BTRFS_I(inode)->lock);
1295         return 0;
1296 }
1297
1298 /*
1299  * extent_io.c merge_extent_hook, used to track merged delayed allocation
1300  * extents so we can keep track of new extents that are just merged onto old
1301  * extents, such as when we are doing sequential writes, so we can properly
1302  * account for the metadata space we'll need.
1303  */
1304 static int btrfs_merge_extent_hook(struct inode *inode,
1305                                    struct extent_state *new,
1306                                    struct extent_state *other)
1307 {
1308         /* not delalloc, ignore it */
1309         if (!(other->state & EXTENT_DELALLOC))
1310                 return 0;
1311
1312         spin_lock(&BTRFS_I(inode)->lock);
1313         BTRFS_I(inode)->outstanding_extents--;
1314         spin_unlock(&BTRFS_I(inode)->lock);
1315         return 0;
1316 }
1317
1318 /*
1319  * extent_io.c set_bit_hook, used to track delayed allocation
1320  * bytes in this file, and to maintain the list of inodes that
1321  * have pending delalloc work to be done.
1322  */
1323 static int btrfs_set_bit_hook(struct inode *inode,
1324                               struct extent_state *state, int *bits)
1325 {
1326
1327         /*
1328          * set_bit and clear bit hooks normally require _irqsave/restore
1329          * but in this case, we are only testing for the DELALLOC
1330          * bit, which is only set or cleared with irqs on
1331          */
1332         if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1333                 struct btrfs_root *root = BTRFS_I(inode)->root;
1334                 u64 len = state->end + 1 - state->start;
1335                 bool do_list = !btrfs_is_free_space_inode(root, inode);
1336
1337                 if (*bits & EXTENT_FIRST_DELALLOC) {
1338                         *bits &= ~EXTENT_FIRST_DELALLOC;
1339                 } else {
1340                         spin_lock(&BTRFS_I(inode)->lock);
1341                         BTRFS_I(inode)->outstanding_extents++;
1342                         spin_unlock(&BTRFS_I(inode)->lock);
1343                 }
1344
1345                 spin_lock(&root->fs_info->delalloc_lock);
1346                 BTRFS_I(inode)->delalloc_bytes += len;
1347                 root->fs_info->delalloc_bytes += len;
1348                 if (do_list && list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1349                         list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1350                                       &root->fs_info->delalloc_inodes);
1351                 }
1352                 spin_unlock(&root->fs_info->delalloc_lock);
1353         }
1354         return 0;
1355 }
1356
1357 /*
1358  * extent_io.c clear_bit_hook, see set_bit_hook for why
1359  */
1360 static int btrfs_clear_bit_hook(struct inode *inode,
1361                                 struct extent_state *state, int *bits)
1362 {
1363         /*
1364          * set_bit and clear bit hooks normally require _irqsave/restore
1365          * but in this case, we are only testing for the DELALLOC
1366          * bit, which is only set or cleared with irqs on
1367          */
1368         if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1369                 struct btrfs_root *root = BTRFS_I(inode)->root;
1370                 u64 len = state->end + 1 - state->start;
1371                 bool do_list = !btrfs_is_free_space_inode(root, inode);
1372
1373                 if (*bits & EXTENT_FIRST_DELALLOC) {
1374                         *bits &= ~EXTENT_FIRST_DELALLOC;
1375                 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1376                         spin_lock(&BTRFS_I(inode)->lock);
1377                         BTRFS_I(inode)->outstanding_extents--;
1378                         spin_unlock(&BTRFS_I(inode)->lock);
1379                 }
1380
1381                 if (*bits & EXTENT_DO_ACCOUNTING)
1382                         btrfs_delalloc_release_metadata(inode, len);
1383
1384                 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1385                     && do_list)
1386                         btrfs_free_reserved_data_space(inode, len);
1387
1388                 spin_lock(&root->fs_info->delalloc_lock);
1389                 root->fs_info->delalloc_bytes -= len;
1390                 BTRFS_I(inode)->delalloc_bytes -= len;
1391
1392                 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1393                     !list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1394                         list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1395                 }
1396                 spin_unlock(&root->fs_info->delalloc_lock);
1397         }
1398         return 0;
1399 }
1400
1401 /*
1402  * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1403  * we don't create bios that span stripes or chunks
1404  */
1405 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1406                          size_t size, struct bio *bio,
1407                          unsigned long bio_flags)
1408 {
1409         struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1410         struct btrfs_mapping_tree *map_tree;
1411         u64 logical = (u64)bio->bi_sector << 9;
1412         u64 length = 0;
1413         u64 map_length;
1414         int ret;
1415
1416         if (bio_flags & EXTENT_BIO_COMPRESSED)
1417                 return 0;
1418
1419         length = bio->bi_size;
1420         map_tree = &root->fs_info->mapping_tree;
1421         map_length = length;
1422         ret = btrfs_map_block(map_tree, READ, logical,
1423                               &map_length, NULL, 0);
1424
1425         if (map_length < length + size)
1426                 return 1;
1427         return ret;
1428 }
1429
1430 /*
1431  * in order to insert checksums into the metadata in large chunks,
1432  * we wait until bio submission time.   All the pages in the bio are
1433  * checksummed and sums are attached onto the ordered extent record.
1434  *
1435  * At IO completion time the cums attached on the ordered extent record
1436  * are inserted into the btree
1437  */
1438 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1439                                     struct bio *bio, int mirror_num,
1440                                     unsigned long bio_flags,
1441                                     u64 bio_offset)
1442 {
1443         struct btrfs_root *root = BTRFS_I(inode)->root;
1444         int ret = 0;
1445
1446         ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1447         BUG_ON(ret);
1448         return 0;
1449 }
1450
1451 /*
1452  * in order to insert checksums into the metadata in large chunks,
1453  * we wait until bio submission time.   All the pages in the bio are
1454  * checksummed and sums are attached onto the ordered extent record.
1455  *
1456  * At IO completion time the cums attached on the ordered extent record
1457  * are inserted into the btree
1458  */
1459 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1460                           int mirror_num, unsigned long bio_flags,
1461                           u64 bio_offset)
1462 {
1463         struct btrfs_root *root = BTRFS_I(inode)->root;
1464         return btrfs_map_bio(root, rw, bio, mirror_num, 1);
1465 }
1466
1467 /*
1468  * extent_io.c submission hook. This does the right thing for csum calculation
1469  * on write, or reading the csums from the tree before a read
1470  */
1471 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1472                           int mirror_num, unsigned long bio_flags,
1473                           u64 bio_offset)
1474 {
1475         struct btrfs_root *root = BTRFS_I(inode)->root;
1476         int ret = 0;
1477         int skip_sum;
1478
1479         skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1480
1481         if (btrfs_is_free_space_inode(root, inode))
1482                 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 2);
1483         else
1484                 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
1485         BUG_ON(ret);
1486
1487         if (!(rw & REQ_WRITE)) {
1488                 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1489                         return btrfs_submit_compressed_read(inode, bio,
1490                                                     mirror_num, bio_flags);
1491                 } else if (!skip_sum) {
1492                         ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1493                         if (ret)
1494                                 return ret;
1495                 }
1496                 goto mapit;
1497         } else if (!skip_sum) {
1498                 /* csum items have already been cloned */
1499                 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1500                         goto mapit;
1501                 /* we're doing a write, do the async checksumming */
1502                 return btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1503                                    inode, rw, bio, mirror_num,
1504                                    bio_flags, bio_offset,
1505                                    __btrfs_submit_bio_start,
1506                                    __btrfs_submit_bio_done);
1507         }
1508
1509 mapit:
1510         return btrfs_map_bio(root, rw, bio, mirror_num, 0);
1511 }
1512
1513 /*
1514  * given a list of ordered sums record them in the inode.  This happens
1515  * at IO completion time based on sums calculated at bio submission time.
1516  */
1517 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1518                              struct inode *inode, u64 file_offset,
1519                              struct list_head *list)
1520 {
1521         struct btrfs_ordered_sum *sum;
1522
1523         list_for_each_entry(sum, list, list) {
1524                 btrfs_csum_file_blocks(trans,
1525                        BTRFS_I(inode)->root->fs_info->csum_root, sum);
1526         }
1527         return 0;
1528 }
1529
1530 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1531                               struct extent_state **cached_state)
1532 {
1533         if ((end & (PAGE_CACHE_SIZE - 1)) == 0)
1534                 WARN_ON(1);
1535         return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1536                                    cached_state, GFP_NOFS);
1537 }
1538
1539 /* see btrfs_writepage_start_hook for details on why this is required */
1540 struct btrfs_writepage_fixup {
1541         struct page *page;
1542         struct btrfs_work work;
1543 };
1544
1545 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1546 {
1547         struct btrfs_writepage_fixup *fixup;
1548         struct btrfs_ordered_extent *ordered;
1549         struct extent_state *cached_state = NULL;
1550         struct page *page;
1551         struct inode *inode;
1552         u64 page_start;
1553         u64 page_end;
1554
1555         fixup = container_of(work, struct btrfs_writepage_fixup, work);
1556         page = fixup->page;
1557 again:
1558         lock_page(page);
1559         if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1560                 ClearPageChecked(page);
1561                 goto out_page;
1562         }
1563
1564         inode = page->mapping->host;
1565         page_start = page_offset(page);
1566         page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1567
1568         lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1569                          &cached_state, GFP_NOFS);
1570
1571         /* already ordered? We're done */
1572         if (PagePrivate2(page))
1573                 goto out;
1574
1575         ordered = btrfs_lookup_ordered_extent(inode, page_start);
1576         if (ordered) {
1577                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1578                                      page_end, &cached_state, GFP_NOFS);
1579                 unlock_page(page);
1580                 btrfs_start_ordered_extent(inode, ordered, 1);
1581                 goto again;
1582         }
1583
1584         BUG();
1585         btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1586         ClearPageChecked(page);
1587 out:
1588         unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1589                              &cached_state, GFP_NOFS);
1590 out_page:
1591         unlock_page(page);
1592         page_cache_release(page);
1593         kfree(fixup);
1594 }
1595
1596 /*
1597  * There are a few paths in the higher layers of the kernel that directly
1598  * set the page dirty bit without asking the filesystem if it is a
1599  * good idea.  This causes problems because we want to make sure COW
1600  * properly happens and the data=ordered rules are followed.
1601  *
1602  * In our case any range that doesn't have the ORDERED bit set
1603  * hasn't been properly setup for IO.  We kick off an async process
1604  * to fix it up.  The async helper will wait for ordered extents, set
1605  * the delalloc bit and make it safe to write the page.
1606  */
1607 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1608 {
1609         struct inode *inode = page->mapping->host;
1610         struct btrfs_writepage_fixup *fixup;
1611         struct btrfs_root *root = BTRFS_I(inode)->root;
1612
1613         /* this page is properly in the ordered list */
1614         if (TestClearPagePrivate2(page))
1615                 return 0;
1616
1617         if (PageChecked(page))
1618                 return -EAGAIN;
1619
1620         fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1621         if (!fixup)
1622                 return -EAGAIN;
1623
1624         SetPageChecked(page);
1625         page_cache_get(page);
1626         fixup->work.func = btrfs_writepage_fixup_worker;
1627         fixup->page = page;
1628         btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1629         return -EAGAIN;
1630 }
1631
1632 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1633                                        struct inode *inode, u64 file_pos,
1634                                        u64 disk_bytenr, u64 disk_num_bytes,
1635                                        u64 num_bytes, u64 ram_bytes,
1636                                        u8 compression, u8 encryption,
1637                                        u16 other_encoding, int extent_type)
1638 {
1639         struct btrfs_root *root = BTRFS_I(inode)->root;
1640         struct btrfs_file_extent_item *fi;
1641         struct btrfs_path *path;
1642         struct extent_buffer *leaf;
1643         struct btrfs_key ins;
1644         u64 hint;
1645         int ret;
1646
1647         path = btrfs_alloc_path();
1648         BUG_ON(!path);
1649
1650         path->leave_spinning = 1;
1651
1652         /*
1653          * we may be replacing one extent in the tree with another.
1654          * The new extent is pinned in the extent map, and we don't want
1655          * to drop it from the cache until it is completely in the btree.
1656          *
1657          * So, tell btrfs_drop_extents to leave this extent in the cache.
1658          * the caller is expected to unpin it and allow it to be merged
1659          * with the others.
1660          */
1661         ret = btrfs_drop_extents(trans, inode, file_pos, file_pos + num_bytes,
1662                                  &hint, 0);
1663         BUG_ON(ret);
1664
1665         ins.objectid = btrfs_ino(inode);
1666         ins.offset = file_pos;
1667         ins.type = BTRFS_EXTENT_DATA_KEY;
1668         ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1669         BUG_ON(ret);
1670         leaf = path->nodes[0];
1671         fi = btrfs_item_ptr(leaf, path->slots[0],
1672                             struct btrfs_file_extent_item);
1673         btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1674         btrfs_set_file_extent_type(leaf, fi, extent_type);
1675         btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1676         btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1677         btrfs_set_file_extent_offset(leaf, fi, 0);
1678         btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1679         btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1680         btrfs_set_file_extent_compression(leaf, fi, compression);
1681         btrfs_set_file_extent_encryption(leaf, fi, encryption);
1682         btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1683
1684         btrfs_unlock_up_safe(path, 1);
1685         btrfs_set_lock_blocking(leaf);
1686
1687         btrfs_mark_buffer_dirty(leaf);
1688
1689         inode_add_bytes(inode, num_bytes);
1690
1691         ins.objectid = disk_bytenr;
1692         ins.offset = disk_num_bytes;
1693         ins.type = BTRFS_EXTENT_ITEM_KEY;
1694         ret = btrfs_alloc_reserved_file_extent(trans, root,
1695                                         root->root_key.objectid,
1696                                         btrfs_ino(inode), file_pos, &ins);
1697         BUG_ON(ret);
1698         btrfs_free_path(path);
1699
1700         return 0;
1701 }
1702
1703 /*
1704  * helper function for btrfs_finish_ordered_io, this
1705  * just reads in some of the csum leaves to prime them into ram
1706  * before we start the transaction.  It limits the amount of btree
1707  * reads required while inside the transaction.
1708  */
1709 /* as ordered data IO finishes, this gets called so we can finish
1710  * an ordered extent if the range of bytes in the file it covers are
1711  * fully written.
1712  */
1713 static int btrfs_finish_ordered_io(struct inode *inode, u64 start, u64 end)
1714 {
1715         struct btrfs_root *root = BTRFS_I(inode)->root;
1716         struct btrfs_trans_handle *trans = NULL;
1717         struct btrfs_ordered_extent *ordered_extent = NULL;
1718         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1719         struct extent_state *cached_state = NULL;
1720         int compress_type = 0;
1721         int ret;
1722         bool nolock;
1723
1724         ret = btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
1725                                              end - start + 1);
1726         if (!ret)
1727                 return 0;
1728         BUG_ON(!ordered_extent);
1729
1730         nolock = btrfs_is_free_space_inode(root, inode);
1731
1732         if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
1733                 BUG_ON(!list_empty(&ordered_extent->list));
1734                 ret = btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1735                 if (!ret) {
1736                         if (nolock)
1737                                 trans = btrfs_join_transaction_nolock(root);
1738                         else
1739                                 trans = btrfs_join_transaction(root);
1740                         BUG_ON(IS_ERR(trans));
1741                         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1742                         ret = btrfs_update_inode(trans, root, inode);
1743                         BUG_ON(ret);
1744                 }
1745                 goto out;
1746         }
1747
1748         lock_extent_bits(io_tree, ordered_extent->file_offset,
1749                          ordered_extent->file_offset + ordered_extent->len - 1,
1750                          0, &cached_state, GFP_NOFS);
1751
1752         if (nolock)
1753                 trans = btrfs_join_transaction_nolock(root);
1754         else
1755                 trans = btrfs_join_transaction(root);
1756         BUG_ON(IS_ERR(trans));
1757         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1758
1759         if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
1760                 compress_type = ordered_extent->compress_type;
1761         if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
1762                 BUG_ON(compress_type);
1763                 ret = btrfs_mark_extent_written(trans, inode,
1764                                                 ordered_extent->file_offset,
1765                                                 ordered_extent->file_offset +
1766                                                 ordered_extent->len);
1767                 BUG_ON(ret);
1768         } else {
1769                 BUG_ON(root == root->fs_info->tree_root);
1770                 ret = insert_reserved_file_extent(trans, inode,
1771                                                 ordered_extent->file_offset,
1772                                                 ordered_extent->start,
1773                                                 ordered_extent->disk_len,
1774                                                 ordered_extent->len,
1775                                                 ordered_extent->len,
1776                                                 compress_type, 0, 0,
1777                                                 BTRFS_FILE_EXTENT_REG);
1778                 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
1779                                    ordered_extent->file_offset,
1780                                    ordered_extent->len);
1781                 BUG_ON(ret);
1782         }
1783         unlock_extent_cached(io_tree, ordered_extent->file_offset,
1784                              ordered_extent->file_offset +
1785                              ordered_extent->len - 1, &cached_state, GFP_NOFS);
1786
1787         add_pending_csums(trans, inode, ordered_extent->file_offset,
1788                           &ordered_extent->list);
1789
1790         ret = btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1791         if (!ret) {
1792                 ret = btrfs_update_inode(trans, root, inode);
1793                 BUG_ON(ret);
1794         }
1795         ret = 0;
1796 out:
1797         if (nolock) {
1798                 if (trans)
1799                         btrfs_end_transaction_nolock(trans, root);
1800         } else {
1801                 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
1802                 if (trans)
1803                         btrfs_end_transaction(trans, root);
1804         }
1805
1806         /* once for us */
1807         btrfs_put_ordered_extent(ordered_extent);
1808         /* once for the tree */
1809         btrfs_put_ordered_extent(ordered_extent);
1810
1811         return 0;
1812 }
1813
1814 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
1815                                 struct extent_state *state, int uptodate)
1816 {
1817         trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
1818
1819         ClearPagePrivate2(page);
1820         return btrfs_finish_ordered_io(page->mapping->host, start, end);
1821 }
1822
1823 /*
1824  * When IO fails, either with EIO or csum verification fails, we
1825  * try other mirrors that might have a good copy of the data.  This
1826  * io_failure_record is used to record state as we go through all the
1827  * mirrors.  If another mirror has good data, the page is set up to date
1828  * and things continue.  If a good mirror can't be found, the original
1829  * bio end_io callback is called to indicate things have failed.
1830  */
1831 struct io_failure_record {
1832         struct page *page;
1833         u64 start;
1834         u64 len;
1835         u64 logical;
1836         unsigned long bio_flags;
1837         int last_mirror;
1838 };
1839
1840 static int btrfs_io_failed_hook(struct bio *failed_bio,
1841                          struct page *page, u64 start, u64 end,
1842                          struct extent_state *state)
1843 {
1844         struct io_failure_record *failrec = NULL;
1845         u64 private;
1846         struct extent_map *em;
1847         struct inode *inode = page->mapping->host;
1848         struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
1849         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1850         struct bio *bio;
1851         int num_copies;
1852         int ret;
1853         int rw;
1854         u64 logical;
1855
1856         ret = get_state_private(failure_tree, start, &private);
1857         if (ret) {
1858                 failrec = kmalloc(sizeof(*failrec), GFP_NOFS);
1859                 if (!failrec)
1860                         return -ENOMEM;
1861                 failrec->start = start;
1862                 failrec->len = end - start + 1;
1863                 failrec->last_mirror = 0;
1864                 failrec->bio_flags = 0;
1865
1866                 read_lock(&em_tree->lock);
1867                 em = lookup_extent_mapping(em_tree, start, failrec->len);
1868                 if (em->start > start || em->start + em->len < start) {
1869                         free_extent_map(em);
1870                         em = NULL;
1871                 }
1872                 read_unlock(&em_tree->lock);
1873
1874                 if (IS_ERR_OR_NULL(em)) {
1875                         kfree(failrec);
1876                         return -EIO;
1877                 }
1878                 logical = start - em->start;
1879                 logical = em->block_start + logical;
1880                 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
1881                         logical = em->block_start;
1882                         failrec->bio_flags = EXTENT_BIO_COMPRESSED;
1883                         extent_set_compress_type(&failrec->bio_flags,
1884                                                  em->compress_type);
1885                 }
1886                 failrec->logical = logical;
1887                 free_extent_map(em);
1888                 set_extent_bits(failure_tree, start, end, EXTENT_LOCKED |
1889                                 EXTENT_DIRTY, GFP_NOFS);
1890                 set_state_private(failure_tree, start,
1891                                  (u64)(unsigned long)failrec);
1892         } else {
1893                 failrec = (struct io_failure_record *)(unsigned long)private;
1894         }
1895         num_copies = btrfs_num_copies(
1896                               &BTRFS_I(inode)->root->fs_info->mapping_tree,
1897                               failrec->logical, failrec->len);
1898         failrec->last_mirror++;
1899         if (!state) {
1900                 spin_lock(&BTRFS_I(inode)->io_tree.lock);
1901                 state = find_first_extent_bit_state(&BTRFS_I(inode)->io_tree,
1902                                                     failrec->start,
1903                                                     EXTENT_LOCKED);
1904                 if (state && state->start != failrec->start)
1905                         state = NULL;
1906                 spin_unlock(&BTRFS_I(inode)->io_tree.lock);
1907         }
1908         if (!state || failrec->last_mirror > num_copies) {
1909                 set_state_private(failure_tree, failrec->start, 0);
1910                 clear_extent_bits(failure_tree, failrec->start,
1911                                   failrec->start + failrec->len - 1,
1912                                   EXTENT_LOCKED | EXTENT_DIRTY, GFP_NOFS);
1913                 kfree(failrec);
1914                 return -EIO;
1915         }
1916         bio = bio_alloc(GFP_NOFS, 1);
1917         bio->bi_private = state;
1918         bio->bi_end_io = failed_bio->bi_end_io;
1919         bio->bi_sector = failrec->logical >> 9;
1920         bio->bi_bdev = failed_bio->bi_bdev;
1921         bio->bi_size = 0;
1922
1923         bio_add_page(bio, page, failrec->len, start - page_offset(page));
1924         if (failed_bio->bi_rw & REQ_WRITE)
1925                 rw = WRITE;
1926         else
1927                 rw = READ;
1928
1929         ret = BTRFS_I(inode)->io_tree.ops->submit_bio_hook(inode, rw, bio,
1930                                                       failrec->last_mirror,
1931                                                       failrec->bio_flags, 0);
1932         return ret;
1933 }
1934
1935 /*
1936  * each time an IO finishes, we do a fast check in the IO failure tree
1937  * to see if we need to process or clean up an io_failure_record
1938  */
1939 static int btrfs_clean_io_failures(struct inode *inode, u64 start)
1940 {
1941         u64 private;
1942         u64 private_failure;
1943         struct io_failure_record *failure;
1944         int ret;
1945
1946         private = 0;
1947         if (count_range_bits(&BTRFS_I(inode)->io_failure_tree, &private,
1948                              (u64)-1, 1, EXTENT_DIRTY, 0)) {
1949                 ret = get_state_private(&BTRFS_I(inode)->io_failure_tree,
1950                                         start, &private_failure);
1951                 if (ret == 0) {
1952                         failure = (struct io_failure_record *)(unsigned long)
1953                                    private_failure;
1954                         set_state_private(&BTRFS_I(inode)->io_failure_tree,
1955                                           failure->start, 0);
1956                         clear_extent_bits(&BTRFS_I(inode)->io_failure_tree,
1957                                           failure->start,
1958                                           failure->start + failure->len - 1,
1959                                           EXTENT_DIRTY | EXTENT_LOCKED,
1960                                           GFP_NOFS);
1961                         kfree(failure);
1962                 }
1963         }
1964         return 0;
1965 }
1966
1967 /*
1968  * when reads are done, we need to check csums to verify the data is correct
1969  * if there's a match, we allow the bio to finish.  If not, we go through
1970  * the io_failure_record routines to find good copies
1971  */
1972 static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
1973                                struct extent_state *state)
1974 {
1975         size_t offset = start - ((u64)page->index << PAGE_CACHE_SHIFT);
1976         struct inode *inode = page->mapping->host;
1977         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1978         char *kaddr;
1979         u64 private = ~(u32)0;
1980         int ret;
1981         struct btrfs_root *root = BTRFS_I(inode)->root;
1982         u32 csum = ~(u32)0;
1983
1984         if (PageChecked(page)) {
1985                 ClearPageChecked(page);
1986                 goto good;
1987         }
1988
1989         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
1990                 goto good;
1991
1992         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
1993             test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
1994                 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
1995                                   GFP_NOFS);
1996                 return 0;
1997         }
1998
1999         if (state && state->start == start) {
2000                 private = state->private;
2001                 ret = 0;
2002         } else {
2003                 ret = get_state_private(io_tree, start, &private);
2004         }
2005         kaddr = kmap_atomic(page, KM_USER0);
2006         if (ret)
2007                 goto zeroit;
2008
2009         csum = btrfs_csum_data(root, kaddr + offset, csum,  end - start + 1);
2010         btrfs_csum_final(csum, (char *)&csum);
2011         if (csum != private)
2012                 goto zeroit;
2013
2014         kunmap_atomic(kaddr, KM_USER0);
2015 good:
2016         /* if the io failure tree for this inode is non-empty,
2017          * check to see if we've recovered from a failed IO
2018          */
2019         btrfs_clean_io_failures(inode, start);
2020         return 0;
2021
2022 zeroit:
2023         printk_ratelimited(KERN_INFO "btrfs csum failed ino %llu off %llu csum %u "
2024                        "private %llu\n",
2025                        (unsigned long long)btrfs_ino(page->mapping->host),
2026                        (unsigned long long)start, csum,
2027                        (unsigned long long)private);
2028         memset(kaddr + offset, 1, end - start + 1);
2029         flush_dcache_page(page);
2030         kunmap_atomic(kaddr, KM_USER0);
2031         if (private == 0)
2032                 return 0;
2033         return -EIO;
2034 }
2035
2036 struct delayed_iput {
2037         struct list_head list;
2038         struct inode *inode;
2039 };
2040
2041 void btrfs_add_delayed_iput(struct inode *inode)
2042 {
2043         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2044         struct delayed_iput *delayed;
2045
2046         if (atomic_add_unless(&inode->i_count, -1, 1))
2047                 return;
2048
2049         delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2050         delayed->inode = inode;
2051
2052         spin_lock(&fs_info->delayed_iput_lock);
2053         list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2054         spin_unlock(&fs_info->delayed_iput_lock);
2055 }
2056
2057 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2058 {
2059         LIST_HEAD(list);
2060         struct btrfs_fs_info *fs_info = root->fs_info;
2061         struct delayed_iput *delayed;
2062         int empty;
2063
2064         spin_lock(&fs_info->delayed_iput_lock);
2065         empty = list_empty(&fs_info->delayed_iputs);
2066         spin_unlock(&fs_info->delayed_iput_lock);
2067         if (empty)
2068                 return;
2069
2070         down_read(&root->fs_info->cleanup_work_sem);
2071         spin_lock(&fs_info->delayed_iput_lock);
2072         list_splice_init(&fs_info->delayed_iputs, &list);
2073         spin_unlock(&fs_info->delayed_iput_lock);
2074
2075         while (!list_empty(&list)) {
2076                 delayed = list_entry(list.next, struct delayed_iput, list);
2077                 list_del(&delayed->list);
2078                 iput(delayed->inode);
2079                 kfree(delayed);
2080         }
2081         up_read(&root->fs_info->cleanup_work_sem);
2082 }
2083
2084 /*
2085  * calculate extra metadata reservation when snapshotting a subvolume
2086  * contains orphan files.
2087  */
2088 void btrfs_orphan_pre_snapshot(struct btrfs_trans_handle *trans,
2089                                 struct btrfs_pending_snapshot *pending,
2090                                 u64 *bytes_to_reserve)
2091 {
2092         struct btrfs_root *root;
2093         struct btrfs_block_rsv *block_rsv;
2094         u64 num_bytes;
2095         int index;
2096
2097         root = pending->root;
2098         if (!root->orphan_block_rsv || list_empty(&root->orphan_list))
2099                 return;
2100
2101         block_rsv = root->orphan_block_rsv;
2102
2103         /* orphan block reservation for the snapshot */
2104         num_bytes = block_rsv->size;
2105
2106         /*
2107          * after the snapshot is created, COWing tree blocks may use more
2108          * space than it frees. So we should make sure there is enough
2109          * reserved space.
2110          */
2111         index = trans->transid & 0x1;
2112         if (block_rsv->reserved + block_rsv->freed[index] < block_rsv->size) {
2113                 num_bytes += block_rsv->size -
2114                              (block_rsv->reserved + block_rsv->freed[index]);
2115         }
2116
2117         *bytes_to_reserve += num_bytes;
2118 }
2119
2120 void btrfs_orphan_post_snapshot(struct btrfs_trans_handle *trans,
2121                                 struct btrfs_pending_snapshot *pending)
2122 {
2123         struct btrfs_root *root = pending->root;
2124         struct btrfs_root *snap = pending->snap;
2125         struct btrfs_block_rsv *block_rsv;
2126         u64 num_bytes;
2127         int index;
2128         int ret;
2129
2130         if (!root->orphan_block_rsv || list_empty(&root->orphan_list))
2131                 return;
2132
2133         /* refill source subvolume's orphan block reservation */
2134         block_rsv = root->orphan_block_rsv;
2135         index = trans->transid & 0x1;
2136         if (block_rsv->reserved + block_rsv->freed[index] < block_rsv->size) {
2137                 num_bytes = block_rsv->size -
2138                             (block_rsv->reserved + block_rsv->freed[index]);
2139                 ret = btrfs_block_rsv_migrate(&pending->block_rsv,
2140                                               root->orphan_block_rsv,
2141                                               num_bytes);
2142                 BUG_ON(ret);
2143         }
2144
2145         /* setup orphan block reservation for the snapshot */
2146         block_rsv = btrfs_alloc_block_rsv(snap);
2147         BUG_ON(!block_rsv);
2148
2149         btrfs_add_durable_block_rsv(root->fs_info, block_rsv);
2150         snap->orphan_block_rsv = block_rsv;
2151
2152         num_bytes = root->orphan_block_rsv->size;
2153         ret = btrfs_block_rsv_migrate(&pending->block_rsv,
2154                                       block_rsv, num_bytes);
2155         BUG_ON(ret);
2156
2157 #if 0
2158         /* insert orphan item for the snapshot */
2159         WARN_ON(!root->orphan_item_inserted);
2160         ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2161                                        snap->root_key.objectid);
2162         BUG_ON(ret);
2163         snap->orphan_item_inserted = 1;
2164 #endif
2165 }
2166
2167 enum btrfs_orphan_cleanup_state {
2168         ORPHAN_CLEANUP_STARTED  = 1,
2169         ORPHAN_CLEANUP_DONE     = 2,
2170 };
2171
2172 /*
2173  * This is called in transaction commmit time. If there are no orphan
2174  * files in the subvolume, it removes orphan item and frees block_rsv
2175  * structure.
2176  */
2177 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2178                               struct btrfs_root *root)
2179 {
2180         int ret;
2181
2182         if (!list_empty(&root->orphan_list) ||
2183             root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2184                 return;
2185
2186         if (root->orphan_item_inserted &&
2187             btrfs_root_refs(&root->root_item) > 0) {
2188                 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2189                                             root->root_key.objectid);
2190                 BUG_ON(ret);
2191                 root->orphan_item_inserted = 0;
2192         }
2193
2194         if (root->orphan_block_rsv) {
2195                 WARN_ON(root->orphan_block_rsv->size > 0);
2196                 btrfs_free_block_rsv(root, root->orphan_block_rsv);
2197                 root->orphan_block_rsv = NULL;
2198         }
2199 }
2200
2201 /*
2202  * This creates an orphan entry for the given inode in case something goes
2203  * wrong in the middle of an unlink/truncate.
2204  *
2205  * NOTE: caller of this function should reserve 5 units of metadata for
2206  *       this function.
2207  */
2208 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2209 {
2210         struct btrfs_root *root = BTRFS_I(inode)->root;
2211         struct btrfs_block_rsv *block_rsv = NULL;
2212         int reserve = 0;
2213         int insert = 0;
2214         int ret;
2215
2216         if (!root->orphan_block_rsv) {
2217                 block_rsv = btrfs_alloc_block_rsv(root);
2218                 BUG_ON(!block_rsv);
2219         }
2220
2221         spin_lock(&root->orphan_lock);
2222         if (!root->orphan_block_rsv) {
2223                 root->orphan_block_rsv = block_rsv;
2224         } else if (block_rsv) {
2225                 btrfs_free_block_rsv(root, block_rsv);
2226                 block_rsv = NULL;
2227         }
2228
2229         if (list_empty(&BTRFS_I(inode)->i_orphan)) {
2230                 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
2231 #if 0
2232                 /*
2233                  * For proper ENOSPC handling, we should do orphan
2234                  * cleanup when mounting. But this introduces backward
2235                  * compatibility issue.
2236                  */
2237                 if (!xchg(&root->orphan_item_inserted, 1))
2238                         insert = 2;
2239                 else
2240                         insert = 1;
2241 #endif
2242                 insert = 1;
2243         }
2244
2245         if (!BTRFS_I(inode)->orphan_meta_reserved) {
2246                 BTRFS_I(inode)->orphan_meta_reserved = 1;
2247                 reserve = 1;
2248         }
2249         spin_unlock(&root->orphan_lock);
2250
2251         if (block_rsv)
2252                 btrfs_add_durable_block_rsv(root->fs_info, block_rsv);
2253
2254         /* grab metadata reservation from transaction handle */
2255         if (reserve) {
2256                 ret = btrfs_orphan_reserve_metadata(trans, inode);
2257                 BUG_ON(ret);
2258         }
2259
2260         /* insert an orphan item to track this unlinked/truncated file */
2261         if (insert >= 1) {
2262                 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
2263                 BUG_ON(ret);
2264         }
2265
2266         /* insert an orphan item to track subvolume contains orphan files */
2267         if (insert >= 2) {
2268                 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2269                                                root->root_key.objectid);
2270                 BUG_ON(ret);
2271         }
2272         return 0;
2273 }
2274
2275 /*
2276  * We have done the truncate/delete so we can go ahead and remove the orphan
2277  * item for this particular inode.
2278  */
2279 int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode)
2280 {
2281         struct btrfs_root *root = BTRFS_I(inode)->root;
2282         int delete_item = 0;
2283         int release_rsv = 0;
2284         int ret = 0;
2285
2286         spin_lock(&root->orphan_lock);
2287         if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
2288                 list_del_init(&BTRFS_I(inode)->i_orphan);
2289                 delete_item = 1;
2290         }
2291
2292         if (BTRFS_I(inode)->orphan_meta_reserved) {
2293                 BTRFS_I(inode)->orphan_meta_reserved = 0;
2294                 release_rsv = 1;
2295         }
2296         spin_unlock(&root->orphan_lock);
2297
2298         if (trans && delete_item) {
2299                 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
2300                 BUG_ON(ret);
2301         }
2302
2303         if (release_rsv)
2304                 btrfs_orphan_release_metadata(inode);
2305
2306         return 0;
2307 }
2308
2309 /*
2310  * this cleans up any orphans that may be left on the list from the last use
2311  * of this root.
2312  */
2313 int btrfs_orphan_cleanup(struct btrfs_root *root)
2314 {
2315         struct btrfs_path *path;
2316         struct extent_buffer *leaf;
2317         struct btrfs_key key, found_key;
2318         struct btrfs_trans_handle *trans;
2319         struct inode *inode;
2320         int ret = 0, nr_unlink = 0, nr_truncate = 0;
2321
2322         if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
2323                 return 0;
2324
2325         path = btrfs_alloc_path();
2326         if (!path) {
2327                 ret = -ENOMEM;
2328                 goto out;
2329         }
2330         path->reada = -1;
2331
2332         key.objectid = BTRFS_ORPHAN_OBJECTID;
2333         btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
2334         key.offset = (u64)-1;
2335
2336         while (1) {
2337                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2338                 if (ret < 0)
2339                         goto out;
2340
2341                 /*
2342                  * if ret == 0 means we found what we were searching for, which
2343                  * is weird, but possible, so only screw with path if we didn't
2344                  * find the key and see if we have stuff that matches
2345                  */
2346                 if (ret > 0) {
2347                         ret = 0;
2348                         if (path->slots[0] == 0)
2349                                 break;
2350                         path->slots[0]--;
2351                 }
2352
2353                 /* pull out the item */
2354                 leaf = path->nodes[0];
2355                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2356
2357                 /* make sure the item matches what we want */
2358                 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
2359                         break;
2360                 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
2361                         break;
2362
2363                 /* release the path since we're done with it */
2364                 btrfs_release_path(path);
2365
2366                 /*
2367                  * this is where we are basically btrfs_lookup, without the
2368                  * crossing root thing.  we store the inode number in the
2369                  * offset of the orphan item.
2370                  */
2371                 found_key.objectid = found_key.offset;
2372                 found_key.type = BTRFS_INODE_ITEM_KEY;
2373                 found_key.offset = 0;
2374                 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
2375                 if (IS_ERR(inode)) {
2376                         ret = PTR_ERR(inode);
2377                         goto out;
2378                 }
2379
2380                 /*
2381                  * add this inode to the orphan list so btrfs_orphan_del does
2382                  * the proper thing when we hit it
2383                  */
2384                 spin_lock(&root->orphan_lock);
2385                 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
2386                 spin_unlock(&root->orphan_lock);
2387
2388                 /*
2389                  * if this is a bad inode, means we actually succeeded in
2390                  * removing the inode, but not the orphan record, which means
2391                  * we need to manually delete the orphan since iput will just
2392                  * do a destroy_inode
2393                  */
2394                 if (is_bad_inode(inode)) {
2395                         trans = btrfs_start_transaction(root, 0);
2396                         if (IS_ERR(trans)) {
2397                                 ret = PTR_ERR(trans);
2398                                 goto out;
2399                         }
2400                         btrfs_orphan_del(trans, inode);
2401                         btrfs_end_transaction(trans, root);
2402                         iput(inode);
2403                         continue;
2404                 }
2405
2406                 /* if we have links, this was a truncate, lets do that */
2407                 if (inode->i_nlink) {
2408                         if (!S_ISREG(inode->i_mode)) {
2409                                 WARN_ON(1);
2410                                 iput(inode);
2411                                 continue;
2412                         }
2413                         nr_truncate++;
2414                         ret = btrfs_truncate(inode);
2415                 } else {
2416                         nr_unlink++;
2417                 }
2418
2419                 /* this will do delete_inode and everything for us */
2420                 iput(inode);
2421                 if (ret)
2422                         goto out;
2423         }
2424         root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
2425
2426         if (root->orphan_block_rsv)
2427                 btrfs_block_rsv_release(root, root->orphan_block_rsv,
2428                                         (u64)-1);
2429
2430         if (root->orphan_block_rsv || root->orphan_item_inserted) {
2431                 trans = btrfs_join_transaction(root);
2432                 if (!IS_ERR(trans))
2433                         btrfs_end_transaction(trans, root);
2434         }
2435
2436         if (nr_unlink)
2437                 printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink);
2438         if (nr_truncate)
2439                 printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate);
2440
2441 out:
2442         if (ret)
2443                 printk(KERN_CRIT "btrfs: could not do orphan cleanup %d\n", ret);
2444         btrfs_free_path(path);
2445         return ret;
2446 }
2447
2448 /*
2449  * very simple check to peek ahead in the leaf looking for xattrs.  If we
2450  * don't find any xattrs, we know there can't be any acls.
2451  *
2452  * slot is the slot the inode is in, objectid is the objectid of the inode
2453  */
2454 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
2455                                           int slot, u64 objectid)
2456 {
2457         u32 nritems = btrfs_header_nritems(leaf);
2458         struct btrfs_key found_key;
2459         int scanned = 0;
2460
2461         slot++;
2462         while (slot < nritems) {
2463                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2464
2465                 /* we found a different objectid, there must not be acls */
2466                 if (found_key.objectid != objectid)
2467                         return 0;
2468
2469                 /* we found an xattr, assume we've got an acl */
2470                 if (found_key.type == BTRFS_XATTR_ITEM_KEY)
2471                         return 1;
2472
2473                 /*
2474                  * we found a key greater than an xattr key, there can't
2475                  * be any acls later on
2476                  */
2477                 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
2478                         return 0;
2479
2480                 slot++;
2481                 scanned++;
2482
2483                 /*
2484                  * it goes inode, inode backrefs, xattrs, extents,
2485                  * so if there are a ton of hard links to an inode there can
2486                  * be a lot of backrefs.  Don't waste time searching too hard,
2487                  * this is just an optimization
2488                  */
2489                 if (scanned >= 8)
2490                         break;
2491         }
2492         /* we hit the end of the leaf before we found an xattr or
2493          * something larger than an xattr.  We have to assume the inode
2494          * has acls
2495          */
2496         return 1;
2497 }
2498
2499 /*
2500  * read an inode from the btree into the in-memory inode
2501  */
2502 static void btrfs_read_locked_inode(struct inode *inode)
2503 {
2504         struct btrfs_path *path;
2505         struct extent_buffer *leaf;
2506         struct btrfs_inode_item *inode_item;
2507         struct btrfs_timespec *tspec;
2508         struct btrfs_root *root = BTRFS_I(inode)->root;
2509         struct btrfs_key location;
2510         int maybe_acls;
2511         u32 rdev;
2512         int ret;
2513         bool filled = false;
2514
2515         ret = btrfs_fill_inode(inode, &rdev);
2516         if (!ret)
2517                 filled = true;
2518
2519         path = btrfs_alloc_path();
2520         BUG_ON(!path);
2521         path->leave_spinning = 1;
2522         memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
2523
2524         ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
2525         if (ret)
2526                 goto make_bad;
2527
2528         leaf = path->nodes[0];
2529
2530         if (filled)
2531                 goto cache_acl;
2532
2533         inode_item = btrfs_item_ptr(leaf, path->slots[0],
2534                                     struct btrfs_inode_item);
2535         inode->i_mode = btrfs_inode_mode(leaf, inode_item);
2536         inode->i_nlink = btrfs_inode_nlink(leaf, inode_item);
2537         inode->i_uid = btrfs_inode_uid(leaf, inode_item);
2538         inode->i_gid = btrfs_inode_gid(leaf, inode_item);
2539         btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
2540
2541         tspec = btrfs_inode_atime(inode_item);
2542         inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2543         inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2544
2545         tspec = btrfs_inode_mtime(inode_item);
2546         inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2547         inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2548
2549         tspec = btrfs_inode_ctime(inode_item);
2550         inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2551         inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2552
2553         inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
2554         BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
2555         BTRFS_I(inode)->sequence = btrfs_inode_sequence(leaf, inode_item);
2556         inode->i_generation = BTRFS_I(inode)->generation;
2557         inode->i_rdev = 0;
2558         rdev = btrfs_inode_rdev(leaf, inode_item);
2559
2560         BTRFS_I(inode)->index_cnt = (u64)-1;
2561         BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
2562 cache_acl:
2563         /*
2564          * try to precache a NULL acl entry for files that don't have
2565          * any xattrs or acls
2566          */
2567         maybe_acls = acls_after_inode_item(leaf, path->slots[0],
2568                                            btrfs_ino(inode));
2569         if (!maybe_acls)
2570                 cache_no_acl(inode);
2571
2572         btrfs_free_path(path);
2573
2574         switch (inode->i_mode & S_IFMT) {
2575         case S_IFREG:
2576                 inode->i_mapping->a_ops = &btrfs_aops;
2577                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2578                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
2579                 inode->i_fop = &btrfs_file_operations;
2580                 inode->i_op = &btrfs_file_inode_operations;
2581                 break;
2582         case S_IFDIR:
2583                 inode->i_fop = &btrfs_dir_file_operations;
2584                 if (root == root->fs_info->tree_root)
2585                         inode->i_op = &btrfs_dir_ro_inode_operations;
2586                 else
2587                         inode->i_op = &btrfs_dir_inode_operations;
2588                 break;
2589         case S_IFLNK:
2590                 inode->i_op = &btrfs_symlink_inode_operations;
2591                 inode->i_mapping->a_ops = &btrfs_symlink_aops;
2592                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2593                 break;
2594         default:
2595                 inode->i_op = &btrfs_special_inode_operations;
2596                 init_special_inode(inode, inode->i_mode, rdev);
2597                 break;
2598         }
2599
2600         btrfs_update_iflags(inode);
2601         return;
2602
2603 make_bad:
2604         btrfs_free_path(path);
2605         make_bad_inode(inode);
2606 }
2607
2608 /*
2609  * given a leaf and an inode, copy the inode fields into the leaf
2610  */
2611 static void fill_inode_item(struct btrfs_trans_handle *trans,
2612                             struct extent_buffer *leaf,
2613                             struct btrfs_inode_item *item,
2614                             struct inode *inode)
2615 {
2616         btrfs_set_inode_uid(leaf, item, inode->i_uid);
2617         btrfs_set_inode_gid(leaf, item, inode->i_gid);
2618         btrfs_set_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size);
2619         btrfs_set_inode_mode(leaf, item, inode->i_mode);
2620         btrfs_set_inode_nlink(leaf, item, inode->i_nlink);
2621
2622         btrfs_set_timespec_sec(leaf, btrfs_inode_atime(item),
2623                                inode->i_atime.tv_sec);
2624         btrfs_set_timespec_nsec(leaf, btrfs_inode_atime(item),
2625                                 inode->i_atime.tv_nsec);
2626
2627         btrfs_set_timespec_sec(leaf, btrfs_inode_mtime(item),
2628                                inode->i_mtime.tv_sec);
2629         btrfs_set_timespec_nsec(leaf, btrfs_inode_mtime(item),
2630                                 inode->i_mtime.tv_nsec);
2631
2632         btrfs_set_timespec_sec(leaf, btrfs_inode_ctime(item),
2633                                inode->i_ctime.tv_sec);
2634         btrfs_set_timespec_nsec(leaf, btrfs_inode_ctime(item),
2635                                 inode->i_ctime.tv_nsec);
2636
2637         btrfs_set_inode_nbytes(leaf, item, inode_get_bytes(inode));
2638         btrfs_set_inode_generation(leaf, item, BTRFS_I(inode)->generation);
2639         btrfs_set_inode_sequence(leaf, item, BTRFS_I(inode)->sequence);
2640         btrfs_set_inode_transid(leaf, item, trans->transid);
2641         btrfs_set_inode_rdev(leaf, item, inode->i_rdev);
2642         btrfs_set_inode_flags(leaf, item, BTRFS_I(inode)->flags);
2643         btrfs_set_inode_block_group(leaf, item, 0);
2644 }
2645
2646 /*
2647  * copy everything in the in-memory inode into the btree.
2648  */
2649 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
2650                                 struct btrfs_root *root, struct inode *inode)
2651 {
2652         struct btrfs_inode_item *inode_item;
2653         struct btrfs_path *path;
2654         struct extent_buffer *leaf;
2655         int ret;
2656
2657         /*
2658          * If the inode is a free space inode, we can deadlock during commit
2659          * if we put it into the delayed code.
2660          *
2661          * The data relocation inode should also be directly updated
2662          * without delay
2663          */
2664         if (!btrfs_is_free_space_inode(root, inode)
2665             && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
2666                 ret = btrfs_delayed_update_inode(trans, root, inode);
2667                 if (!ret)
2668                         btrfs_set_inode_last_trans(trans, inode);
2669                 return ret;
2670         }
2671
2672         path = btrfs_alloc_path();
2673         if (!path)
2674                 return -ENOMEM;
2675
2676         path->leave_spinning = 1;
2677         ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
2678                                  1);
2679         if (ret) {
2680                 if (ret > 0)
2681                         ret = -ENOENT;
2682                 goto failed;
2683         }
2684
2685         btrfs_unlock_up_safe(path, 1);
2686         leaf = path->nodes[0];
2687         inode_item = btrfs_item_ptr(leaf, path->slots[0],
2688                                     struct btrfs_inode_item);
2689
2690         fill_inode_item(trans, leaf, inode_item, inode);
2691         btrfs_mark_buffer_dirty(leaf);
2692         btrfs_set_inode_last_trans(trans, inode);
2693         ret = 0;
2694 failed:
2695         btrfs_free_path(path);
2696         return ret;
2697 }
2698
2699 /*
2700  * unlink helper that gets used here in inode.c and in the tree logging
2701  * recovery code.  It remove a link in a directory with a given name, and
2702  * also drops the back refs in the inode to the directory
2703  */
2704 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2705                                 struct btrfs_root *root,
2706                                 struct inode *dir, struct inode *inode,
2707                                 const char *name, int name_len)
2708 {
2709         struct btrfs_path *path;
2710         int ret = 0;
2711         struct extent_buffer *leaf;
2712         struct btrfs_dir_item *di;
2713         struct btrfs_key key;
2714         u64 index;
2715         u64 ino = btrfs_ino(inode);
2716         u64 dir_ino = btrfs_ino(dir);
2717
2718         path = btrfs_alloc_path();
2719         if (!path) {
2720                 ret = -ENOMEM;
2721                 goto out;
2722         }
2723
2724         path->leave_spinning = 1;
2725         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
2726                                     name, name_len, -1);
2727         if (IS_ERR(di)) {
2728                 ret = PTR_ERR(di);
2729                 goto err;
2730         }
2731         if (!di) {
2732                 ret = -ENOENT;
2733                 goto err;
2734         }
2735         leaf = path->nodes[0];
2736         btrfs_dir_item_key_to_cpu(leaf, di, &key);
2737         ret = btrfs_delete_one_dir_name(trans, root, path, di);
2738         if (ret)
2739                 goto err;
2740         btrfs_release_path(path);
2741
2742         ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
2743                                   dir_ino, &index);
2744         if (ret) {
2745                 printk(KERN_INFO "btrfs failed to delete reference to %.*s, "
2746                        "inode %llu parent %llu\n", name_len, name,
2747                        (unsigned long long)ino, (unsigned long long)dir_ino);
2748                 goto err;
2749         }
2750
2751         ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
2752         if (ret)
2753                 goto err;
2754
2755         ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
2756                                          inode, dir_ino);
2757         BUG_ON(ret != 0 && ret != -ENOENT);
2758
2759         ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
2760                                            dir, index);
2761         if (ret == -ENOENT)
2762                 ret = 0;
2763 err:
2764         btrfs_free_path(path);
2765         if (ret)
2766                 goto out;
2767
2768         btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2769         inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2770         btrfs_update_inode(trans, root, dir);
2771 out:
2772         return ret;
2773 }
2774
2775 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2776                        struct btrfs_root *root,
2777                        struct inode *dir, struct inode *inode,
2778                        const char *name, int name_len)
2779 {
2780         int ret;
2781         ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
2782         if (!ret) {
2783                 btrfs_drop_nlink(inode);
2784                 ret = btrfs_update_inode(trans, root, inode);
2785         }
2786         return ret;
2787 }
2788                 
2789
2790 /* helper to check if there is any shared block in the path */
2791 static int check_path_shared(struct btrfs_root *root,
2792                              struct btrfs_path *path)
2793 {
2794         struct extent_buffer *eb;
2795         int level;
2796         u64 refs = 1;
2797
2798         for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2799                 int ret;
2800
2801                 if (!path->nodes[level])
2802                         break;
2803                 eb = path->nodes[level];
2804                 if (!btrfs_block_can_be_shared(root, eb))
2805                         continue;
2806                 ret = btrfs_lookup_extent_info(NULL, root, eb->start, eb->len,
2807                                                &refs, NULL);
2808                 if (refs > 1)
2809                         return 1;
2810         }
2811         return 0;
2812 }
2813
2814 /*
2815  * helper to start transaction for unlink and rmdir.
2816  *
2817  * unlink and rmdir are special in btrfs, they do not always free space.
2818  * so in enospc case, we should make sure they will free space before
2819  * allowing them to use the global metadata reservation.
2820  */
2821 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir,
2822                                                        struct dentry *dentry)
2823 {
2824         struct btrfs_trans_handle *trans;
2825         struct btrfs_root *root = BTRFS_I(dir)->root;
2826         struct btrfs_path *path;
2827         struct btrfs_inode_ref *ref;
2828         struct btrfs_dir_item *di;
2829         struct inode *inode = dentry->d_inode;
2830         u64 index;
2831         int check_link = 1;
2832         int err = -ENOSPC;
2833         int ret;
2834         u64 ino = btrfs_ino(inode);
2835         u64 dir_ino = btrfs_ino(dir);
2836
2837         trans = btrfs_start_transaction(root, 10);
2838         if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
2839                 return trans;
2840
2841         if (ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
2842                 return ERR_PTR(-ENOSPC);
2843
2844         /* check if there is someone else holds reference */
2845         if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1)
2846                 return ERR_PTR(-ENOSPC);
2847
2848         if (atomic_read(&inode->i_count) > 2)
2849                 return ERR_PTR(-ENOSPC);
2850
2851         if (xchg(&root->fs_info->enospc_unlink, 1))
2852                 return ERR_PTR(-ENOSPC);
2853
2854         path = btrfs_alloc_path();
2855         if (!path) {
2856                 root->fs_info->enospc_unlink = 0;
2857                 return ERR_PTR(-ENOMEM);
2858         }
2859
2860         trans = btrfs_start_transaction(root, 0);
2861         if (IS_ERR(trans)) {
2862                 btrfs_free_path(path);
2863                 root->fs_info->enospc_unlink = 0;
2864                 return trans;
2865         }
2866
2867         path->skip_locking = 1;
2868         path->search_commit_root = 1;
2869
2870         ret = btrfs_lookup_inode(trans, root, path,
2871                                 &BTRFS_I(dir)->location, 0);
2872         if (ret < 0) {
2873                 err = ret;
2874                 goto out;
2875         }
2876         if (ret == 0) {
2877                 if (check_path_shared(root, path))
2878                         goto out;
2879         } else {
2880                 check_link = 0;
2881         }
2882         btrfs_release_path(path);
2883
2884         ret = btrfs_lookup_inode(trans, root, path,
2885                                 &BTRFS_I(inode)->location, 0);
2886         if (ret < 0) {
2887                 err = ret;
2888                 goto out;
2889         }
2890         if (ret == 0) {
2891                 if (check_path_shared(root, path))
2892                         goto out;
2893         } else {
2894                 check_link = 0;
2895         }
2896         btrfs_release_path(path);
2897
2898         if (ret == 0 && S_ISREG(inode->i_mode)) {
2899                 ret = btrfs_lookup_file_extent(trans, root, path,
2900                                                ino, (u64)-1, 0);
2901                 if (ret < 0) {
2902                         err = ret;
2903                         goto out;
2904                 }
2905                 BUG_ON(ret == 0);
2906                 if (check_path_shared(root, path))
2907                         goto out;
2908                 btrfs_release_path(path);
2909         }
2910
2911         if (!check_link) {
2912                 err = 0;
2913                 goto out;
2914         }
2915
2916         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
2917                                 dentry->d_name.name, dentry->d_name.len, 0);
2918         if (IS_ERR(di)) {
2919                 err = PTR_ERR(di);
2920                 goto out;
2921         }
2922         if (di) {
2923                 if (check_path_shared(root, path))
2924                         goto out;
2925         } else {
2926                 err = 0;
2927                 goto out;
2928         }
2929         btrfs_release_path(path);
2930
2931         ref = btrfs_lookup_inode_ref(trans, root, path,
2932                                 dentry->d_name.name, dentry->d_name.len,
2933                                 ino, dir_ino, 0);
2934         if (IS_ERR(ref)) {
2935                 err = PTR_ERR(ref);
2936                 goto out;
2937         }
2938         BUG_ON(!ref);
2939         if (check_path_shared(root, path))
2940                 goto out;
2941         index = btrfs_inode_ref_index(path->nodes[0], ref);
2942         btrfs_release_path(path);
2943
2944         /*
2945          * This is a commit root search, if we can lookup inode item and other
2946          * relative items in the commit root, it means the transaction of
2947          * dir/file creation has been committed, and the dir index item that we
2948          * delay to insert has also been inserted into the commit root. So
2949          * we needn't worry about the delayed insertion of the dir index item
2950          * here.
2951          */
2952         di = btrfs_lookup_dir_index_item(trans, root, path, dir_ino, index,
2953                                 dentry->d_name.name, dentry->d_name.len, 0);
2954         if (IS_ERR(di)) {
2955                 err = PTR_ERR(di);
2956                 goto out;
2957         }
2958         BUG_ON(ret == -ENOENT);
2959         if (check_path_shared(root, path))
2960                 goto out;
2961
2962         err = 0;
2963 out:
2964         btrfs_free_path(path);
2965         if (err) {
2966                 btrfs_end_transaction(trans, root);
2967                 root->fs_info->enospc_unlink = 0;
2968                 return ERR_PTR(err);
2969         }
2970
2971         trans->block_rsv = &root->fs_info->global_block_rsv;
2972         return trans;
2973 }
2974
2975 static void __unlink_end_trans(struct btrfs_trans_handle *trans,
2976                                struct btrfs_root *root)
2977 {
2978         if (trans->block_rsv == &root->fs_info->global_block_rsv) {
2979                 BUG_ON(!root->fs_info->enospc_unlink);
2980                 root->fs_info->enospc_unlink = 0;
2981         }
2982         btrfs_end_transaction_throttle(trans, root);
2983 }
2984
2985 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
2986 {
2987         struct btrfs_root *root = BTRFS_I(dir)->root;
2988         struct btrfs_trans_handle *trans;
2989         struct inode *inode = dentry->d_inode;
2990         int ret;
2991         unsigned long nr = 0;
2992
2993         trans = __unlink_start_trans(dir, dentry);
2994         if (IS_ERR(trans))
2995                 return PTR_ERR(trans);
2996
2997         btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
2998
2999         ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3000                                  dentry->d_name.name, dentry->d_name.len);
3001         BUG_ON(ret);
3002
3003         if (inode->i_nlink == 0) {
3004                 ret = btrfs_orphan_add(trans, inode);
3005                 BUG_ON(ret);
3006         }
3007
3008         nr = trans->blocks_used;
3009         __unlink_end_trans(trans, root);
3010         btrfs_btree_balance_dirty(root, nr);
3011         return ret;
3012 }
3013
3014 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3015                         struct btrfs_root *root,
3016                         struct inode *dir, u64 objectid,
3017                         const char *name, int name_len)
3018 {
3019         struct btrfs_path *path;
3020         struct extent_buffer *leaf;
3021         struct btrfs_dir_item *di;
3022         struct btrfs_key key;
3023         u64 index;
3024         int ret;
3025         u64 dir_ino = btrfs_ino(dir);
3026
3027         path = btrfs_alloc_path();
3028         if (!path)
3029                 return -ENOMEM;
3030
3031         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3032                                    name, name_len, -1);
3033         BUG_ON(IS_ERR_OR_NULL(di));
3034
3035         leaf = path->nodes[0];
3036         btrfs_dir_item_key_to_cpu(leaf, di, &key);
3037         WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3038         ret = btrfs_delete_one_dir_name(trans, root, path, di);
3039         BUG_ON(ret);
3040         btrfs_release_path(path);
3041
3042         ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3043                                  objectid, root->root_key.objectid,
3044                                  dir_ino, &index, name, name_len);
3045         if (ret < 0) {
3046                 BUG_ON(ret != -ENOENT);
3047                 di = btrfs_search_dir_index_item(root, path, dir_ino,
3048                                                  name, name_len);
3049                 BUG_ON(IS_ERR_OR_NULL(di));
3050
3051                 leaf = path->nodes[0];
3052                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3053                 btrfs_release_path(path);
3054                 index = key.offset;
3055         }
3056         btrfs_release_path(path);
3057
3058         ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3059         BUG_ON(ret);
3060
3061         btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3062         dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3063         ret = btrfs_update_inode(trans, root, dir);
3064         BUG_ON(ret);
3065
3066         btrfs_free_path(path);
3067         return 0;
3068 }
3069
3070 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3071 {
3072         struct inode *inode = dentry->d_inode;
3073         int err = 0;
3074         struct btrfs_root *root = BTRFS_I(dir)->root;
3075         struct btrfs_trans_handle *trans;
3076         unsigned long nr = 0;
3077
3078         if (inode->i_size > BTRFS_EMPTY_DIR_SIZE ||
3079             btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
3080                 return -ENOTEMPTY;
3081
3082         trans = __unlink_start_trans(dir, dentry);
3083         if (IS_ERR(trans))
3084                 return PTR_ERR(trans);
3085
3086         if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3087                 err = btrfs_unlink_subvol(trans, root, dir,
3088                                           BTRFS_I(inode)->location.objectid,