Btrfs: convert the inode bit field to use the actual bit operations
[firefly-linux-kernel-4.4.55.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 <linux/mount.h>
42 #include "compat.h"
43 #include "ctree.h"
44 #include "disk-io.h"
45 #include "transaction.h"
46 #include "btrfs_inode.h"
47 #include "ioctl.h"
48 #include "print-tree.h"
49 #include "ordered-data.h"
50 #include "xattr.h"
51 #include "tree-log.h"
52 #include "volumes.h"
53 #include "compression.h"
54 #include "locking.h"
55 #include "free-space-cache.h"
56 #include "inode-map.h"
57
58 struct btrfs_iget_args {
59         u64 ino;
60         struct btrfs_root *root;
61 };
62
63 static const struct inode_operations btrfs_dir_inode_operations;
64 static const struct inode_operations btrfs_symlink_inode_operations;
65 static const struct inode_operations btrfs_dir_ro_inode_operations;
66 static const struct inode_operations btrfs_special_inode_operations;
67 static const struct inode_operations btrfs_file_inode_operations;
68 static const struct address_space_operations btrfs_aops;
69 static const struct address_space_operations btrfs_symlink_aops;
70 static const struct file_operations btrfs_dir_file_operations;
71 static struct extent_io_ops btrfs_extent_io_ops;
72
73 static struct kmem_cache *btrfs_inode_cachep;
74 struct kmem_cache *btrfs_trans_handle_cachep;
75 struct kmem_cache *btrfs_transaction_cachep;
76 struct kmem_cache *btrfs_path_cachep;
77 struct kmem_cache *btrfs_free_space_cachep;
78
79 #define S_SHIFT 12
80 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
81         [S_IFREG >> S_SHIFT]    = BTRFS_FT_REG_FILE,
82         [S_IFDIR >> S_SHIFT]    = BTRFS_FT_DIR,
83         [S_IFCHR >> S_SHIFT]    = BTRFS_FT_CHRDEV,
84         [S_IFBLK >> S_SHIFT]    = BTRFS_FT_BLKDEV,
85         [S_IFIFO >> S_SHIFT]    = BTRFS_FT_FIFO,
86         [S_IFSOCK >> S_SHIFT]   = BTRFS_FT_SOCK,
87         [S_IFLNK >> S_SHIFT]    = BTRFS_FT_SYMLINK,
88 };
89
90 static int btrfs_setsize(struct inode *inode, loff_t newsize);
91 static int btrfs_truncate(struct inode *inode);
92 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
93 static noinline int cow_file_range(struct inode *inode,
94                                    struct page *locked_page,
95                                    u64 start, u64 end, int *page_started,
96                                    unsigned long *nr_written, int unlock);
97 static noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
98                                 struct btrfs_root *root, struct inode *inode);
99
100 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
101                                      struct inode *inode,  struct inode *dir,
102                                      const struct qstr *qstr)
103 {
104         int err;
105
106         err = btrfs_init_acl(trans, inode, dir);
107         if (!err)
108                 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
109         return err;
110 }
111
112 /*
113  * this does all the hard work for inserting an inline extent into
114  * the btree.  The caller should have done a btrfs_drop_extents so that
115  * no overlapping inline items exist in the btree
116  */
117 static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
118                                 struct btrfs_root *root, struct inode *inode,
119                                 u64 start, size_t size, size_t compressed_size,
120                                 int compress_type,
121                                 struct page **compressed_pages)
122 {
123         struct btrfs_key key;
124         struct btrfs_path *path;
125         struct extent_buffer *leaf;
126         struct page *page = NULL;
127         char *kaddr;
128         unsigned long ptr;
129         struct btrfs_file_extent_item *ei;
130         int err = 0;
131         int ret;
132         size_t cur_size = size;
133         size_t datasize;
134         unsigned long offset;
135
136         if (compressed_size && compressed_pages)
137                 cur_size = compressed_size;
138
139         path = btrfs_alloc_path();
140         if (!path)
141                 return -ENOMEM;
142
143         path->leave_spinning = 1;
144
145         key.objectid = btrfs_ino(inode);
146         key.offset = start;
147         btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
148         datasize = btrfs_file_extent_calc_inline_size(cur_size);
149
150         inode_add_bytes(inode, size);
151         ret = btrfs_insert_empty_item(trans, root, path, &key,
152                                       datasize);
153         if (ret) {
154                 err = ret;
155                 goto fail;
156         }
157         leaf = path->nodes[0];
158         ei = btrfs_item_ptr(leaf, path->slots[0],
159                             struct btrfs_file_extent_item);
160         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
161         btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
162         btrfs_set_file_extent_encryption(leaf, ei, 0);
163         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
164         btrfs_set_file_extent_ram_bytes(leaf, ei, size);
165         ptr = btrfs_file_extent_inline_start(ei);
166
167         if (compress_type != BTRFS_COMPRESS_NONE) {
168                 struct page *cpage;
169                 int i = 0;
170                 while (compressed_size > 0) {
171                         cpage = compressed_pages[i];
172                         cur_size = min_t(unsigned long, compressed_size,
173                                        PAGE_CACHE_SIZE);
174
175                         kaddr = kmap_atomic(cpage);
176                         write_extent_buffer(leaf, kaddr, ptr, cur_size);
177                         kunmap_atomic(kaddr);
178
179                         i++;
180                         ptr += cur_size;
181                         compressed_size -= cur_size;
182                 }
183                 btrfs_set_file_extent_compression(leaf, ei,
184                                                   compress_type);
185         } else {
186                 page = find_get_page(inode->i_mapping,
187                                      start >> PAGE_CACHE_SHIFT);
188                 btrfs_set_file_extent_compression(leaf, ei, 0);
189                 kaddr = kmap_atomic(page);
190                 offset = start & (PAGE_CACHE_SIZE - 1);
191                 write_extent_buffer(leaf, kaddr + offset, ptr, size);
192                 kunmap_atomic(kaddr);
193                 page_cache_release(page);
194         }
195         btrfs_mark_buffer_dirty(leaf);
196         btrfs_free_path(path);
197
198         /*
199          * we're an inline extent, so nobody can
200          * extend the file past i_size without locking
201          * a page we already have locked.
202          *
203          * We must do any isize and inode updates
204          * before we unlock the pages.  Otherwise we
205          * could end up racing with unlink.
206          */
207         BTRFS_I(inode)->disk_i_size = inode->i_size;
208         ret = btrfs_update_inode(trans, root, inode);
209
210         return ret;
211 fail:
212         btrfs_free_path(path);
213         return err;
214 }
215
216
217 /*
218  * conditionally insert an inline extent into the file.  This
219  * does the checks required to make sure the data is small enough
220  * to fit as an inline extent.
221  */
222 static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
223                                  struct btrfs_root *root,
224                                  struct inode *inode, u64 start, u64 end,
225                                  size_t compressed_size, int compress_type,
226                                  struct page **compressed_pages)
227 {
228         u64 isize = i_size_read(inode);
229         u64 actual_end = min(end + 1, isize);
230         u64 inline_len = actual_end - start;
231         u64 aligned_end = (end + root->sectorsize - 1) &
232                         ~((u64)root->sectorsize - 1);
233         u64 hint_byte;
234         u64 data_len = inline_len;
235         int ret;
236
237         if (compressed_size)
238                 data_len = compressed_size;
239
240         if (start > 0 ||
241             actual_end >= PAGE_CACHE_SIZE ||
242             data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
243             (!compressed_size &&
244             (actual_end & (root->sectorsize - 1)) == 0) ||
245             end + 1 < isize ||
246             data_len > root->fs_info->max_inline) {
247                 return 1;
248         }
249
250         ret = btrfs_drop_extents(trans, inode, start, aligned_end,
251                                  &hint_byte, 1);
252         if (ret)
253                 return ret;
254
255         if (isize > actual_end)
256                 inline_len = min_t(u64, isize, actual_end);
257         ret = insert_inline_extent(trans, root, inode, start,
258                                    inline_len, compressed_size,
259                                    compress_type, compressed_pages);
260         if (ret) {
261                 btrfs_abort_transaction(trans, root, ret);
262                 return ret;
263         }
264         btrfs_delalloc_release_metadata(inode, end + 1 - start);
265         btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
266         return 0;
267 }
268
269 struct async_extent {
270         u64 start;
271         u64 ram_size;
272         u64 compressed_size;
273         struct page **pages;
274         unsigned long nr_pages;
275         int compress_type;
276         struct list_head list;
277 };
278
279 struct async_cow {
280         struct inode *inode;
281         struct btrfs_root *root;
282         struct page *locked_page;
283         u64 start;
284         u64 end;
285         struct list_head extents;
286         struct btrfs_work work;
287 };
288
289 static noinline int add_async_extent(struct async_cow *cow,
290                                      u64 start, u64 ram_size,
291                                      u64 compressed_size,
292                                      struct page **pages,
293                                      unsigned long nr_pages,
294                                      int compress_type)
295 {
296         struct async_extent *async_extent;
297
298         async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
299         BUG_ON(!async_extent); /* -ENOMEM */
300         async_extent->start = start;
301         async_extent->ram_size = ram_size;
302         async_extent->compressed_size = compressed_size;
303         async_extent->pages = pages;
304         async_extent->nr_pages = nr_pages;
305         async_extent->compress_type = compress_type;
306         list_add_tail(&async_extent->list, &cow->extents);
307         return 0;
308 }
309
310 /*
311  * we create compressed extents in two phases.  The first
312  * phase compresses a range of pages that have already been
313  * locked (both pages and state bits are locked).
314  *
315  * This is done inside an ordered work queue, and the compression
316  * is spread across many cpus.  The actual IO submission is step
317  * two, and the ordered work queue takes care of making sure that
318  * happens in the same order things were put onto the queue by
319  * writepages and friends.
320  *
321  * If this code finds it can't get good compression, it puts an
322  * entry onto the work queue to write the uncompressed bytes.  This
323  * makes sure that both compressed inodes and uncompressed inodes
324  * are written in the same order that pdflush sent them down.
325  */
326 static noinline int compress_file_range(struct inode *inode,
327                                         struct page *locked_page,
328                                         u64 start, u64 end,
329                                         struct async_cow *async_cow,
330                                         int *num_added)
331 {
332         struct btrfs_root *root = BTRFS_I(inode)->root;
333         struct btrfs_trans_handle *trans;
334         u64 num_bytes;
335         u64 blocksize = root->sectorsize;
336         u64 actual_end;
337         u64 isize = i_size_read(inode);
338         int ret = 0;
339         struct page **pages = NULL;
340         unsigned long nr_pages;
341         unsigned long nr_pages_ret = 0;
342         unsigned long total_compressed = 0;
343         unsigned long total_in = 0;
344         unsigned long max_compressed = 128 * 1024;
345         unsigned long max_uncompressed = 128 * 1024;
346         int i;
347         int will_compress;
348         int compress_type = root->fs_info->compress_type;
349
350         /* if this is a small write inside eof, kick off a defrag */
351         if ((end - start + 1) < 16 * 1024 &&
352             (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
353                 btrfs_add_inode_defrag(NULL, inode);
354
355         actual_end = min_t(u64, isize, end + 1);
356 again:
357         will_compress = 0;
358         nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
359         nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
360
361         /*
362          * we don't want to send crud past the end of i_size through
363          * compression, that's just a waste of CPU time.  So, if the
364          * end of the file is before the start of our current
365          * requested range of bytes, we bail out to the uncompressed
366          * cleanup code that can deal with all of this.
367          *
368          * It isn't really the fastest way to fix things, but this is a
369          * very uncommon corner.
370          */
371         if (actual_end <= start)
372                 goto cleanup_and_bail_uncompressed;
373
374         total_compressed = actual_end - start;
375
376         /* we want to make sure that amount of ram required to uncompress
377          * an extent is reasonable, so we limit the total size in ram
378          * of a compressed extent to 128k.  This is a crucial number
379          * because it also controls how easily we can spread reads across
380          * cpus for decompression.
381          *
382          * We also want to make sure the amount of IO required to do
383          * a random read is reasonably small, so we limit the size of
384          * a compressed extent to 128k.
385          */
386         total_compressed = min(total_compressed, max_uncompressed);
387         num_bytes = (end - start + blocksize) & ~(blocksize - 1);
388         num_bytes = max(blocksize,  num_bytes);
389         total_in = 0;
390         ret = 0;
391
392         /*
393          * we do compression for mount -o compress and when the
394          * inode has not been flagged as nocompress.  This flag can
395          * change at any time if we discover bad compression ratios.
396          */
397         if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
398             (btrfs_test_opt(root, COMPRESS) ||
399              (BTRFS_I(inode)->force_compress) ||
400              (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
401                 WARN_ON(pages);
402                 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
403                 if (!pages) {
404                         /* just bail out to the uncompressed code */
405                         goto cont;
406                 }
407
408                 if (BTRFS_I(inode)->force_compress)
409                         compress_type = BTRFS_I(inode)->force_compress;
410
411                 ret = btrfs_compress_pages(compress_type,
412                                            inode->i_mapping, start,
413                                            total_compressed, pages,
414                                            nr_pages, &nr_pages_ret,
415                                            &total_in,
416                                            &total_compressed,
417                                            max_compressed);
418
419                 if (!ret) {
420                         unsigned long offset = total_compressed &
421                                 (PAGE_CACHE_SIZE - 1);
422                         struct page *page = pages[nr_pages_ret - 1];
423                         char *kaddr;
424
425                         /* zero the tail end of the last page, we might be
426                          * sending it down to disk
427                          */
428                         if (offset) {
429                                 kaddr = kmap_atomic(page);
430                                 memset(kaddr + offset, 0,
431                                        PAGE_CACHE_SIZE - offset);
432                                 kunmap_atomic(kaddr);
433                         }
434                         will_compress = 1;
435                 }
436         }
437 cont:
438         if (start == 0) {
439                 trans = btrfs_join_transaction(root);
440                 if (IS_ERR(trans)) {
441                         ret = PTR_ERR(trans);
442                         trans = NULL;
443                         goto cleanup_and_out;
444                 }
445                 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
446
447                 /* lets try to make an inline extent */
448                 if (ret || total_in < (actual_end - start)) {
449                         /* we didn't compress the entire range, try
450                          * to make an uncompressed inline extent.
451                          */
452                         ret = cow_file_range_inline(trans, root, inode,
453                                                     start, end, 0, 0, NULL);
454                 } else {
455                         /* try making a compressed inline extent */
456                         ret = cow_file_range_inline(trans, root, inode,
457                                                     start, end,
458                                                     total_compressed,
459                                                     compress_type, pages);
460                 }
461                 if (ret <= 0) {
462                         /*
463                          * inline extent creation worked or returned error,
464                          * we don't need to create any more async work items.
465                          * Unlock and free up our temp pages.
466                          */
467                         extent_clear_unlock_delalloc(inode,
468                              &BTRFS_I(inode)->io_tree,
469                              start, end, NULL,
470                              EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
471                              EXTENT_CLEAR_DELALLOC |
472                              EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK);
473
474                         btrfs_end_transaction(trans, root);
475                         goto free_pages_out;
476                 }
477                 btrfs_end_transaction(trans, root);
478         }
479
480         if (will_compress) {
481                 /*
482                  * we aren't doing an inline extent round the compressed size
483                  * up to a block size boundary so the allocator does sane
484                  * things
485                  */
486                 total_compressed = (total_compressed + blocksize - 1) &
487                         ~(blocksize - 1);
488
489                 /*
490                  * one last check to make sure the compression is really a
491                  * win, compare the page count read with the blocks on disk
492                  */
493                 total_in = (total_in + PAGE_CACHE_SIZE - 1) &
494                         ~(PAGE_CACHE_SIZE - 1);
495                 if (total_compressed >= total_in) {
496                         will_compress = 0;
497                 } else {
498                         num_bytes = total_in;
499                 }
500         }
501         if (!will_compress && pages) {
502                 /*
503                  * the compression code ran but failed to make things smaller,
504                  * free any pages it allocated and our page pointer array
505                  */
506                 for (i = 0; i < nr_pages_ret; i++) {
507                         WARN_ON(pages[i]->mapping);
508                         page_cache_release(pages[i]);
509                 }
510                 kfree(pages);
511                 pages = NULL;
512                 total_compressed = 0;
513                 nr_pages_ret = 0;
514
515                 /* flag the file so we don't compress in the future */
516                 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
517                     !(BTRFS_I(inode)->force_compress)) {
518                         BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
519                 }
520         }
521         if (will_compress) {
522                 *num_added += 1;
523
524                 /* the async work queues will take care of doing actual
525                  * allocation on disk for these compressed pages,
526                  * and will submit them to the elevator.
527                  */
528                 add_async_extent(async_cow, start, num_bytes,
529                                  total_compressed, pages, nr_pages_ret,
530                                  compress_type);
531
532                 if (start + num_bytes < end) {
533                         start += num_bytes;
534                         pages = NULL;
535                         cond_resched();
536                         goto again;
537                 }
538         } else {
539 cleanup_and_bail_uncompressed:
540                 /*
541                  * No compression, but we still need to write the pages in
542                  * the file we've been given so far.  redirty the locked
543                  * page if it corresponds to our extent and set things up
544                  * for the async work queue to run cow_file_range to do
545                  * the normal delalloc dance
546                  */
547                 if (page_offset(locked_page) >= start &&
548                     page_offset(locked_page) <= end) {
549                         __set_page_dirty_nobuffers(locked_page);
550                         /* unlocked later on in the async handlers */
551                 }
552                 add_async_extent(async_cow, start, end - start + 1,
553                                  0, NULL, 0, BTRFS_COMPRESS_NONE);
554                 *num_added += 1;
555         }
556
557 out:
558         return ret;
559
560 free_pages_out:
561         for (i = 0; i < nr_pages_ret; i++) {
562                 WARN_ON(pages[i]->mapping);
563                 page_cache_release(pages[i]);
564         }
565         kfree(pages);
566
567         goto out;
568
569 cleanup_and_out:
570         extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
571                                      start, end, NULL,
572                                      EXTENT_CLEAR_UNLOCK_PAGE |
573                                      EXTENT_CLEAR_DIRTY |
574                                      EXTENT_CLEAR_DELALLOC |
575                                      EXTENT_SET_WRITEBACK |
576                                      EXTENT_END_WRITEBACK);
577         if (!trans || IS_ERR(trans))
578                 btrfs_error(root->fs_info, ret, "Failed to join transaction");
579         else
580                 btrfs_abort_transaction(trans, root, ret);
581         goto free_pages_out;
582 }
583
584 /*
585  * phase two of compressed writeback.  This is the ordered portion
586  * of the code, which only gets called in the order the work was
587  * queued.  We walk all the async extents created by compress_file_range
588  * and send them down to the disk.
589  */
590 static noinline int submit_compressed_extents(struct inode *inode,
591                                               struct async_cow *async_cow)
592 {
593         struct async_extent *async_extent;
594         u64 alloc_hint = 0;
595         struct btrfs_trans_handle *trans;
596         struct btrfs_key ins;
597         struct extent_map *em;
598         struct btrfs_root *root = BTRFS_I(inode)->root;
599         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
600         struct extent_io_tree *io_tree;
601         int ret = 0;
602
603         if (list_empty(&async_cow->extents))
604                 return 0;
605
606
607         while (!list_empty(&async_cow->extents)) {
608                 async_extent = list_entry(async_cow->extents.next,
609                                           struct async_extent, list);
610                 list_del(&async_extent->list);
611
612                 io_tree = &BTRFS_I(inode)->io_tree;
613
614 retry:
615                 /* did the compression code fall back to uncompressed IO? */
616                 if (!async_extent->pages) {
617                         int page_started = 0;
618                         unsigned long nr_written = 0;
619
620                         lock_extent(io_tree, async_extent->start,
621                                          async_extent->start +
622                                          async_extent->ram_size - 1);
623
624                         /* allocate blocks */
625                         ret = cow_file_range(inode, async_cow->locked_page,
626                                              async_extent->start,
627                                              async_extent->start +
628                                              async_extent->ram_size - 1,
629                                              &page_started, &nr_written, 0);
630
631                         /* JDM XXX */
632
633                         /*
634                          * if page_started, cow_file_range inserted an
635                          * inline extent and took care of all the unlocking
636                          * and IO for us.  Otherwise, we need to submit
637                          * all those pages down to the drive.
638                          */
639                         if (!page_started && !ret)
640                                 extent_write_locked_range(io_tree,
641                                                   inode, async_extent->start,
642                                                   async_extent->start +
643                                                   async_extent->ram_size - 1,
644                                                   btrfs_get_extent,
645                                                   WB_SYNC_ALL);
646                         kfree(async_extent);
647                         cond_resched();
648                         continue;
649                 }
650
651                 lock_extent(io_tree, async_extent->start,
652                             async_extent->start + async_extent->ram_size - 1);
653
654                 trans = btrfs_join_transaction(root);
655                 if (IS_ERR(trans)) {
656                         ret = PTR_ERR(trans);
657                 } else {
658                         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
659                         ret = btrfs_reserve_extent(trans, root,
660                                            async_extent->compressed_size,
661                                            async_extent->compressed_size,
662                                            0, alloc_hint, &ins, 1);
663                         if (ret)
664                                 btrfs_abort_transaction(trans, root, ret);
665                         btrfs_end_transaction(trans, root);
666                 }
667
668                 if (ret) {
669                         int i;
670                         for (i = 0; i < async_extent->nr_pages; i++) {
671                                 WARN_ON(async_extent->pages[i]->mapping);
672                                 page_cache_release(async_extent->pages[i]);
673                         }
674                         kfree(async_extent->pages);
675                         async_extent->nr_pages = 0;
676                         async_extent->pages = NULL;
677                         unlock_extent(io_tree, async_extent->start,
678                                       async_extent->start +
679                                       async_extent->ram_size - 1);
680                         if (ret == -ENOSPC)
681                                 goto retry;
682                         goto out_free; /* JDM: Requeue? */
683                 }
684
685                 /*
686                  * here we're doing allocation and writeback of the
687                  * compressed pages
688                  */
689                 btrfs_drop_extent_cache(inode, async_extent->start,
690                                         async_extent->start +
691                                         async_extent->ram_size - 1, 0);
692
693                 em = alloc_extent_map();
694                 BUG_ON(!em); /* -ENOMEM */
695                 em->start = async_extent->start;
696                 em->len = async_extent->ram_size;
697                 em->orig_start = em->start;
698
699                 em->block_start = ins.objectid;
700                 em->block_len = ins.offset;
701                 em->bdev = root->fs_info->fs_devices->latest_bdev;
702                 em->compress_type = async_extent->compress_type;
703                 set_bit(EXTENT_FLAG_PINNED, &em->flags);
704                 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
705
706                 while (1) {
707                         write_lock(&em_tree->lock);
708                         ret = add_extent_mapping(em_tree, em);
709                         write_unlock(&em_tree->lock);
710                         if (ret != -EEXIST) {
711                                 free_extent_map(em);
712                                 break;
713                         }
714                         btrfs_drop_extent_cache(inode, async_extent->start,
715                                                 async_extent->start +
716                                                 async_extent->ram_size - 1, 0);
717                 }
718
719                 ret = btrfs_add_ordered_extent_compress(inode,
720                                                 async_extent->start,
721                                                 ins.objectid,
722                                                 async_extent->ram_size,
723                                                 ins.offset,
724                                                 BTRFS_ORDERED_COMPRESSED,
725                                                 async_extent->compress_type);
726                 BUG_ON(ret); /* -ENOMEM */
727
728                 /*
729                  * clear dirty, set writeback and unlock the pages.
730                  */
731                 extent_clear_unlock_delalloc(inode,
732                                 &BTRFS_I(inode)->io_tree,
733                                 async_extent->start,
734                                 async_extent->start +
735                                 async_extent->ram_size - 1,
736                                 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
737                                 EXTENT_CLEAR_UNLOCK |
738                                 EXTENT_CLEAR_DELALLOC |
739                                 EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
740
741                 ret = btrfs_submit_compressed_write(inode,
742                                     async_extent->start,
743                                     async_extent->ram_size,
744                                     ins.objectid,
745                                     ins.offset, async_extent->pages,
746                                     async_extent->nr_pages);
747
748                 BUG_ON(ret); /* -ENOMEM */
749                 alloc_hint = ins.objectid + ins.offset;
750                 kfree(async_extent);
751                 cond_resched();
752         }
753         ret = 0;
754 out:
755         return ret;
756 out_free:
757         kfree(async_extent);
758         goto out;
759 }
760
761 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
762                                       u64 num_bytes)
763 {
764         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
765         struct extent_map *em;
766         u64 alloc_hint = 0;
767
768         read_lock(&em_tree->lock);
769         em = search_extent_mapping(em_tree, start, num_bytes);
770         if (em) {
771                 /*
772                  * if block start isn't an actual block number then find the
773                  * first block in this inode and use that as a hint.  If that
774                  * block is also bogus then just don't worry about it.
775                  */
776                 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
777                         free_extent_map(em);
778                         em = search_extent_mapping(em_tree, 0, 0);
779                         if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
780                                 alloc_hint = em->block_start;
781                         if (em)
782                                 free_extent_map(em);
783                 } else {
784                         alloc_hint = em->block_start;
785                         free_extent_map(em);
786                 }
787         }
788         read_unlock(&em_tree->lock);
789
790         return alloc_hint;
791 }
792
793 /*
794  * when extent_io.c finds a delayed allocation range in the file,
795  * the call backs end up in this code.  The basic idea is to
796  * allocate extents on disk for the range, and create ordered data structs
797  * in ram to track those extents.
798  *
799  * locked_page is the page that writepage had locked already.  We use
800  * it to make sure we don't do extra locks or unlocks.
801  *
802  * *page_started is set to one if we unlock locked_page and do everything
803  * required to start IO on it.  It may be clean and already done with
804  * IO when we return.
805  */
806 static noinline int cow_file_range(struct inode *inode,
807                                    struct page *locked_page,
808                                    u64 start, u64 end, int *page_started,
809                                    unsigned long *nr_written,
810                                    int unlock)
811 {
812         struct btrfs_root *root = BTRFS_I(inode)->root;
813         struct btrfs_trans_handle *trans;
814         u64 alloc_hint = 0;
815         u64 num_bytes;
816         unsigned long ram_size;
817         u64 disk_num_bytes;
818         u64 cur_alloc_size;
819         u64 blocksize = root->sectorsize;
820         struct btrfs_key ins;
821         struct extent_map *em;
822         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
823         int ret = 0;
824
825         BUG_ON(btrfs_is_free_space_inode(root, inode));
826         trans = btrfs_join_transaction(root);
827         if (IS_ERR(trans)) {
828                 extent_clear_unlock_delalloc(inode,
829                              &BTRFS_I(inode)->io_tree,
830                              start, end, NULL,
831                              EXTENT_CLEAR_UNLOCK_PAGE |
832                              EXTENT_CLEAR_UNLOCK |
833                              EXTENT_CLEAR_DELALLOC |
834                              EXTENT_CLEAR_DIRTY |
835                              EXTENT_SET_WRITEBACK |
836                              EXTENT_END_WRITEBACK);
837                 return PTR_ERR(trans);
838         }
839         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
840
841         num_bytes = (end - start + blocksize) & ~(blocksize - 1);
842         num_bytes = max(blocksize,  num_bytes);
843         disk_num_bytes = num_bytes;
844         ret = 0;
845
846         /* if this is a small write inside eof, kick off defrag */
847         if (num_bytes < 64 * 1024 &&
848             (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
849                 btrfs_add_inode_defrag(trans, inode);
850
851         if (start == 0) {
852                 /* lets try to make an inline extent */
853                 ret = cow_file_range_inline(trans, root, inode,
854                                             start, end, 0, 0, NULL);
855                 if (ret == 0) {
856                         extent_clear_unlock_delalloc(inode,
857                                      &BTRFS_I(inode)->io_tree,
858                                      start, end, NULL,
859                                      EXTENT_CLEAR_UNLOCK_PAGE |
860                                      EXTENT_CLEAR_UNLOCK |
861                                      EXTENT_CLEAR_DELALLOC |
862                                      EXTENT_CLEAR_DIRTY |
863                                      EXTENT_SET_WRITEBACK |
864                                      EXTENT_END_WRITEBACK);
865
866                         *nr_written = *nr_written +
867                              (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
868                         *page_started = 1;
869                         goto out;
870                 } else if (ret < 0) {
871                         btrfs_abort_transaction(trans, root, ret);
872                         goto out_unlock;
873                 }
874         }
875
876         BUG_ON(disk_num_bytes >
877                btrfs_super_total_bytes(root->fs_info->super_copy));
878
879         alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
880         btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
881
882         while (disk_num_bytes > 0) {
883                 unsigned long op;
884
885                 cur_alloc_size = disk_num_bytes;
886                 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
887                                            root->sectorsize, 0, alloc_hint,
888                                            &ins, 1);
889                 if (ret < 0) {
890                         btrfs_abort_transaction(trans, root, ret);
891                         goto out_unlock;
892                 }
893
894                 em = alloc_extent_map();
895                 BUG_ON(!em); /* -ENOMEM */
896                 em->start = start;
897                 em->orig_start = em->start;
898                 ram_size = ins.offset;
899                 em->len = ins.offset;
900
901                 em->block_start = ins.objectid;
902                 em->block_len = ins.offset;
903                 em->bdev = root->fs_info->fs_devices->latest_bdev;
904                 set_bit(EXTENT_FLAG_PINNED, &em->flags);
905
906                 while (1) {
907                         write_lock(&em_tree->lock);
908                         ret = add_extent_mapping(em_tree, em);
909                         write_unlock(&em_tree->lock);
910                         if (ret != -EEXIST) {
911                                 free_extent_map(em);
912                                 break;
913                         }
914                         btrfs_drop_extent_cache(inode, start,
915                                                 start + ram_size - 1, 0);
916                 }
917
918                 cur_alloc_size = ins.offset;
919                 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
920                                                ram_size, cur_alloc_size, 0);
921                 BUG_ON(ret); /* -ENOMEM */
922
923                 if (root->root_key.objectid ==
924                     BTRFS_DATA_RELOC_TREE_OBJECTID) {
925                         ret = btrfs_reloc_clone_csums(inode, start,
926                                                       cur_alloc_size);
927                         if (ret) {
928                                 btrfs_abort_transaction(trans, root, ret);
929                                 goto out_unlock;
930                         }
931                 }
932
933                 if (disk_num_bytes < cur_alloc_size)
934                         break;
935
936                 /* we're not doing compressed IO, don't unlock the first
937                  * page (which the caller expects to stay locked), don't
938                  * clear any dirty bits and don't set any writeback bits
939                  *
940                  * Do set the Private2 bit so we know this page was properly
941                  * setup for writepage
942                  */
943                 op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0;
944                 op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
945                         EXTENT_SET_PRIVATE2;
946
947                 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
948                                              start, start + ram_size - 1,
949                                              locked_page, op);
950                 disk_num_bytes -= cur_alloc_size;
951                 num_bytes -= cur_alloc_size;
952                 alloc_hint = ins.objectid + ins.offset;
953                 start += cur_alloc_size;
954         }
955         ret = 0;
956 out:
957         btrfs_end_transaction(trans, root);
958
959         return ret;
960 out_unlock:
961         extent_clear_unlock_delalloc(inode,
962                      &BTRFS_I(inode)->io_tree,
963                      start, end, NULL,
964                      EXTENT_CLEAR_UNLOCK_PAGE |
965                      EXTENT_CLEAR_UNLOCK |
966                      EXTENT_CLEAR_DELALLOC |
967                      EXTENT_CLEAR_DIRTY |
968                      EXTENT_SET_WRITEBACK |
969                      EXTENT_END_WRITEBACK);
970
971         goto out;
972 }
973
974 /*
975  * work queue call back to started compression on a file and pages
976  */
977 static noinline void async_cow_start(struct btrfs_work *work)
978 {
979         struct async_cow *async_cow;
980         int num_added = 0;
981         async_cow = container_of(work, struct async_cow, work);
982
983         compress_file_range(async_cow->inode, async_cow->locked_page,
984                             async_cow->start, async_cow->end, async_cow,
985                             &num_added);
986         if (num_added == 0)
987                 async_cow->inode = NULL;
988 }
989
990 /*
991  * work queue call back to submit previously compressed pages
992  */
993 static noinline void async_cow_submit(struct btrfs_work *work)
994 {
995         struct async_cow *async_cow;
996         struct btrfs_root *root;
997         unsigned long nr_pages;
998
999         async_cow = container_of(work, struct async_cow, work);
1000
1001         root = async_cow->root;
1002         nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1003                 PAGE_CACHE_SHIFT;
1004
1005         atomic_sub(nr_pages, &root->fs_info->async_delalloc_pages);
1006
1007         if (atomic_read(&root->fs_info->async_delalloc_pages) <
1008             5 * 1042 * 1024 &&
1009             waitqueue_active(&root->fs_info->async_submit_wait))
1010                 wake_up(&root->fs_info->async_submit_wait);
1011
1012         if (async_cow->inode)
1013                 submit_compressed_extents(async_cow->inode, async_cow);
1014 }
1015
1016 static noinline void async_cow_free(struct btrfs_work *work)
1017 {
1018         struct async_cow *async_cow;
1019         async_cow = container_of(work, struct async_cow, work);
1020         kfree(async_cow);
1021 }
1022
1023 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1024                                 u64 start, u64 end, int *page_started,
1025                                 unsigned long *nr_written)
1026 {
1027         struct async_cow *async_cow;
1028         struct btrfs_root *root = BTRFS_I(inode)->root;
1029         unsigned long nr_pages;
1030         u64 cur_end;
1031         int limit = 10 * 1024 * 1042;
1032
1033         clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1034                          1, 0, NULL, GFP_NOFS);
1035         while (start < end) {
1036                 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1037                 BUG_ON(!async_cow); /* -ENOMEM */
1038                 async_cow->inode = inode;
1039                 async_cow->root = root;
1040                 async_cow->locked_page = locked_page;
1041                 async_cow->start = start;
1042
1043                 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
1044                         cur_end = end;
1045                 else
1046                         cur_end = min(end, start + 512 * 1024 - 1);
1047
1048                 async_cow->end = cur_end;
1049                 INIT_LIST_HEAD(&async_cow->extents);
1050
1051                 async_cow->work.func = async_cow_start;
1052                 async_cow->work.ordered_func = async_cow_submit;
1053                 async_cow->work.ordered_free = async_cow_free;
1054                 async_cow->work.flags = 0;
1055
1056                 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1057                         PAGE_CACHE_SHIFT;
1058                 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1059
1060                 btrfs_queue_worker(&root->fs_info->delalloc_workers,
1061                                    &async_cow->work);
1062
1063                 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1064                         wait_event(root->fs_info->async_submit_wait,
1065                            (atomic_read(&root->fs_info->async_delalloc_pages) <
1066                             limit));
1067                 }
1068
1069                 while (atomic_read(&root->fs_info->async_submit_draining) &&
1070                       atomic_read(&root->fs_info->async_delalloc_pages)) {
1071                         wait_event(root->fs_info->async_submit_wait,
1072                           (atomic_read(&root->fs_info->async_delalloc_pages) ==
1073                            0));
1074                 }
1075
1076                 *nr_written += nr_pages;
1077                 start = cur_end + 1;
1078         }
1079         *page_started = 1;
1080         return 0;
1081 }
1082
1083 static noinline int csum_exist_in_range(struct btrfs_root *root,
1084                                         u64 bytenr, u64 num_bytes)
1085 {
1086         int ret;
1087         struct btrfs_ordered_sum *sums;
1088         LIST_HEAD(list);
1089
1090         ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1091                                        bytenr + num_bytes - 1, &list, 0);
1092         if (ret == 0 && list_empty(&list))
1093                 return 0;
1094
1095         while (!list_empty(&list)) {
1096                 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1097                 list_del(&sums->list);
1098                 kfree(sums);
1099         }
1100         return 1;
1101 }
1102
1103 /*
1104  * when nowcow writeback call back.  This checks for snapshots or COW copies
1105  * of the extents that exist in the file, and COWs the file as required.
1106  *
1107  * If no cow copies or snapshots exist, we write directly to the existing
1108  * blocks on disk
1109  */
1110 static noinline int run_delalloc_nocow(struct inode *inode,
1111                                        struct page *locked_page,
1112                               u64 start, u64 end, int *page_started, int force,
1113                               unsigned long *nr_written)
1114 {
1115         struct btrfs_root *root = BTRFS_I(inode)->root;
1116         struct btrfs_trans_handle *trans;
1117         struct extent_buffer *leaf;
1118         struct btrfs_path *path;
1119         struct btrfs_file_extent_item *fi;
1120         struct btrfs_key found_key;
1121         u64 cow_start;
1122         u64 cur_offset;
1123         u64 extent_end;
1124         u64 extent_offset;
1125         u64 disk_bytenr;
1126         u64 num_bytes;
1127         int extent_type;
1128         int ret, err;
1129         int type;
1130         int nocow;
1131         int check_prev = 1;
1132         bool nolock;
1133         u64 ino = btrfs_ino(inode);
1134
1135         path = btrfs_alloc_path();
1136         if (!path)
1137                 return -ENOMEM;
1138
1139         nolock = btrfs_is_free_space_inode(root, inode);
1140
1141         if (nolock)
1142                 trans = btrfs_join_transaction_nolock(root);
1143         else
1144                 trans = btrfs_join_transaction(root);
1145
1146         if (IS_ERR(trans)) {
1147                 btrfs_free_path(path);
1148                 return PTR_ERR(trans);
1149         }
1150
1151         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1152
1153         cow_start = (u64)-1;
1154         cur_offset = start;
1155         while (1) {
1156                 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1157                                                cur_offset, 0);
1158                 if (ret < 0) {
1159                         btrfs_abort_transaction(trans, root, ret);
1160                         goto error;
1161                 }
1162                 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1163                         leaf = path->nodes[0];
1164                         btrfs_item_key_to_cpu(leaf, &found_key,
1165                                               path->slots[0] - 1);
1166                         if (found_key.objectid == ino &&
1167                             found_key.type == BTRFS_EXTENT_DATA_KEY)
1168                                 path->slots[0]--;
1169                 }
1170                 check_prev = 0;
1171 next_slot:
1172                 leaf = path->nodes[0];
1173                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1174                         ret = btrfs_next_leaf(root, path);
1175                         if (ret < 0) {
1176                                 btrfs_abort_transaction(trans, root, ret);
1177                                 goto error;
1178                         }
1179                         if (ret > 0)
1180                                 break;
1181                         leaf = path->nodes[0];
1182                 }
1183
1184                 nocow = 0;
1185                 disk_bytenr = 0;
1186                 num_bytes = 0;
1187                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1188
1189                 if (found_key.objectid > ino ||
1190                     found_key.type > BTRFS_EXTENT_DATA_KEY ||
1191                     found_key.offset > end)
1192                         break;
1193
1194                 if (found_key.offset > cur_offset) {
1195                         extent_end = found_key.offset;
1196                         extent_type = 0;
1197                         goto out_check;
1198                 }
1199
1200                 fi = btrfs_item_ptr(leaf, path->slots[0],
1201                                     struct btrfs_file_extent_item);
1202                 extent_type = btrfs_file_extent_type(leaf, fi);
1203
1204                 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1205                     extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1206                         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1207                         extent_offset = btrfs_file_extent_offset(leaf, fi);
1208                         extent_end = found_key.offset +
1209                                 btrfs_file_extent_num_bytes(leaf, fi);
1210                         if (extent_end <= start) {
1211                                 path->slots[0]++;
1212                                 goto next_slot;
1213                         }
1214                         if (disk_bytenr == 0)
1215                                 goto out_check;
1216                         if (btrfs_file_extent_compression(leaf, fi) ||
1217                             btrfs_file_extent_encryption(leaf, fi) ||
1218                             btrfs_file_extent_other_encoding(leaf, fi))
1219                                 goto out_check;
1220                         if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1221                                 goto out_check;
1222                         if (btrfs_extent_readonly(root, disk_bytenr))
1223                                 goto out_check;
1224                         if (btrfs_cross_ref_exist(trans, root, ino,
1225                                                   found_key.offset -
1226                                                   extent_offset, disk_bytenr))
1227                                 goto out_check;
1228                         disk_bytenr += extent_offset;
1229                         disk_bytenr += cur_offset - found_key.offset;
1230                         num_bytes = min(end + 1, extent_end) - cur_offset;
1231                         /*
1232                          * force cow if csum exists in the range.
1233                          * this ensure that csum for a given extent are
1234                          * either valid or do not exist.
1235                          */
1236                         if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1237                                 goto out_check;
1238                         nocow = 1;
1239                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1240                         extent_end = found_key.offset +
1241                                 btrfs_file_extent_inline_len(leaf, fi);
1242                         extent_end = ALIGN(extent_end, root->sectorsize);
1243                 } else {
1244                         BUG_ON(1);
1245                 }
1246 out_check:
1247                 if (extent_end <= start) {
1248                         path->slots[0]++;
1249                         goto next_slot;
1250                 }
1251                 if (!nocow) {
1252                         if (cow_start == (u64)-1)
1253                                 cow_start = cur_offset;
1254                         cur_offset = extent_end;
1255                         if (cur_offset > end)
1256                                 break;
1257                         path->slots[0]++;
1258                         goto next_slot;
1259                 }
1260
1261                 btrfs_release_path(path);
1262                 if (cow_start != (u64)-1) {
1263                         ret = cow_file_range(inode, locked_page, cow_start,
1264                                         found_key.offset - 1, page_started,
1265                                         nr_written, 1);
1266                         if (ret) {
1267                                 btrfs_abort_transaction(trans, root, ret);
1268                                 goto error;
1269                         }
1270                         cow_start = (u64)-1;
1271                 }
1272
1273                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1274                         struct extent_map *em;
1275                         struct extent_map_tree *em_tree;
1276                         em_tree = &BTRFS_I(inode)->extent_tree;
1277                         em = alloc_extent_map();
1278                         BUG_ON(!em); /* -ENOMEM */
1279                         em->start = cur_offset;
1280                         em->orig_start = em->start;
1281                         em->len = num_bytes;
1282                         em->block_len = num_bytes;
1283                         em->block_start = disk_bytenr;
1284                         em->bdev = root->fs_info->fs_devices->latest_bdev;
1285                         set_bit(EXTENT_FLAG_PINNED, &em->flags);
1286                         while (1) {
1287                                 write_lock(&em_tree->lock);
1288                                 ret = add_extent_mapping(em_tree, em);
1289                                 write_unlock(&em_tree->lock);
1290                                 if (ret != -EEXIST) {
1291                                         free_extent_map(em);
1292                                         break;
1293                                 }
1294                                 btrfs_drop_extent_cache(inode, em->start,
1295                                                 em->start + em->len - 1, 0);
1296                         }
1297                         type = BTRFS_ORDERED_PREALLOC;
1298                 } else {
1299                         type = BTRFS_ORDERED_NOCOW;
1300                 }
1301
1302                 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1303                                                num_bytes, num_bytes, type);
1304                 BUG_ON(ret); /* -ENOMEM */
1305
1306                 if (root->root_key.objectid ==
1307                     BTRFS_DATA_RELOC_TREE_OBJECTID) {
1308                         ret = btrfs_reloc_clone_csums(inode, cur_offset,
1309                                                       num_bytes);
1310                         if (ret) {
1311                                 btrfs_abort_transaction(trans, root, ret);
1312                                 goto error;
1313                         }
1314                 }
1315
1316                 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
1317                                 cur_offset, cur_offset + num_bytes - 1,
1318                                 locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
1319                                 EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
1320                                 EXTENT_SET_PRIVATE2);
1321                 cur_offset = extent_end;
1322                 if (cur_offset > end)
1323                         break;
1324         }
1325         btrfs_release_path(path);
1326
1327         if (cur_offset <= end && cow_start == (u64)-1)
1328                 cow_start = cur_offset;
1329         if (cow_start != (u64)-1) {
1330                 ret = cow_file_range(inode, locked_page, cow_start, end,
1331                                      page_started, nr_written, 1);
1332                 if (ret) {
1333                         btrfs_abort_transaction(trans, root, ret);
1334                         goto error;
1335                 }
1336         }
1337
1338 error:
1339         if (nolock) {
1340                 err = btrfs_end_transaction_nolock(trans, root);
1341         } else {
1342                 err = btrfs_end_transaction(trans, root);
1343         }
1344         if (!ret)
1345                 ret = err;
1346
1347         btrfs_free_path(path);
1348         return ret;
1349 }
1350
1351 /*
1352  * extent_io.c call back to do delayed allocation processing
1353  */
1354 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1355                               u64 start, u64 end, int *page_started,
1356                               unsigned long *nr_written)
1357 {
1358         int ret;
1359         struct btrfs_root *root = BTRFS_I(inode)->root;
1360
1361         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)
1362                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1363                                          page_started, 1, nr_written);
1364         else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC)
1365                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1366                                          page_started, 0, nr_written);
1367         else if (!btrfs_test_opt(root, COMPRESS) &&
1368                  !(BTRFS_I(inode)->force_compress) &&
1369                  !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))
1370                 ret = cow_file_range(inode, locked_page, start, end,
1371                                       page_started, nr_written, 1);
1372         else
1373                 ret = cow_file_range_async(inode, locked_page, start, end,
1374                                            page_started, nr_written);
1375         return ret;
1376 }
1377
1378 static void btrfs_split_extent_hook(struct inode *inode,
1379                                     struct extent_state *orig, u64 split)
1380 {
1381         /* not delalloc, ignore it */
1382         if (!(orig->state & EXTENT_DELALLOC))
1383                 return;
1384
1385         spin_lock(&BTRFS_I(inode)->lock);
1386         BTRFS_I(inode)->outstanding_extents++;
1387         spin_unlock(&BTRFS_I(inode)->lock);
1388 }
1389
1390 /*
1391  * extent_io.c merge_extent_hook, used to track merged delayed allocation
1392  * extents so we can keep track of new extents that are just merged onto old
1393  * extents, such as when we are doing sequential writes, so we can properly
1394  * account for the metadata space we'll need.
1395  */
1396 static void btrfs_merge_extent_hook(struct inode *inode,
1397                                     struct extent_state *new,
1398                                     struct extent_state *other)
1399 {
1400         /* not delalloc, ignore it */
1401         if (!(other->state & EXTENT_DELALLOC))
1402                 return;
1403
1404         spin_lock(&BTRFS_I(inode)->lock);
1405         BTRFS_I(inode)->outstanding_extents--;
1406         spin_unlock(&BTRFS_I(inode)->lock);
1407 }
1408
1409 /*
1410  * extent_io.c set_bit_hook, used to track delayed allocation
1411  * bytes in this file, and to maintain the list of inodes that
1412  * have pending delalloc work to be done.
1413  */
1414 static void btrfs_set_bit_hook(struct inode *inode,
1415                                struct extent_state *state, int *bits)
1416 {
1417
1418         /*
1419          * set_bit and clear bit hooks normally require _irqsave/restore
1420          * but in this case, we are only testing for the DELALLOC
1421          * bit, which is only set or cleared with irqs on
1422          */
1423         if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1424                 struct btrfs_root *root = BTRFS_I(inode)->root;
1425                 u64 len = state->end + 1 - state->start;
1426                 bool do_list = !btrfs_is_free_space_inode(root, inode);
1427
1428                 if (*bits & EXTENT_FIRST_DELALLOC) {
1429                         *bits &= ~EXTENT_FIRST_DELALLOC;
1430                 } else {
1431                         spin_lock(&BTRFS_I(inode)->lock);
1432                         BTRFS_I(inode)->outstanding_extents++;
1433                         spin_unlock(&BTRFS_I(inode)->lock);
1434                 }
1435
1436                 spin_lock(&root->fs_info->delalloc_lock);
1437                 BTRFS_I(inode)->delalloc_bytes += len;
1438                 root->fs_info->delalloc_bytes += len;
1439                 if (do_list && list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1440                         list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1441                                       &root->fs_info->delalloc_inodes);
1442                 }
1443                 spin_unlock(&root->fs_info->delalloc_lock);
1444         }
1445 }
1446
1447 /*
1448  * extent_io.c clear_bit_hook, see set_bit_hook for why
1449  */
1450 static void btrfs_clear_bit_hook(struct inode *inode,
1451                                  struct extent_state *state, int *bits)
1452 {
1453         /*
1454          * set_bit and clear bit hooks normally require _irqsave/restore
1455          * but in this case, we are only testing for the DELALLOC
1456          * bit, which is only set or cleared with irqs on
1457          */
1458         if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1459                 struct btrfs_root *root = BTRFS_I(inode)->root;
1460                 u64 len = state->end + 1 - state->start;
1461                 bool do_list = !btrfs_is_free_space_inode(root, inode);
1462
1463                 if (*bits & EXTENT_FIRST_DELALLOC) {
1464                         *bits &= ~EXTENT_FIRST_DELALLOC;
1465                 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1466                         spin_lock(&BTRFS_I(inode)->lock);
1467                         BTRFS_I(inode)->outstanding_extents--;
1468                         spin_unlock(&BTRFS_I(inode)->lock);
1469                 }
1470
1471                 if (*bits & EXTENT_DO_ACCOUNTING)
1472                         btrfs_delalloc_release_metadata(inode, len);
1473
1474                 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1475                     && do_list)
1476                         btrfs_free_reserved_data_space(inode, len);
1477
1478                 spin_lock(&root->fs_info->delalloc_lock);
1479                 root->fs_info->delalloc_bytes -= len;
1480                 BTRFS_I(inode)->delalloc_bytes -= len;
1481
1482                 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1483                     !list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1484                         list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1485                 }
1486                 spin_unlock(&root->fs_info->delalloc_lock);
1487         }
1488 }
1489
1490 /*
1491  * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1492  * we don't create bios that span stripes or chunks
1493  */
1494 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1495                          size_t size, struct bio *bio,
1496                          unsigned long bio_flags)
1497 {
1498         struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1499         struct btrfs_mapping_tree *map_tree;
1500         u64 logical = (u64)bio->bi_sector << 9;
1501         u64 length = 0;
1502         u64 map_length;
1503         int ret;
1504
1505         if (bio_flags & EXTENT_BIO_COMPRESSED)
1506                 return 0;
1507
1508         length = bio->bi_size;
1509         map_tree = &root->fs_info->mapping_tree;
1510         map_length = length;
1511         ret = btrfs_map_block(map_tree, READ, logical,
1512                               &map_length, NULL, 0);
1513         /* Will always return 0 or 1 with map_multi == NULL */
1514         BUG_ON(ret < 0);
1515         if (map_length < length + size)
1516                 return 1;
1517         return 0;
1518 }
1519
1520 /*
1521  * in order to insert checksums into the metadata in large chunks,
1522  * we wait until bio submission time.   All the pages in the bio are
1523  * checksummed and sums are attached onto the ordered extent record.
1524  *
1525  * At IO completion time the cums attached on the ordered extent record
1526  * are inserted into the btree
1527  */
1528 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1529                                     struct bio *bio, int mirror_num,
1530                                     unsigned long bio_flags,
1531                                     u64 bio_offset)
1532 {
1533         struct btrfs_root *root = BTRFS_I(inode)->root;
1534         int ret = 0;
1535
1536         ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1537         BUG_ON(ret); /* -ENOMEM */
1538         return 0;
1539 }
1540
1541 /*
1542  * in order to insert checksums into the metadata in large chunks,
1543  * we wait until bio submission time.   All the pages in the bio are
1544  * checksummed and sums are attached onto the ordered extent record.
1545  *
1546  * At IO completion time the cums attached on the ordered extent record
1547  * are inserted into the btree
1548  */
1549 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1550                           int mirror_num, unsigned long bio_flags,
1551                           u64 bio_offset)
1552 {
1553         struct btrfs_root *root = BTRFS_I(inode)->root;
1554         return btrfs_map_bio(root, rw, bio, mirror_num, 1);
1555 }
1556
1557 /*
1558  * extent_io.c submission hook. This does the right thing for csum calculation
1559  * on write, or reading the csums from the tree before a read
1560  */
1561 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1562                           int mirror_num, unsigned long bio_flags,
1563                           u64 bio_offset)
1564 {
1565         struct btrfs_root *root = BTRFS_I(inode)->root;
1566         int ret = 0;
1567         int skip_sum;
1568         int metadata = 0;
1569
1570         skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1571
1572         if (btrfs_is_free_space_inode(root, inode))
1573                 metadata = 2;
1574
1575         if (!(rw & REQ_WRITE)) {
1576                 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1577                 if (ret)
1578                         return ret;
1579
1580                 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1581                         return btrfs_submit_compressed_read(inode, bio,
1582                                                     mirror_num, bio_flags);
1583                 } else if (!skip_sum) {
1584                         ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1585                         if (ret)
1586                                 return ret;
1587                 }
1588                 goto mapit;
1589         } else if (!skip_sum) {
1590                 /* csum items have already been cloned */
1591                 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1592                         goto mapit;
1593                 /* we're doing a write, do the async checksumming */
1594                 return btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1595                                    inode, rw, bio, mirror_num,
1596                                    bio_flags, bio_offset,
1597                                    __btrfs_submit_bio_start,
1598                                    __btrfs_submit_bio_done);
1599         }
1600
1601 mapit:
1602         return btrfs_map_bio(root, rw, bio, mirror_num, 0);
1603 }
1604
1605 /*
1606  * given a list of ordered sums record them in the inode.  This happens
1607  * at IO completion time based on sums calculated at bio submission time.
1608  */
1609 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1610                              struct inode *inode, u64 file_offset,
1611                              struct list_head *list)
1612 {
1613         struct btrfs_ordered_sum *sum;
1614
1615         list_for_each_entry(sum, list, list) {
1616                 btrfs_csum_file_blocks(trans,
1617                        BTRFS_I(inode)->root->fs_info->csum_root, sum);
1618         }
1619         return 0;
1620 }
1621
1622 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1623                               struct extent_state **cached_state)
1624 {
1625         if ((end & (PAGE_CACHE_SIZE - 1)) == 0)
1626                 WARN_ON(1);
1627         return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1628                                    cached_state, GFP_NOFS);
1629 }
1630
1631 /* see btrfs_writepage_start_hook for details on why this is required */
1632 struct btrfs_writepage_fixup {
1633         struct page *page;
1634         struct btrfs_work work;
1635 };
1636
1637 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1638 {
1639         struct btrfs_writepage_fixup *fixup;
1640         struct btrfs_ordered_extent *ordered;
1641         struct extent_state *cached_state = NULL;
1642         struct page *page;
1643         struct inode *inode;
1644         u64 page_start;
1645         u64 page_end;
1646         int ret;
1647
1648         fixup = container_of(work, struct btrfs_writepage_fixup, work);
1649         page = fixup->page;
1650 again:
1651         lock_page(page);
1652         if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1653                 ClearPageChecked(page);
1654                 goto out_page;
1655         }
1656
1657         inode = page->mapping->host;
1658         page_start = page_offset(page);
1659         page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1660
1661         lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1662                          &cached_state);
1663
1664         /* already ordered? We're done */
1665         if (PagePrivate2(page))
1666                 goto out;
1667
1668         ordered = btrfs_lookup_ordered_extent(inode, page_start);
1669         if (ordered) {
1670                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1671                                      page_end, &cached_state, GFP_NOFS);
1672                 unlock_page(page);
1673                 btrfs_start_ordered_extent(inode, ordered, 1);
1674                 btrfs_put_ordered_extent(ordered);
1675                 goto again;
1676         }
1677
1678         ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1679         if (ret) {
1680                 mapping_set_error(page->mapping, ret);
1681                 end_extent_writepage(page, ret, page_start, page_end);
1682                 ClearPageChecked(page);
1683                 goto out;
1684          }
1685
1686         btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1687         ClearPageChecked(page);
1688         set_page_dirty(page);
1689 out:
1690         unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1691                              &cached_state, GFP_NOFS);
1692 out_page:
1693         unlock_page(page);
1694         page_cache_release(page);
1695         kfree(fixup);
1696 }
1697
1698 /*
1699  * There are a few paths in the higher layers of the kernel that directly
1700  * set the page dirty bit without asking the filesystem if it is a
1701  * good idea.  This causes problems because we want to make sure COW
1702  * properly happens and the data=ordered rules are followed.
1703  *
1704  * In our case any range that doesn't have the ORDERED bit set
1705  * hasn't been properly setup for IO.  We kick off an async process
1706  * to fix it up.  The async helper will wait for ordered extents, set
1707  * the delalloc bit and make it safe to write the page.
1708  */
1709 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1710 {
1711         struct inode *inode = page->mapping->host;
1712         struct btrfs_writepage_fixup *fixup;
1713         struct btrfs_root *root = BTRFS_I(inode)->root;
1714
1715         /* this page is properly in the ordered list */
1716         if (TestClearPagePrivate2(page))
1717                 return 0;
1718
1719         if (PageChecked(page))
1720                 return -EAGAIN;
1721
1722         fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1723         if (!fixup)
1724                 return -EAGAIN;
1725
1726         SetPageChecked(page);
1727         page_cache_get(page);
1728         fixup->work.func = btrfs_writepage_fixup_worker;
1729         fixup->page = page;
1730         btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1731         return -EBUSY;
1732 }
1733
1734 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1735                                        struct inode *inode, u64 file_pos,
1736                                        u64 disk_bytenr, u64 disk_num_bytes,
1737                                        u64 num_bytes, u64 ram_bytes,
1738                                        u8 compression, u8 encryption,
1739                                        u16 other_encoding, int extent_type)
1740 {
1741         struct btrfs_root *root = BTRFS_I(inode)->root;
1742         struct btrfs_file_extent_item *fi;
1743         struct btrfs_path *path;
1744         struct extent_buffer *leaf;
1745         struct btrfs_key ins;
1746         u64 hint;
1747         int ret;
1748
1749         path = btrfs_alloc_path();
1750         if (!path)
1751                 return -ENOMEM;
1752
1753         path->leave_spinning = 1;
1754
1755         /*
1756          * we may be replacing one extent in the tree with another.
1757          * The new extent is pinned in the extent map, and we don't want
1758          * to drop it from the cache until it is completely in the btree.
1759          *
1760          * So, tell btrfs_drop_extents to leave this extent in the cache.
1761          * the caller is expected to unpin it and allow it to be merged
1762          * with the others.
1763          */
1764         ret = btrfs_drop_extents(trans, inode, file_pos, file_pos + num_bytes,
1765                                  &hint, 0);
1766         if (ret)
1767                 goto out;
1768
1769         ins.objectid = btrfs_ino(inode);
1770         ins.offset = file_pos;
1771         ins.type = BTRFS_EXTENT_DATA_KEY;
1772         ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1773         if (ret)
1774                 goto out;
1775         leaf = path->nodes[0];
1776         fi = btrfs_item_ptr(leaf, path->slots[0],
1777                             struct btrfs_file_extent_item);
1778         btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1779         btrfs_set_file_extent_type(leaf, fi, extent_type);
1780         btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1781         btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1782         btrfs_set_file_extent_offset(leaf, fi, 0);
1783         btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1784         btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1785         btrfs_set_file_extent_compression(leaf, fi, compression);
1786         btrfs_set_file_extent_encryption(leaf, fi, encryption);
1787         btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1788
1789         btrfs_unlock_up_safe(path, 1);
1790         btrfs_set_lock_blocking(leaf);
1791
1792         btrfs_mark_buffer_dirty(leaf);
1793
1794         inode_add_bytes(inode, num_bytes);
1795
1796         ins.objectid = disk_bytenr;
1797         ins.offset = disk_num_bytes;
1798         ins.type = BTRFS_EXTENT_ITEM_KEY;
1799         ret = btrfs_alloc_reserved_file_extent(trans, root,
1800                                         root->root_key.objectid,
1801                                         btrfs_ino(inode), file_pos, &ins);
1802 out:
1803         btrfs_free_path(path);
1804
1805         return ret;
1806 }
1807
1808 /*
1809  * helper function for btrfs_finish_ordered_io, this
1810  * just reads in some of the csum leaves to prime them into ram
1811  * before we start the transaction.  It limits the amount of btree
1812  * reads required while inside the transaction.
1813  */
1814 /* as ordered data IO finishes, this gets called so we can finish
1815  * an ordered extent if the range of bytes in the file it covers are
1816  * fully written.
1817  */
1818 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
1819 {
1820         struct inode *inode = ordered_extent->inode;
1821         struct btrfs_root *root = BTRFS_I(inode)->root;
1822         struct btrfs_trans_handle *trans = NULL;
1823         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1824         struct extent_state *cached_state = NULL;
1825         int compress_type = 0;
1826         int ret;
1827         bool nolock;
1828
1829         nolock = btrfs_is_free_space_inode(root, inode);
1830
1831         if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
1832                 ret = -EIO;
1833                 goto out;
1834         }
1835
1836         if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
1837                 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
1838                 ret = btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1839                 if (!ret) {
1840                         if (nolock)
1841                                 trans = btrfs_join_transaction_nolock(root);
1842                         else
1843                                 trans = btrfs_join_transaction(root);
1844                         if (IS_ERR(trans))
1845                                 return PTR_ERR(trans);
1846                         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1847                         ret = btrfs_update_inode_fallback(trans, root, inode);
1848                         if (ret) /* -ENOMEM or corruption */
1849                                 btrfs_abort_transaction(trans, root, ret);
1850                 }
1851                 goto out;
1852         }
1853
1854         lock_extent_bits(io_tree, ordered_extent->file_offset,
1855                          ordered_extent->file_offset + ordered_extent->len - 1,
1856                          0, &cached_state);
1857
1858         if (nolock)
1859                 trans = btrfs_join_transaction_nolock(root);
1860         else
1861                 trans = btrfs_join_transaction(root);
1862         if (IS_ERR(trans)) {
1863                 ret = PTR_ERR(trans);
1864                 trans = NULL;
1865                 goto out_unlock;
1866         }
1867         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1868
1869         if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
1870                 compress_type = ordered_extent->compress_type;
1871         if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
1872                 BUG_ON(compress_type);
1873                 ret = btrfs_mark_extent_written(trans, inode,
1874                                                 ordered_extent->file_offset,
1875                                                 ordered_extent->file_offset +
1876                                                 ordered_extent->len);
1877         } else {
1878                 BUG_ON(root == root->fs_info->tree_root);
1879                 ret = insert_reserved_file_extent(trans, inode,
1880                                                 ordered_extent->file_offset,
1881                                                 ordered_extent->start,
1882                                                 ordered_extent->disk_len,
1883                                                 ordered_extent->len,
1884                                                 ordered_extent->len,
1885                                                 compress_type, 0, 0,
1886                                                 BTRFS_FILE_EXTENT_REG);
1887                 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
1888                                    ordered_extent->file_offset,
1889                                    ordered_extent->len);
1890         }
1891
1892         if (ret < 0) {
1893                 btrfs_abort_transaction(trans, root, ret);
1894                 goto out_unlock;
1895         }
1896
1897         add_pending_csums(trans, inode, ordered_extent->file_offset,
1898                           &ordered_extent->list);
1899
1900         ret = btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1901         if (!ret || !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
1902                 ret = btrfs_update_inode_fallback(trans, root, inode);
1903                 if (ret) { /* -ENOMEM or corruption */
1904                         btrfs_abort_transaction(trans, root, ret);
1905                         goto out_unlock;
1906                 }
1907         }
1908         ret = 0;
1909 out_unlock:
1910         unlock_extent_cached(io_tree, ordered_extent->file_offset,
1911                              ordered_extent->file_offset +
1912                              ordered_extent->len - 1, &cached_state, GFP_NOFS);
1913 out:
1914         if (root != root->fs_info->tree_root)
1915                 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
1916         if (trans) {
1917                 if (nolock)
1918                         btrfs_end_transaction_nolock(trans, root);
1919                 else
1920                         btrfs_end_transaction(trans, root);
1921         }
1922
1923         if (ret)
1924                 clear_extent_uptodate(io_tree, ordered_extent->file_offset,
1925                                       ordered_extent->file_offset +
1926                                       ordered_extent->len - 1, NULL, GFP_NOFS);
1927
1928         /*
1929          * This needs to be dont to make sure anybody waiting knows we are done
1930          * upating everything for this ordered extent.
1931          */
1932         btrfs_remove_ordered_extent(inode, ordered_extent);
1933
1934         /* once for us */
1935         btrfs_put_ordered_extent(ordered_extent);
1936         /* once for the tree */
1937         btrfs_put_ordered_extent(ordered_extent);
1938
1939         return ret;
1940 }
1941
1942 static void finish_ordered_fn(struct btrfs_work *work)
1943 {
1944         struct btrfs_ordered_extent *ordered_extent;
1945         ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
1946         btrfs_finish_ordered_io(ordered_extent);
1947 }
1948
1949 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
1950                                 struct extent_state *state, int uptodate)
1951 {
1952         struct inode *inode = page->mapping->host;
1953         struct btrfs_root *root = BTRFS_I(inode)->root;
1954         struct btrfs_ordered_extent *ordered_extent = NULL;
1955         struct btrfs_workers *workers;
1956
1957         trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
1958
1959         ClearPagePrivate2(page);
1960         if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
1961                                             end - start + 1, uptodate))
1962                 return 0;
1963
1964         ordered_extent->work.func = finish_ordered_fn;
1965         ordered_extent->work.flags = 0;
1966
1967         if (btrfs_is_free_space_inode(root, inode))
1968                 workers = &root->fs_info->endio_freespace_worker;
1969         else
1970                 workers = &root->fs_info->endio_write_workers;
1971         btrfs_queue_worker(workers, &ordered_extent->work);
1972
1973         return 0;
1974 }
1975
1976 /*
1977  * when reads are done, we need to check csums to verify the data is correct
1978  * if there's a match, we allow the bio to finish.  If not, the code in
1979  * extent_io.c will try to find good copies for us.
1980  */
1981 static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
1982                                struct extent_state *state, int mirror)
1983 {
1984         size_t offset = start - ((u64)page->index << PAGE_CACHE_SHIFT);
1985         struct inode *inode = page->mapping->host;
1986         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1987         char *kaddr;
1988         u64 private = ~(u32)0;
1989         int ret;
1990         struct btrfs_root *root = BTRFS_I(inode)->root;
1991         u32 csum = ~(u32)0;
1992
1993         if (PageChecked(page)) {
1994                 ClearPageChecked(page);
1995                 goto good;
1996         }
1997
1998         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
1999                 goto good;
2000
2001         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2002             test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2003                 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2004                                   GFP_NOFS);
2005                 return 0;
2006         }
2007
2008         if (state && state->start == start) {
2009                 private = state->private;
2010                 ret = 0;
2011         } else {
2012                 ret = get_state_private(io_tree, start, &private);
2013         }
2014         kaddr = kmap_atomic(page);
2015         if (ret)
2016                 goto zeroit;
2017
2018         csum = btrfs_csum_data(root, kaddr + offset, csum,  end - start + 1);
2019         btrfs_csum_final(csum, (char *)&csum);
2020         if (csum != private)
2021                 goto zeroit;
2022
2023         kunmap_atomic(kaddr);
2024 good:
2025         return 0;
2026
2027 zeroit:
2028         printk_ratelimited(KERN_INFO "btrfs csum failed ino %llu off %llu csum %u "
2029                        "private %llu\n",
2030                        (unsigned long long)btrfs_ino(page->mapping->host),
2031                        (unsigned long long)start, csum,
2032                        (unsigned long long)private);
2033         memset(kaddr + offset, 1, end - start + 1);
2034         flush_dcache_page(page);
2035         kunmap_atomic(kaddr);
2036         if (private == 0)
2037                 return 0;
2038         return -EIO;
2039 }
2040
2041 struct delayed_iput {
2042         struct list_head list;
2043         struct inode *inode;
2044 };
2045
2046 /* JDM: If this is fs-wide, why can't we add a pointer to
2047  * btrfs_inode instead and avoid the allocation? */
2048 void btrfs_add_delayed_iput(struct inode *inode)
2049 {
2050         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2051         struct delayed_iput *delayed;
2052
2053         if (atomic_add_unless(&inode->i_count, -1, 1))
2054                 return;
2055
2056         delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2057         delayed->inode = inode;
2058
2059         spin_lock(&fs_info->delayed_iput_lock);
2060         list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2061         spin_unlock(&fs_info->delayed_iput_lock);
2062 }
2063
2064 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2065 {
2066         LIST_HEAD(list);
2067         struct btrfs_fs_info *fs_info = root->fs_info;
2068         struct delayed_iput *delayed;
2069         int empty;
2070
2071         spin_lock(&fs_info->delayed_iput_lock);
2072         empty = list_empty(&fs_info->delayed_iputs);
2073         spin_unlock(&fs_info->delayed_iput_lock);
2074         if (empty)
2075                 return;
2076
2077         down_read(&root->fs_info->cleanup_work_sem);
2078         spin_lock(&fs_info->delayed_iput_lock);
2079         list_splice_init(&fs_info->delayed_iputs, &list);
2080         spin_unlock(&fs_info->delayed_iput_lock);
2081
2082         while (!list_empty(&list)) {
2083                 delayed = list_entry(list.next, struct delayed_iput, list);
2084                 list_del(&delayed->list);
2085                 iput(delayed->inode);
2086                 kfree(delayed);
2087         }
2088         up_read(&root->fs_info->cleanup_work_sem);
2089 }
2090
2091 enum btrfs_orphan_cleanup_state {
2092         ORPHAN_CLEANUP_STARTED  = 1,
2093         ORPHAN_CLEANUP_DONE     = 2,
2094 };
2095
2096 /*
2097  * This is called in transaction commit time. If there are no orphan
2098  * files in the subvolume, it removes orphan item and frees block_rsv
2099  * structure.
2100  */
2101 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2102                               struct btrfs_root *root)
2103 {
2104         struct btrfs_block_rsv *block_rsv;
2105         int ret;
2106
2107         if (!list_empty(&root->orphan_list) ||
2108             root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2109                 return;
2110
2111         spin_lock(&root->orphan_lock);
2112         if (!list_empty(&root->orphan_list)) {
2113                 spin_unlock(&root->orphan_lock);
2114                 return;
2115         }
2116
2117         if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
2118                 spin_unlock(&root->orphan_lock);
2119                 return;
2120         }
2121
2122         block_rsv = root->orphan_block_rsv;
2123         root->orphan_block_rsv = NULL;
2124         spin_unlock(&root->orphan_lock);
2125
2126         if (root->orphan_item_inserted &&
2127             btrfs_root_refs(&root->root_item) > 0) {
2128                 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2129                                             root->root_key.objectid);
2130                 BUG_ON(ret);
2131                 root->orphan_item_inserted = 0;
2132         }
2133
2134         if (block_rsv) {
2135                 WARN_ON(block_rsv->size > 0);
2136                 btrfs_free_block_rsv(root, block_rsv);
2137         }
2138 }
2139
2140 /*
2141  * This creates an orphan entry for the given inode in case something goes
2142  * wrong in the middle of an unlink/truncate.
2143  *
2144  * NOTE: caller of this function should reserve 5 units of metadata for
2145  *       this function.
2146  */
2147 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2148 {
2149         struct btrfs_root *root = BTRFS_I(inode)->root;
2150         struct btrfs_block_rsv *block_rsv = NULL;
2151         int reserve = 0;
2152         int insert = 0;
2153         int ret;
2154
2155         if (!root->orphan_block_rsv) {
2156                 block_rsv = btrfs_alloc_block_rsv(root);
2157                 if (!block_rsv)
2158                         return -ENOMEM;
2159         }
2160
2161         spin_lock(&root->orphan_lock);
2162         if (!root->orphan_block_rsv) {
2163                 root->orphan_block_rsv = block_rsv;
2164         } else if (block_rsv) {
2165                 btrfs_free_block_rsv(root, block_rsv);
2166                 block_rsv = NULL;
2167         }
2168
2169         if (list_empty(&BTRFS_I(inode)->i_orphan)) {
2170                 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
2171 #if 0
2172                 /*
2173                  * For proper ENOSPC handling, we should do orphan
2174                  * cleanup when mounting. But this introduces backward
2175                  * compatibility issue.
2176                  */
2177                 if (!xchg(&root->orphan_item_inserted, 1))
2178                         insert = 2;
2179                 else
2180                         insert = 1;
2181 #endif
2182                 insert = 1;
2183         }
2184
2185         if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2186                               &BTRFS_I(inode)->runtime_flags))
2187                 reserve = 1;
2188         spin_unlock(&root->orphan_lock);
2189
2190         /* grab metadata reservation from transaction handle */
2191         if (reserve) {
2192                 ret = btrfs_orphan_reserve_metadata(trans, inode);
2193                 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
2194         }
2195
2196         /* insert an orphan item to track this unlinked/truncated file */
2197         if (insert >= 1) {
2198                 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
2199                 if (ret && ret != -EEXIST) {
2200                         btrfs_abort_transaction(trans, root, ret);
2201                         return ret;
2202                 }
2203                 ret = 0;
2204         }
2205
2206         /* insert an orphan item to track subvolume contains orphan files */
2207         if (insert >= 2) {
2208                 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2209                                                root->root_key.objectid);
2210                 if (ret && ret != -EEXIST) {
2211                         btrfs_abort_transaction(trans, root, ret);
2212                         return ret;
2213                 }
2214         }
2215         return 0;
2216 }
2217
2218 /*
2219  * We have done the truncate/delete so we can go ahead and remove the orphan
2220  * item for this particular inode.
2221  */
2222 int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode)
2223 {
2224         struct btrfs_root *root = BTRFS_I(inode)->root;
2225         int delete_item = 0;
2226         int release_rsv = 0;
2227         int ret = 0;
2228
2229         spin_lock(&root->orphan_lock);
2230         if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
2231                 list_del_init(&BTRFS_I(inode)->i_orphan);
2232                 delete_item = 1;
2233         }
2234
2235         if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2236                                &BTRFS_I(inode)->runtime_flags))
2237                 release_rsv = 1;
2238         spin_unlock(&root->orphan_lock);
2239
2240         if (trans && delete_item) {
2241                 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
2242                 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
2243         }
2244
2245         if (release_rsv)
2246                 btrfs_orphan_release_metadata(inode);
2247
2248         return 0;
2249 }
2250
2251 /*
2252  * this cleans up any orphans that may be left on the list from the last use
2253  * of this root.
2254  */
2255 int btrfs_orphan_cleanup(struct btrfs_root *root)
2256 {
2257         struct btrfs_path *path;
2258         struct extent_buffer *leaf;
2259         struct btrfs_key key, found_key;
2260         struct btrfs_trans_handle *trans;
2261         struct inode *inode;
2262         u64 last_objectid = 0;
2263         int ret = 0, nr_unlink = 0, nr_truncate = 0;
2264
2265         if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
2266                 return 0;
2267
2268         path = btrfs_alloc_path();
2269         if (!path) {
2270                 ret = -ENOMEM;
2271                 goto out;
2272         }
2273         path->reada = -1;
2274
2275         key.objectid = BTRFS_ORPHAN_OBJECTID;
2276         btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
2277         key.offset = (u64)-1;
2278
2279         while (1) {
2280                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2281                 if (ret < 0)
2282                         goto out;
2283
2284                 /*
2285                  * if ret == 0 means we found what we were searching for, which
2286                  * is weird, but possible, so only screw with path if we didn't
2287                  * find the key and see if we have stuff that matches
2288                  */
2289                 if (ret > 0) {
2290                         ret = 0;
2291                         if (path->slots[0] == 0)
2292                                 break;
2293                         path->slots[0]--;
2294                 }
2295
2296                 /* pull out the item */
2297                 leaf = path->nodes[0];
2298                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2299
2300                 /* make sure the item matches what we want */
2301                 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
2302                         break;
2303                 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
2304                         break;
2305
2306                 /* release the path since we're done with it */
2307                 btrfs_release_path(path);
2308
2309                 /*
2310                  * this is where we are basically btrfs_lookup, without the
2311                  * crossing root thing.  we store the inode number in the
2312                  * offset of the orphan item.
2313                  */
2314
2315                 if (found_key.offset == last_objectid) {
2316                         printk(KERN_ERR "btrfs: Error removing orphan entry, "
2317                                "stopping orphan cleanup\n");
2318                         ret = -EINVAL;
2319                         goto out;
2320                 }
2321
2322                 last_objectid = found_key.offset;
2323
2324                 found_key.objectid = found_key.offset;
2325                 found_key.type = BTRFS_INODE_ITEM_KEY;
2326                 found_key.offset = 0;
2327                 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
2328                 ret = PTR_RET(inode);
2329                 if (ret && ret != -ESTALE)
2330                         goto out;
2331
2332                 if (ret == -ESTALE && root == root->fs_info->tree_root) {
2333                         struct btrfs_root *dead_root;
2334                         struct btrfs_fs_info *fs_info = root->fs_info;
2335                         int is_dead_root = 0;
2336
2337                         /*
2338                          * this is an orphan in the tree root. Currently these
2339                          * could come from 2 sources:
2340                          *  a) a snapshot deletion in progress
2341                          *  b) a free space cache inode
2342                          * We need to distinguish those two, as the snapshot
2343                          * orphan must not get deleted.
2344                          * find_dead_roots already ran before us, so if this
2345                          * is a snapshot deletion, we should find the root
2346                          * in the dead_roots list
2347                          */
2348                         spin_lock(&fs_info->trans_lock);
2349                         list_for_each_entry(dead_root, &fs_info->dead_roots,
2350                                             root_list) {
2351                                 if (dead_root->root_key.objectid ==
2352                                     found_key.objectid) {
2353                                         is_dead_root = 1;
2354                                         break;
2355                                 }
2356                         }
2357                         spin_unlock(&fs_info->trans_lock);
2358                         if (is_dead_root) {
2359                                 /* prevent this orphan from being found again */
2360                                 key.offset = found_key.objectid - 1;
2361                                 continue;
2362                         }
2363                 }
2364                 /*
2365                  * Inode is already gone but the orphan item is still there,
2366                  * kill the orphan item.
2367                  */
2368                 if (ret == -ESTALE) {
2369                         trans = btrfs_start_transaction(root, 1);
2370                         if (IS_ERR(trans)) {
2371                                 ret = PTR_ERR(trans);
2372                                 goto out;
2373                         }
2374                         ret = btrfs_del_orphan_item(trans, root,
2375                                                     found_key.objectid);
2376                         BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
2377                         btrfs_end_transaction(trans, root);
2378                         continue;
2379                 }
2380
2381                 /*
2382                  * add this inode to the orphan list so btrfs_orphan_del does
2383                  * the proper thing when we hit it
2384                  */
2385                 spin_lock(&root->orphan_lock);
2386                 list_add(&BTRFS_I(inode)->i_orphan, &root->orphan_list);
2387                 spin_unlock(&root->orphan_lock);
2388
2389                 /* if we have links, this was a truncate, lets do that */
2390                 if (inode->i_nlink) {
2391                         if (!S_ISREG(inode->i_mode)) {
2392                                 WARN_ON(1);
2393                                 iput(inode);
2394                                 continue;
2395                         }
2396                         nr_truncate++;
2397                         ret = btrfs_truncate(inode);
2398                 } else {
2399                         nr_unlink++;
2400                 }
2401
2402                 /* this will do delete_inode and everything for us */
2403                 iput(inode);
2404                 if (ret)
2405                         goto out;
2406         }
2407         /* release the path since we're done with it */
2408         btrfs_release_path(path);
2409
2410         root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
2411
2412         if (root->orphan_block_rsv)
2413                 btrfs_block_rsv_release(root, root->orphan_block_rsv,
2414                                         (u64)-1);
2415
2416         if (root->orphan_block_rsv || root->orphan_item_inserted) {
2417                 trans = btrfs_join_transaction(root);
2418                 if (!IS_ERR(trans))
2419                         btrfs_end_transaction(trans, root);
2420         }
2421
2422         if (nr_unlink)
2423                 printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink);
2424         if (nr_truncate)
2425                 printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate);
2426
2427 out:
2428         if (ret)
2429                 printk(KERN_CRIT "btrfs: could not do orphan cleanup %d\n", ret);
2430         btrfs_free_path(path);
2431         return ret;
2432 }
2433
2434 /*
2435  * very simple check to peek ahead in the leaf looking for xattrs.  If we
2436  * don't find any xattrs, we know there can't be any acls.
2437  *
2438  * slot is the slot the inode is in, objectid is the objectid of the inode
2439  */
2440 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
2441                                           int slot, u64 objectid)
2442 {
2443         u32 nritems = btrfs_header_nritems(leaf);
2444         struct btrfs_key found_key;
2445         int scanned = 0;
2446
2447         slot++;
2448         while (slot < nritems) {
2449                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2450
2451                 /* we found a different objectid, there must not be acls */
2452                 if (found_key.objectid != objectid)
2453                         return 0;
2454
2455                 /* we found an xattr, assume we've got an acl */
2456                 if (found_key.type == BTRFS_XATTR_ITEM_KEY)
2457                         return 1;
2458
2459                 /*
2460                  * we found a key greater than an xattr key, there can't
2461                  * be any acls later on
2462                  */
2463                 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
2464                         return 0;
2465
2466                 slot++;
2467                 scanned++;
2468
2469                 /*
2470                  * it goes inode, inode backrefs, xattrs, extents,
2471                  * so if there are a ton of hard links to an inode there can
2472                  * be a lot of backrefs.  Don't waste time searching too hard,
2473                  * this is just an optimization
2474                  */
2475                 if (scanned >= 8)
2476                         break;
2477         }
2478         /* we hit the end of the leaf before we found an xattr or
2479          * something larger than an xattr.  We have to assume the inode
2480          * has acls
2481          */
2482         return 1;
2483 }
2484
2485 /*
2486  * read an inode from the btree into the in-memory inode
2487  */
2488 static void btrfs_read_locked_inode(struct inode *inode)
2489 {
2490         struct btrfs_path *path;
2491         struct extent_buffer *leaf;
2492         struct btrfs_inode_item *inode_item;
2493         struct btrfs_timespec *tspec;
2494         struct btrfs_root *root = BTRFS_I(inode)->root;
2495         struct btrfs_key location;
2496         int maybe_acls;
2497         u32 rdev;
2498         int ret;
2499         bool filled = false;
2500
2501         ret = btrfs_fill_inode(inode, &rdev);
2502         if (!ret)
2503                 filled = true;
2504
2505         path = btrfs_alloc_path();
2506         if (!path)
2507                 goto make_bad;
2508
2509         path->leave_spinning = 1;
2510         memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
2511
2512         ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
2513         if (ret)
2514                 goto make_bad;
2515
2516         leaf = path->nodes[0];
2517
2518         if (filled)
2519                 goto cache_acl;
2520
2521         inode_item = btrfs_item_ptr(leaf, path->slots[0],
2522                                     struct btrfs_inode_item);
2523         inode->i_mode = btrfs_inode_mode(leaf, inode_item);
2524         set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
2525         inode->i_uid = btrfs_inode_uid(leaf, inode_item);
2526         inode->i_gid = btrfs_inode_gid(leaf, inode_item);
2527         btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
2528
2529         tspec = btrfs_inode_atime(inode_item);
2530         inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2531         inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2532
2533         tspec = btrfs_inode_mtime(inode_item);
2534         inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2535         inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2536
2537         tspec = btrfs_inode_ctime(inode_item);
2538         inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2539         inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2540
2541         inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
2542         BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
2543         inode->i_version = btrfs_inode_sequence(leaf, inode_item);
2544         inode->i_generation = BTRFS_I(inode)->generation;
2545         inode->i_rdev = 0;
2546         rdev = btrfs_inode_rdev(leaf, inode_item);
2547
2548         BTRFS_I(inode)->index_cnt = (u64)-1;
2549         BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
2550 cache_acl:
2551         /*
2552          * try to precache a NULL acl entry for files that don't have
2553          * any xattrs or acls
2554          */
2555         maybe_acls = acls_after_inode_item(leaf, path->slots[0],
2556                                            btrfs_ino(inode));
2557         if (!maybe_acls)
2558                 cache_no_acl(inode);
2559
2560         btrfs_free_path(path);
2561
2562         switch (inode->i_mode & S_IFMT) {
2563         case S_IFREG:
2564                 inode->i_mapping->a_ops = &btrfs_aops;
2565                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2566                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
2567                 inode->i_fop = &btrfs_file_operations;
2568                 inode->i_op = &btrfs_file_inode_operations;
2569                 break;
2570         case S_IFDIR:
2571                 inode->i_fop = &btrfs_dir_file_operations;
2572                 if (root == root->fs_info->tree_root)
2573                         inode->i_op = &btrfs_dir_ro_inode_operations;
2574                 else
2575                         inode->i_op = &btrfs_dir_inode_operations;
2576                 break;
2577         case S_IFLNK:
2578                 inode->i_op = &btrfs_symlink_inode_operations;
2579                 inode->i_mapping->a_ops = &btrfs_symlink_aops;
2580                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2581                 break;
2582         default:
2583                 inode->i_op = &btrfs_special_inode_operations;
2584                 init_special_inode(inode, inode->i_mode, rdev);
2585                 break;
2586         }
2587
2588         btrfs_update_iflags(inode);
2589         return;
2590
2591 make_bad:
2592         btrfs_free_path(path);
2593         make_bad_inode(inode);
2594 }
2595
2596 /*
2597  * given a leaf and an inode, copy the inode fields into the leaf
2598  */
2599 static void fill_inode_item(struct btrfs_trans_handle *trans,
2600                             struct extent_buffer *leaf,
2601                             struct btrfs_inode_item *item,
2602                             struct inode *inode)
2603 {
2604         btrfs_set_inode_uid(leaf, item, inode->i_uid);
2605         btrfs_set_inode_gid(leaf, item, inode->i_gid);
2606         btrfs_set_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size);
2607         btrfs_set_inode_mode(leaf, item, inode->i_mode);
2608         btrfs_set_inode_nlink(leaf, item, inode->i_nlink);
2609
2610         btrfs_set_timespec_sec(leaf, btrfs_inode_atime(item),
2611                                inode->i_atime.tv_sec);
2612         btrfs_set_timespec_nsec(leaf, btrfs_inode_atime(item),
2613                                 inode->i_atime.tv_nsec);
2614
2615         btrfs_set_timespec_sec(leaf, btrfs_inode_mtime(item),
2616                                inode->i_mtime.tv_sec);
2617         btrfs_set_timespec_nsec(leaf, btrfs_inode_mtime(item),
2618                                 inode->i_mtime.tv_nsec);
2619
2620         btrfs_set_timespec_sec(leaf, btrfs_inode_ctime(item),
2621                                inode->i_ctime.tv_sec);
2622         btrfs_set_timespec_nsec(leaf, btrfs_inode_ctime(item),
2623                                 inode->i_ctime.tv_nsec);
2624
2625         btrfs_set_inode_nbytes(leaf, item, inode_get_bytes(inode));
2626         btrfs_set_inode_generation(leaf, item, BTRFS_I(inode)->generation);
2627         btrfs_set_inode_sequence(leaf, item, inode->i_version);
2628         btrfs_set_inode_transid(leaf, item, trans->transid);
2629         btrfs_set_inode_rdev(leaf, item, inode->i_rdev);
2630         btrfs_set_inode_flags(leaf, item, BTRFS_I(inode)->flags);
2631         btrfs_set_inode_block_group(leaf, item, 0);
2632 }
2633
2634 /*
2635  * copy everything in the in-memory inode into the btree.
2636  */
2637 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
2638                                 struct btrfs_root *root, struct inode *inode)
2639 {
2640         struct btrfs_inode_item *inode_item;
2641         struct btrfs_path *path;
2642         struct extent_buffer *leaf;
2643         int ret;
2644
2645         path = btrfs_alloc_path();
2646         if (!path)
2647                 return -ENOMEM;
2648
2649         path->leave_spinning = 1;
2650         ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
2651                                  1);
2652         if (ret) {
2653                 if (ret > 0)
2654                         ret = -ENOENT;
2655                 goto failed;
2656         }
2657
2658         btrfs_unlock_up_safe(path, 1);
2659         leaf = path->nodes[0];
2660         inode_item = btrfs_item_ptr(leaf, path->slots[0],
2661                                     struct btrfs_inode_item);
2662
2663         fill_inode_item(trans, leaf, inode_item, inode);
2664         btrfs_mark_buffer_dirty(leaf);
2665         btrfs_set_inode_last_trans(trans, inode);
2666         ret = 0;
2667 failed:
2668         btrfs_free_path(path);
2669         return ret;
2670 }
2671
2672 /*
2673  * copy everything in the in-memory inode into the btree.
2674  */
2675 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
2676                                 struct btrfs_root *root, struct inode *inode)
2677 {
2678         int ret;
2679
2680         /*
2681          * If the inode is a free space inode, we can deadlock during commit
2682          * if we put it into the delayed code.
2683          *
2684          * The data relocation inode should also be directly updated
2685          * without delay
2686          */
2687         if (!btrfs_is_free_space_inode(root, inode)
2688             && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
2689                 ret = btrfs_delayed_update_inode(trans, root, inode);
2690                 if (!ret)
2691                         btrfs_set_inode_last_trans(trans, inode);
2692                 return ret;
2693         }
2694
2695         return btrfs_update_inode_item(trans, root, inode);
2696 }
2697
2698 static noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
2699                                 struct btrfs_root *root, struct inode *inode)
2700 {
2701         int ret;
2702
2703         ret = btrfs_update_inode(trans, root, inode);
2704         if (ret == -ENOSPC)
2705                 return btrfs_update_inode_item(trans, root, inode);
2706         return ret;
2707 }
2708
2709 /*
2710  * unlink helper that gets used here in inode.c and in the tree logging
2711  * recovery code.  It remove a link in a directory with a given name, and
2712  * also drops the back refs in the inode to the directory
2713  */
2714 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2715                                 struct btrfs_root *root,
2716                                 struct inode *dir, struct inode *inode,
2717                                 const char *name, int name_len)
2718 {
2719         struct btrfs_path *path;
2720         int ret = 0;
2721         struct extent_buffer *leaf;
2722         struct btrfs_dir_item *di;
2723         struct btrfs_key key;
2724         u64 index;
2725         u64 ino = btrfs_ino(inode);
2726         u64 dir_ino = btrfs_ino(dir);
2727
2728         path = btrfs_alloc_path();
2729         if (!path) {
2730                 ret = -ENOMEM;
2731                 goto out;
2732         }
2733
2734         path->leave_spinning = 1;
2735         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
2736                                     name, name_len, -1);
2737         if (IS_ERR(di)) {
2738                 ret = PTR_ERR(di);
2739                 goto err;
2740         }
2741         if (!di) {
2742                 ret = -ENOENT;
2743                 goto err;
2744         }
2745         leaf = path->nodes[0];
2746         btrfs_dir_item_key_to_cpu(leaf, di, &key);
2747         ret = btrfs_delete_one_dir_name(trans, root, path, di);
2748         if (ret)
2749                 goto err;
2750         btrfs_release_path(path);
2751
2752         ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
2753                                   dir_ino, &index);
2754         if (ret) {
2755                 printk(KERN_INFO "btrfs failed to delete reference to %.*s, "
2756                        "inode %llu parent %llu\n", name_len, name,
2757                        (unsigned long long)ino, (unsigned long long)dir_ino);
2758                 btrfs_abort_transaction(trans, root, ret);
2759                 goto err;
2760         }
2761
2762         ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
2763         if (ret) {
2764                 btrfs_abort_transaction(trans, root, ret);
2765                 goto err;
2766         }
2767
2768         ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
2769                                          inode, dir_ino);
2770         if (ret != 0 && ret != -ENOENT) {
2771                 btrfs_abort_transaction(trans, root, ret);
2772                 goto err;
2773         }
2774
2775         ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
2776                                            dir, index);
2777         if (ret == -ENOENT)
2778                 ret = 0;
2779 err:
2780         btrfs_free_path(path);
2781         if (ret)
2782                 goto out;
2783
2784         btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2785         inode_inc_iversion(inode);
2786         inode_inc_iversion(dir);
2787         inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2788         btrfs_update_inode(trans, root, dir);
2789 out:
2790         return ret;
2791 }
2792
2793 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2794                        struct btrfs_root *root,
2795                        struct inode *dir, struct inode *inode,
2796                        const char *name, int name_len)
2797 {
2798         int ret;
2799         ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
2800         if (!ret) {
2801                 btrfs_drop_nlink(inode);
2802                 ret = btrfs_update_inode(trans, root, inode);
2803         }
2804         return ret;
2805 }
2806                 
2807
2808 /* helper to check if there is any shared block in the path */
2809 static int check_path_shared(struct btrfs_root *root,
2810                              struct btrfs_path *path)
2811 {
2812         struct extent_buffer *eb;
2813         int level;
2814         u64 refs = 1;
2815
2816         for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2817                 int ret;
2818
2819                 if (!path->nodes[level])
2820                         break;
2821                 eb = path->nodes[level];
2822                 if (!btrfs_block_can_be_shared(root, eb))
2823                         continue;
2824                 ret = btrfs_lookup_extent_info(NULL, root, eb->start, eb->len,
2825                                                &refs, NULL);
2826                 if (refs > 1)
2827                         return 1;
2828         }
2829         return 0;
2830 }
2831
2832 /*
2833  * helper to start transaction for unlink and rmdir.
2834  *
2835  * unlink and rmdir are special in btrfs, they do not always free space.
2836  * so in enospc case, we should make sure they will free space before
2837  * allowing them to use the global metadata reservation.
2838  */
2839 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir,
2840                                                        struct dentry *dentry)
2841 {
2842         struct btrfs_trans_handle *trans;
2843         struct btrfs_root *root = BTRFS_I(dir)->root;
2844         struct btrfs_path *path;
2845         struct btrfs_inode_ref *ref;
2846         struct btrfs_dir_item *di;
2847         struct inode *inode = dentry->d_inode;
2848         u64 index;
2849         int check_link = 1;
2850         int err = -ENOSPC;
2851         int ret;
2852         u64 ino = btrfs_ino(inode);
2853         u64 dir_ino = btrfs_ino(dir);
2854
2855         /*
2856          * 1 for the possible orphan item
2857          * 1 for the dir item
2858          * 1 for the dir index
2859          * 1 for the inode ref
2860          * 1 for the inode ref in the tree log
2861          * 2 for the dir entries in the log
2862          * 1 for the inode
2863          */
2864         trans = btrfs_start_transaction(root, 8);
2865         if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
2866                 return trans;
2867
2868         if (ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
2869                 return ERR_PTR(-ENOSPC);
2870
2871         /* check if there is someone else holds reference */
2872         if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1)
2873                 return ERR_PTR(-ENOSPC);
2874
2875         if (atomic_read(&inode->i_count) > 2)
2876                 return ERR_PTR(-ENOSPC);
2877
2878         if (xchg(&root->fs_info->enospc_unlink, 1))
2879                 return ERR_PTR(-ENOSPC);
2880
2881         path = btrfs_alloc_path();
2882         if (!path) {
2883                 root->fs_info->enospc_unlink = 0;
2884                 return ERR_PTR(-ENOMEM);
2885         }
2886
2887         /* 1 for the orphan item */
2888         trans = btrfs_start_transaction(root, 1);
2889         if (IS_ERR(trans)) {
2890                 btrfs_free_path(path);
2891                 root->fs_info->enospc_unlink = 0;
2892                 return trans;
2893         }
2894
2895         path->skip_locking = 1;
2896         path->search_commit_root = 1;
2897
2898         ret = btrfs_lookup_inode(trans, root, path,
2899                                 &BTRFS_I(dir)->location, 0);
2900         if (ret < 0) {
2901                 err = ret;
2902                 goto out;
2903         }
2904         if (ret == 0) {
2905                 if (check_path_shared(root, path))
2906                         goto out;
2907         } else {
2908                 check_link = 0;
2909         }
2910         btrfs_release_path(path);
2911
2912         ret = btrfs_lookup_inode(trans, root, path,
2913                                 &BTRFS_I(inode)->location, 0);
2914         if (ret < 0) {
2915                 err = ret;
2916                 goto out;
2917         }
2918         if (ret == 0) {
2919                 if (check_path_shared(root, path))
2920                         goto out;
2921         } else {
2922                 check_link = 0;
2923         }
2924         btrfs_release_path(path);
2925
2926         if (ret == 0 && S_ISREG(inode->i_mode)) {
2927                 ret = btrfs_lookup_file_extent(trans, root, path,
2928                                                ino, (u64)-1, 0);
2929                 if (ret < 0) {
2930                         err = ret;
2931                         goto out;
2932                 }
2933                 BUG_ON(ret == 0); /* Corruption */
2934                 if (check_path_shared(root, path))
2935                         goto out;
2936                 btrfs_release_path(path);
2937         }
2938
2939         if (!check_link) {
2940                 err = 0;
2941                 goto out;
2942         }
2943
2944         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
2945                                 dentry->d_name.name, dentry->d_name.len, 0);
2946         if (IS_ERR(di)) {
2947                 err = PTR_ERR(di);
2948                 goto out;
2949         }
2950         if (di) {
2951                 if (check_path_shared(root, path))
2952                         goto out;
2953         } else {
2954                 err = 0;
2955                 goto out;
2956         }
2957         btrfs_release_path(path);
2958
2959         ref = btrfs_lookup_inode_ref(trans, root, path,
2960                                 dentry->d_name.name, dentry->d_name.len,
2961                                 ino, dir_ino, 0);
2962         if (IS_ERR(ref)) {
2963                 err = PTR_ERR(ref);
2964                 goto out;
2965         }
2966         BUG_ON(!ref); /* Logic error */
2967         if (check_path_shared(root, path))
2968                 goto out;
2969         index = btrfs_inode_ref_index(path->nodes[0], ref);
2970         btrfs_release_path(path);
2971
2972         /*
2973          * This is a commit root search, if we can lookup inode item and other
2974          * relative items in the commit root, it means the transaction of
2975          * dir/file creation has been committed, and the dir index item that we
2976          * delay to insert has also been inserted into the commit root. So
2977          * we needn't worry about the delayed insertion of the dir index item
2978          * here.
2979          */
2980         di = btrfs_lookup_dir_index_item(trans, root, path, dir_ino, index,
2981                                 dentry->d_name.name, dentry->d_name.len, 0);
2982         if (IS_ERR(di)) {
2983                 err = PTR_ERR(di);
2984                 goto out;
2985         }
2986         BUG_ON(ret == -ENOENT);
2987         if (check_path_shared(root, path))
2988                 goto out;
2989
2990         err = 0;
2991 out:
2992         btrfs_free_path(path);
2993         /* Migrate the orphan reservation over */
2994         if (!err)
2995                 err = btrfs_block_rsv_migrate(trans->block_rsv,
2996                                 &root->fs_info->global_block_rsv,
2997                                 trans->bytes_reserved);
2998
2999         if (err) {
3000                 btrfs_end_transaction(trans, root);
3001                 root->fs_info->enospc_unlink = 0;
3002                 return ERR_PTR(err);
3003         }
3004
3005         trans->block_rsv = &root->fs_info->global_block_rsv;
3006         return trans;
3007 }
3008
3009 static void __unlink_end_trans(struct btrfs_trans_handle *trans,
3010                                struct btrfs_root *root)
3011 {
3012         if (trans->block_rsv == &root->fs_info->global_block_rsv) {
3013                 btrfs_block_rsv_release(root, trans->block_rsv,
3014                                         trans->bytes_reserved);
3015                 trans->block_rsv = &root->fs_info->trans_block_rsv;
3016                 BUG_ON(!root->fs_info->enospc_unlink);
3017                 root->fs_info->enospc_unlink = 0;
3018         }
3019         btrfs_end_transaction(trans, root);
3020 }
3021
3022 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3023 {
3024         struct btrfs_root *root = BTRFS_I(dir)->root;
3025         struct btrfs_trans_handle *trans;
3026         struct inode *inode = dentry->d_inode;
3027         int ret;
3028         unsigned long nr = 0;
3029
3030         trans = __unlink_start_trans(dir, dentry);
3031         if (IS_ERR(trans))
3032                 return PTR_ERR(trans);
3033
3034         btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3035
3036         ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3037                                  dentry->d_name.name, dentry->d_name.len);
3038         if (ret)
3039                 goto out;
3040
3041         if (inode->i_nlink == 0) {
3042                 ret = btrfs_orphan_add(trans, inode);
3043                 if (ret)
3044                         goto out;
3045         }
3046
3047 out:
3048         nr = trans->blocks_used;
3049         __unlink_end_trans(trans, root);
3050         btrfs_btree_balance_dirty(root, nr);
3051         return ret;
3052 }
3053
3054 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3055                         struct btrfs_root *root,
3056                         struct inode *dir, u64 objectid,
3057                         const char *name, int name_len)
3058 {
3059         struct btrfs_path *path;
3060         struct extent_buffer *leaf;
3061         struct btrfs_dir_item *di;
3062         struct btrfs_key key;
3063         u64 index;
3064         int ret;
3065         u64 dir_ino = btrfs_ino(dir);
3066
3067         path = btrfs_alloc_path();
3068         if (!path)
3069                 return -ENOMEM;
3070
3071         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3072                                    name, name_len, -1);
3073         if (IS_ERR_OR_NULL(di)) {
3074                 if (!di)
3075                         ret = -ENOENT;
3076                 else
3077                         ret = PTR_ERR(di);
3078                 goto out;
3079         }
3080
3081         leaf = path->nodes[0];
3082         btrfs_dir_item_key_to_cpu(leaf, di, &key);
3083         WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3084         ret = btrfs_delete_one_dir_name(trans, root, path, di);
3085         if (ret) {
3086                 btrfs_abort_transaction(trans, root, ret);
3087                 goto out;
3088         }
3089         btrfs_release_path(path);
3090
3091         ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3092                                  objectid, root->root_key.objectid,
3093                                  dir_ino, &index, name, name_len);
3094         if (ret < 0) {
3095                 if (ret != -ENOENT) {
3096                         btrfs_abort_transaction(trans, root, ret);
3097                         goto out;
3098                 }
3099                 di = btrfs_search_dir_index_item(root, path, dir_ino,
3100                                                  name, name_len);
3101                 if (IS_ERR_OR_NULL(di)) {
3102                         if (!di)
3103                                 ret = -ENOENT;
3104                         else
3105                                 ret = PTR_ERR(di);
3106                         btrfs_abort_transaction(trans, root, ret);
3107                         goto out;
3108                 }
3109
3110                 leaf = path->nodes[0];
3111                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3112                 btrfs_release_path(path);
3113                 index = key.offset;
3114         }
3115         btrfs_release_path(path);
3116
3117         ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3118         if (ret) {
3119                 btrfs_abort_transaction(trans, root, ret);
3120                 goto out;
3121         }
3122
3123         btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3124         inode_inc_iversion(dir);
3125         dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3126         ret = btrfs_update_inode(trans, root, dir);
3127         if (ret)
3128                 btrfs_abort_transaction(trans, root, ret);
3129 out:
3130         btrfs_free_path(path);
3131         return ret;
3132 }
3133
3134 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3135 {
3136         struct inode *inode = dentry->d_inode;
3137         int err = 0;
3138         struct btrfs_root *root = BTRFS_I(dir)->root;
3139         struct btrfs_trans_handle *trans;
3140         unsigned long nr = 0;
3141
3142         if (inode->i_size > BTRFS_EMPTY_DIR_SIZE ||
3143             btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
3144                 return -ENOTEMPTY;
3145
3146         trans = __unlink_start_trans(dir, dentry);
3147         if (IS_ERR(trans))
3148                 return PTR_ERR(trans);
3149
3150         if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3151                 err = btrfs_unlink_subvol(trans, root, dir,
3152                                           BTRFS_I(inode)->location.objectid,
3153                                           dentry->d_name.name,
3154                                           dentry->d_name.len);
3155                 goto out;
3156         }
3157
3158         err = btrfs_orphan_add(trans, inode);
3159         if (err)
3160                 goto out;
3161
3162         /* now the directory is empty */
3163         err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3164                                  dentry->d_name.name, dentry->d_name.len);
3165         if (!err)
3166                 btrfs_i_size_write(inode, 0);
3167 out:
3168         nr = trans->blocks_used;
3169         __unlink_end_trans(trans, root);
3170         btrfs_btree_balance_dirty(root, nr);
3171
3172         return err;
3173 }
3174
3175 /*
3176  * this can truncate away extent items, csum items and directory items.
3177  * It starts at a high offset and removes keys until it can't find
3178  * any higher than new_size
3179  *
3180  * csum items that cross the new i_size are truncated to the new size
3181  * as well.
3182  *
3183  * min_type is the minimum key type to truncate down to.  If set to 0, this
3184  * will kill all the items on this inode, including the INODE_ITEM_KEY.
3185  */
3186 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
3187                                struct btrfs_root *root,
3188                                struct inode *inode,
3189                                u64 new_size, u32 min_type)
3190 {
3191         struct btrfs_path *path;
3192         struct extent_buffer *leaf;
3193         struct btrfs_file_extent_item *fi;
3194         struct btrfs_key key;
3195         struct btrfs_key found_key;
3196         u64 extent_start = 0;
3197         u64 extent_num_bytes = 0;
3198         u64 extent_offset = 0;
3199         u64 item_end = 0;
3200         u64 mask = root->sectorsize - 1;
3201         u32 found_type = (u8)-1;
3202         int found_extent;
3203         int del_item;
3204         int pending_del_nr = 0;
3205         int pending_del_slot = 0;
3206         int extent_type = -1;
3207         int ret;
3208         int err = 0;
3209         u64 ino = btrfs_ino(inode);
3210
3211         BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
3212
3213         path = btrfs_alloc_path();
3214         if (!path)
3215                 return -ENOMEM;
3216         path->reada = -1;
3217
3218         if (root->ref_cows || root == root->fs_info->tree_root)
3219                 btrfs_drop_extent_cache(inode, new_size & (~mask), (u64)-1, 0);
3220
3221         /*
3222          * This function is also used to drop the items in the log tree before
3223          * we relog the inode, so if root != BTRFS_I(inode)->root, it means
3224          * it is used to drop the loged items. So we shouldn't kill the delayed
3225          * items.
3226          */
3227         if (min_type == 0 && root == BTRFS_I(inode)->root)
3228                 btrfs_kill_delayed_inode_items(inode);
3229
3230         key.objectid = ino;
3231         key.offset = (u64)-1;
3232         key.type = (u8)-1;
3233
3234 search_again:
3235         path->leave_spinning = 1;
3236         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3237         if (ret < 0) {
3238                 err = ret;
3239                 goto out;
3240         }
3241
3242         if (ret > 0) {
3243                 /* there are no items in the tree for us to truncate, we're
3244                  * done
3245                  */
3246                 if (path->slots[0] == 0)
3247                         goto out;
3248                 path->slots[0]--;
3249         }
3250
3251         while (1) {
3252                 fi = NULL;
3253                 leaf = path->nodes[0];
3254                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3255                 found_type = btrfs_key_type(&found_key);
3256
3257                 if (found_key.objectid != ino)
3258                         break;
3259
3260                 if (found_type < min_type)
3261                         break;
3262
3263                 item_end = found_key.offset;
3264                 if (found_type == BTRFS_EXTENT_DATA_KEY) {
3265                         fi = btrfs_item_ptr(leaf, path->slots[0],
3266                                             struct btrfs_file_extent_item);
3267                         extent_type = btrfs_file_extent_type(leaf, fi);
3268                         if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3269                                 item_end +=
3270                                     btrfs_file_extent_num_bytes(leaf, fi);
3271                         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3272                                 item_end += btrfs_file_extent_inline_len(leaf,
3273                                                                          fi);
3274                         }
3275                         item_end--;
3276                 }
3277                 if (found_type > min_type) {
3278                         del_item = 1;
3279                 } else {
3280                         if (item_end < new_size)
3281                                 break;
3282                         if (found_key.offset >= new_size)
3283                                 del_item = 1;
3284                         else
3285                                 del_item = 0;
3286                 }
3287                 found_extent = 0;
3288                 /* FIXME, shrink the extent if the ref count is only 1 */
3289                 if (found_type != BTRFS_EXTENT_DATA_KEY)
3290                         goto delete;
3291
3292                 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3293                         u64 num_dec;
3294                         extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
3295                         if (!del_item) {
3296                                 u64 orig_num_bytes =
3297                                         btrfs_file_extent_num_bytes(leaf, fi);
3298                                 extent_num_bytes = new_size -
3299                                         found_key.offset + root->sectorsize - 1;
3300                                 extent_num_bytes = extent_num_bytes &
3301                                         ~((u64)root->sectorsize - 1);
3302                                 btrfs_set_file_extent_num_bytes(leaf, fi,
3303                                                          extent_num_bytes);
3304                                 num_dec = (orig_num_bytes -
3305                                            extent_num_bytes);
3306                                 if (root->ref_cows && extent_start != 0)
3307                                         inode_sub_bytes(inode, num_dec);
3308                                 btrfs_mark_buffer_dirty(leaf);
3309                         } else {
3310                                 extent_num_bytes =
3311                                         btrfs_file_extent_disk_num_bytes(leaf,
3312                                                                          fi);
3313                                 extent_offset = found_key.offset -
3314                                         btrfs_file_extent_offset(leaf, fi);
3315
3316                                 /* FIXME blocksize != 4096 */
3317                                 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
3318                                 if (extent_start != 0) {
3319                                         found_extent = 1;
3320                                         if (root->ref_cows)
3321                                                 inode_sub_bytes(inode, num_dec);
3322                                 }
3323                         }
3324                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3325                         /*
3326                          * we can't truncate inline items that have had
3327                          * special encodings
3328                          */
3329                         if (!del_item &&
3330                             btrfs_file_extent_compression(leaf, fi) == 0 &&
3331                             btrfs_file_extent_encryption(leaf, fi) == 0 &&
3332                             btrfs_file_extent_other_encoding(leaf, fi) == 0) {
3333                                 u32 size = new_size - found_key.offset;
3334
3335                                 if (root->ref_cows) {
3336                                         inode_sub_bytes(inode, item_end + 1 -
3337                                                         new_size);
3338                                 }
3339                                 size =
3340                                     btrfs_file_extent_calc_inline_size(size);
3341                                 btrfs_truncate_item(trans, root, path,
3342                                                     size, 1);
3343                         } else if (root->ref_cows) {
3344                                 inode_sub_bytes(inode, item_end + 1 -
3345                                                 found_key.offset);
3346                         }
3347                 }
3348 delete:
3349                 if (del_item) {
3350                         if (!pending_del_nr) {
3351                                 /* no pending yet, add ourselves */
3352                                 pending_del_slot = path->slots[0];
3353                                 pending_del_nr = 1;
3354                         } else if (pending_del_nr &&
3355                                    path->slots[0] + 1 == pending_del_slot) {
3356                                 /* hop on the pending chunk */
3357                                 pending_del_nr++;
3358                                 pending_del_slot = path->slots[0];
3359                         } else {
3360                                 BUG();
3361                         }
3362                 } else {
3363                         break;
3364                 }
3365                 if (found_extent && (root->ref_cows ||
3366                                      root == root->fs_info->tree_root)) {
3367                         btrfs_set_path_blocking(path);
3368                         ret = btrfs_free_extent(trans, root, extent_start,
3369                                                 extent_num_bytes, 0,
3370                                                 btrfs_header_owner(leaf),
3371                                                 ino, extent_offset, 0);
3372                         BUG_ON(ret);
3373                 }
3374
3375                 if (found_type == BTRFS_INODE_ITEM_KEY)
3376                         break;
3377
3378                 if (path->slots[0] == 0 ||
3379                     path->slots[0] != pending_del_slot) {
3380                         if (root->ref_cows &&
3381                             BTRFS_I(inode)->location.objectid !=
3382                                                 BTRFS_FREE_INO_OBJECTID) {
3383                                 err = -EAGAIN;
3384                                 goto out;
3385                         }
3386                         if (pending_del_nr) {
3387                                 ret = btrfs_del_items(trans, root, path,
3388                                                 pending_del_slot,
3389                                                 pending_del_nr);
3390                                 if (ret) {
3391                                         btrfs_abort_transaction(trans,
3392                                                                 root, ret);
3393                                         goto error;
3394                                 }
3395                                 pending_del_nr = 0;
3396                         }
3397                         btrfs_release_path(path);
3398                         goto search_again;
3399                 } else {
3400                         path->slots[0]--;
3401                 }
3402         }
3403 out:
3404         if (pending_del_nr) {
3405                 ret = btrfs_del_items(trans, root, path, pending_del_slot,
3406                                       pending_del_nr);
3407                 if (ret)
3408                         btrfs_abort_transaction(trans, root, ret);
3409         }
3410 error:
3411         btrfs_free_path(path);
3412         return err;
3413 }
3414
3415 /*
3416  * taken from block_truncate_page, but does cow as it zeros out
3417  * any bytes left in the last page in the file.
3418  */
3419 static int btrfs_truncate_page(struct address_space *mapping, loff_t from)
3420 {
3421         struct inode *inode = mapping->host;
3422         struct btrfs_root *root = BTRFS_I(inode)->root;
3423         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3424         struct btrfs_ordered_extent *ordered;
3425         struct extent_state *cached_state = NULL;
3426         char *kaddr;
3427         u32 blocksize = root->sectorsize;
3428         pgoff_t index = from >> PAGE_CACHE_SHIFT;
3429         unsigned offset = from & (PAGE_CACHE_SIZE-1);
3430         struct page *page;
3431         gfp_t mask = btrfs_alloc_write_mask(mapping);
3432         int ret = 0;
3433         u64 page_start;
3434         u64 page_end;
3435
3436         if ((offset & (blocksize - 1)) == 0)
3437                 goto out;
3438         ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
3439         if (ret)
3440                 goto out;
3441
3442         ret = -ENOMEM;
3443 again:
3444         page = find_or_create_page(mapping, index, mask);
3445         if (!page) {
3446                 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3447                 goto out;
3448         }
3449
3450         page_start = page_offset(page);
3451         page_end = page_start + PAGE_CACHE_SIZE - 1;
3452
3453         if (!PageUptodate(page)) {
3454                 ret = btrfs_readpage(NULL, page);
3455                 lock_page(page);
3456                 if (page->mapping != mapping) {
3457                         unlock_page(page);
3458                         page_cache_release(page);
3459                         goto again;
3460                 }
3461                 if (!PageUptodate(page)) {
3462                         ret = -EIO;
3463                         goto out_unlock;
3464                 }
3465         }
3466         wait_on_page_writeback(page);
3467
3468         lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
3469         set_page_extent_mapped(page);
3470
3471         ordered = btrfs_lookup_ordered_extent(inode, page_start);
3472         if (ordered) {
3473                 unlock_extent_cached(io_tree, page_start, page_end,
3474                                      &cached_state, GFP_NOFS);
3475                 unlock_page(page);
3476                 page_cache_release(page);
3477                 btrfs_start_ordered_extent(inode, ordered, 1);
3478                 btrfs_put_ordered_extent(ordered);
3479                 goto again;
3480         }
3481
3482         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
3483                           EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
3484                           0, 0, &cached_state, GFP_NOFS);
3485
3486         ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
3487                                         &cached_state);
3488         if (ret) {
3489                 unlock_extent_cached(io_tree, page_start, page_end,
3490                                      &cached_state, GFP_NOFS);
3491                 goto out_unlock;
3492         }
3493
3494         ret = 0;
3495         if (offset != PAGE_CACHE_SIZE) {
3496                 kaddr = kmap(page);
3497                 memset(kaddr + offset, 0, PAGE_CACHE_SIZE - offset);
3498                 flush_dcache_page(page);
3499                 kunmap(page);
3500         }
3501         ClearPageChecked(page);
3502         set_page_dirty(page);
3503         unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
3504                              GFP_NOFS);
3505
3506 out_unlock:
3507         if (ret)
3508                 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3509         unlock_page(page);
3510         page_cache_release(page);
3511 out:
3512         return ret;
3513 }
3514
3515 /*
3516  * This function puts in dummy file extents for the area we're creating a hole
3517  * for.  So if we are truncating this file to a larger size we need to insert
3518  * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
3519  * the range between oldsize and size
3520  */
3521 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
3522 {
3523         struct btrfs_trans_handle *trans;
3524         struct btrfs_root *root = BTRFS_I(inode)->root;
3525         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3526         struct extent_map *em = NULL;
3527         struct extent_state *cached_state = NULL;
3528         u64 mask = root->sectorsize - 1;
3529         u64 hole_start = (oldsize + mask) & ~mask;
3530         u64 block_end = (size + mask) & ~mask;
3531         u64 last_byte;
3532         u64 cur_offset;
3533         u64 hole_size;
3534         int err = 0;
3535
3536         if (size <= hole_start)
3537                 return 0;
3538
3539         while (1) {
3540                 struct btrfs_ordered_extent *ordered;
3541                 btrfs_wait_ordered_range(inode, hole_start,
3542                                          block_end - hole_start);
3543                 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
3544                                  &cached_state);
3545                 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
3546                 if (!ordered)
3547                         break;
3548                 unlock_extent_cached(io_tree, hole_start, block_end - 1,
3549                                      &cached_state, GFP_NOFS);
3550                 btrfs_put_ordered_extent(ordered);
3551         }
3552
3553         cur_offset = hole_start;
3554         while (1) {
3555                 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
3556                                 block_end - cur_offset, 0);
3557                 if (IS_ERR(em)) {
3558                         err = PTR_ERR(em);
3559                         break;
3560                 }
3561                 last_byte = min(extent_map_end(em), block_end);
3562                 last_byte = (last_byte + mask) & ~mask;
3563                 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3564                         u64 hint_byte = 0;
3565                         hole_size = last_byte - cur_offset;
3566
3567                         trans = btrfs_start_transaction(root, 3);
3568                         if (IS_ERR(trans)) {
3569                                 err = PTR_ERR(trans);
3570                                 break;
3571                         }
3572
3573                         err = btrfs_drop_extents(trans, inode, cur_offset,
3574                                                  cur_offset + hole_size,
3575                                                  &hint_byte, 1);
3576                         if (err) {
3577                                 btrfs_abort_transaction(trans, root, err);
3578                                 btrfs_end_transaction(trans, root);
3579                                 break;
3580                         }
3581
3582                         err = btrfs_insert_file_extent(trans, root,
3583                                         btrfs_ino(inode), cur_offset, 0,
3584                                         0, hole_size, 0, hole_size,
3585                                         0, 0, 0);
3586                         if (err) {
3587                                 btrfs_abort_transaction(trans, root, err);
3588                                 btrfs_end_transaction(trans, root);
3589                                 break;
3590                         }
3591
3592                         btrfs_drop_extent_cache(inode, hole_start,
3593                                         last_byte - 1, 0);
3594
3595                         btrfs_update_inode(trans, root, inode);
3596                         btrfs_end_transaction(trans, root);
3597                 }
3598                 free_extent_map(em);
3599                 em = NULL;
3600                 cur_offset = last_byte;
3601                 if (cur_offset >= block_end)
3602                         break;
3603         }
3604
3605         free_extent_map(em);
3606         unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
3607                              GFP_NOFS);
3608         return err;
3609 }
3610
3611 static int btrfs_setsize(struct inode *inode, loff_t newsize)
3612 {
3613         struct btrfs_root *root = BTRFS_I(inode)->root;
3614         struct btrfs_trans_handle *trans;
3615         loff_t oldsize = i_size_read(inode);
3616         int ret;
3617
3618         if (newsize == oldsize)
3619                 return 0;
3620
3621         if (newsize > oldsize) {
3622                 truncate_pagecache(inode, oldsize, newsize);
3623                 ret = btrfs_cont_expand(inode, oldsize, newsize);
3624                 if (ret)
3625                         return ret;
3626
3627                 trans = btrfs_start_transaction(root, 1);
3628                 if (IS_ERR(trans))
3629                         return PTR_ERR(trans);
3630
3631                 i_size_write(inode, newsize);
3632                 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
3633                 ret = btrfs_update_inode(trans, root, inode);
3634                 btrfs_end_transaction(trans, root);
3635         } else {
3636
3637                 /*
3638                  * We're truncating a file that used to have good data down to
3639                  * zero. Make sure it gets into the ordered flush list so that
3640                  * any new writes get down to disk quickly.
3641                  */
3642                 if (newsize == 0)
3643                         set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
3644                                 &BTRFS_I(inode)->runtime_flags);
3645
3646                 /* we don't support swapfiles, so vmtruncate shouldn't fail */
3647                 truncate_setsize(inode, newsize);
3648                 ret = btrfs_truncate(inode);
3649         }
3650
3651         return ret;
3652 }
3653
3654 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
3655 {
3656         struct inode *inode = dentry->d_inode;
3657         struct btrfs_root *root = BTRFS_I(inode)->root;
3658         int err;
3659
3660         if (btrfs_root_readonly(root))
3661                 return -EROFS;
3662
3663         err = inode_change_ok(inode, attr);
3664         if (err)
3665                 return err;
3666
3667         if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
3668                 err = btrfs_setsize(inode, attr->ia_size);
3669                 if (err)
3670                         return err;
3671         }
3672
3673         if (attr->ia_valid) {
3674                 setattr_copy(inode, attr);
3675                 inode_inc_iversion(inode);
3676                 err = btrfs_dirty_inode(inode);
3677
3678                 if (!err && attr->ia_valid & ATTR_MODE)
3679                         err = btrfs_acl_chmod(inode);
3680         }
3681
3682         return err;
3683 }
3684
3685 void btrfs_evict_inode(struct inode *inode)
3686 {
3687         struct btrfs_trans_handle *trans;
3688         struct btrfs_root *root = BTRFS_I(inode)->root;
3689         struct btrfs_block_rsv *rsv, *global_rsv;
3690         u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
3691         unsigned long nr;
3692         int ret;
3693
3694         trace_btrfs_inode_evict(inode);
3695
3696         truncate_inode_pages(&inode->i_data, 0);
3697         if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 ||
3698                                btrfs_is_free_space_inode(root, inode)))
3699                 goto no_delete;
3700
3701         if (is_bad_inode(inode)) {
3702                 btrfs_orphan_del(NULL, inode);
3703                 goto no_delete;
3704         }
3705         /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
3706         btrfs_wait_ordered_range(inode, 0, (u64)-1);
3707
3708         if (root->fs_info->log_root_recovering) {
3709                 BUG_ON(!list_empty(&BTRFS_I(inode)->i_orphan));
3710                 goto no_delete;
3711         }
3712
3713         if (inode->i_nlink > 0) {
3714                 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
3715                 goto no_delete;
3716         }
3717
3718         rsv = btrfs_alloc_block_rsv(root);
3719         if (!rsv) {
3720                 btrfs_orphan_del(NULL, inode);
3721                 goto no_delete;
3722         }
3723         rsv->size = min_size;
3724         global_rsv = &root->fs_info->global_block_rsv;
3725
3726         btrfs_i_size_write(inode, 0);
3727
3728         /*
3729          * This is a bit simpler than btrfs_truncate since
3730          *
3731          * 1) We've already reserved our space for our orphan item in the
3732          *    unlink.
3733          * 2) We're going to delete the inode item, so we don't need to update
3734          *    it at all.
3735          *
3736          * So we just need to reserve some slack space in case we add bytes when
3737          * doing the truncate.
3738          */
3739         while (1) {
3740                 ret = btrfs_block_rsv_refill_noflush(root, rsv, min_size);
3741
3742                 /*
3743                  * Try and steal from the global reserve since we will
3744                  * likely not use this space anyway, we want to try as
3745                  * hard as possible to get this to work.
3746                  */
3747                 if (ret)
3748                         ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
3749
3750                 if (ret) {
3751                         printk(KERN_WARNING "Could not get space for a "
3752                                "delete, will truncate on mount %d\n", ret);
3753                         btrfs_orphan_del(NULL, inode);
3754                         btrfs_free_block_rsv(root, rsv);
3755                         goto no_delete;
3756                 }
3757
3758                 trans = btrfs_start_transaction(root, 0);
3759                 if (IS_ERR(trans)) {
3760                         btrfs_orphan_del(NULL, inode);
3761                         btrfs_free_block_rsv(root, rsv);
3762                         goto no_delete;
3763                 }
3764
3765                 trans->block_rsv = rsv;
3766
3767                 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
3768                 if (ret != -EAGAIN)
3769                         break;
3770
3771                 nr = trans->blocks_used;
3772                 btrfs_end_transaction(trans, root);
3773                 trans = NULL;
3774                 btrfs_btree_balance_dirty(root, nr);
3775         }
3776
3777         btrfs_free_block_rsv(root, rsv);
3778
3779         if (ret == 0) {
3780                 trans->block_rsv = root->orphan_block_rsv;
3781                 ret = btrfs_orphan_del(trans, inode);
3782                 BUG_ON(ret);
3783         }
3784
3785         trans->block_rsv = &root->fs_info->trans_block_rsv;
3786         if (!(root == root->fs_info->tree_root ||
3787               root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
3788                 btrfs_return_ino(root, btrfs_ino(inode));
3789
3790         nr = trans->blocks_used;
3791         btrfs_end_transaction(trans, root);
3792         btrfs_btree_balance_dirty(root, nr);
3793 no_delete:
3794         end_writeback(inode);
3795         return;
3796 }
3797
3798 /*
3799  * this returns the key found in the dir entry in the location pointer.
3800  * If no dir entries were found, location->objectid is 0.
3801  */
3802 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
3803                                struct btrfs_key *location)
3804 {
3805         const char *name = dentry->d_name.name;
3806         int namelen = dentry->d_name.len;
3807         struct btrfs_dir_item *di;
3808         struct btrfs_path *path;
3809         struct btrfs_root *root = BTRFS_I(dir)->root;
3810         int ret = 0;
3811
3812         path = btrfs_alloc_path();
3813         if (!path)
3814                 return -ENOMEM;
3815
3816         di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
3817                                     namelen, 0);
3818         if (IS_ERR(di))
3819                 ret = PTR_ERR(di);
3820
3821         if (IS_ERR_OR_NULL(di))
3822                 goto out_err;
3823
3824         btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
3825 out:
3826         btrfs_free_path(path);
3827         return ret;
3828 out_err:
3829         location->objectid = 0;
3830         goto out;
3831 }
3832
3833 /*
3834  * when we hit a tree root in a directory, the btrfs part of the inode
3835  * needs to be changed to reflect the root directory of the tree root.  This
3836  * is kind of like crossing a mount point.
3837  */
3838 static int fixup_tree_root_location(struct btrfs_root *root,
3839                                     struct inode *dir,
3840                                     struct dentry *dentry,
3841                                     struct btrfs_key *location,
3842                                     struct btrfs_root **sub_root)
3843 {
3844         struct btrfs_path *path;
3845         struct btrfs_root *new_root;
3846         struct btrfs_root_ref *ref;
3847         struct extent_buffer *leaf;
3848         int ret;
3849         int err = 0;
3850
3851         path = btrfs_alloc_path();
3852         if (!path) {
3853                 err = -ENOMEM;
3854                 goto out;
3855         }
3856
3857         err = -ENOENT;
3858         ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
3859                                   BTRFS_I(dir)->root->root_key.objectid,
3860                                   location->objectid);
3861         if (ret) {
3862                 if (ret < 0)
3863                         err = ret;
3864                 goto out;
3865         }
3866
3867         leaf = path->nodes[0];
3868         ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
3869         if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
3870             btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
3871                 goto out;
3872
3873         ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
3874                                    (unsigned long)(ref + 1),
3875                                    dentry->d_name.len);
3876         if (ret)
3877                 goto out;
3878
3879         btrfs_release_path(path);
3880
3881         new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
3882         if (IS_ERR(new_root)) {
3883                 err = PTR_ERR(new_root);
3884                 goto out;
3885         }
3886
3887         if (btrfs_root_refs(&new_root->root_item) == 0) {
3888                 err = -ENOENT;
3889                 goto out;
3890         }
3891
3892         *sub_root = new_root;
3893         location->objectid = btrfs_root_dirid(&new_root->root_item);
3894         location->type = BTRFS_INODE_ITEM_KEY;
3895         location->offset = 0;
3896         err = 0;
3897 out:
3898         btrfs_free_path(path);
3899         return err;
3900 }
3901
3902 static void inode_tree_add(struct inode *inode)
3903 {
3904         struct btrfs_root *root = BTRFS_I(inode)->root;
3905         struct btrfs_inode *entry;
3906         struct rb_node **p;
3907         struct rb_node *parent;
3908         u64 ino = btrfs_ino(inode);
3909 again:
3910         p = &root->inode_tree.rb_node;
3911         parent = NULL;
3912
3913         if (inode_unhashed(inode))
3914                 return;
3915
3916         spin_lock(&root->inode_lock);
3917         while (*p) {
3918                 parent = *p;
3919                 entry = rb_entry(parent, struct btrfs_inode, rb_node);
3920
3921                 if (ino < btrfs_ino(&entry->vfs_inode))
3922                         p = &parent->rb_left;
3923                 else if (ino > btrfs_ino(&entry->vfs_inode))
3924                         p = &parent->rb_right;
3925                 else {
3926                         WARN_ON(!(entry->vfs_inode.i_state &
3927                                   (I_WILL_FREE | I_FREEING)));
3928                         rb_erase(parent, &root->inode_tree);
3929                         RB_CLEAR_NODE(parent);
3930                         spin_unlock(&root->inode_lock);
3931                         goto again;
3932                 }
3933         }
3934         rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
3935         rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
3936         spin_unlock(&root->inode_lock);
3937 }
3938
3939 static void inode_tree_del(struct inode *inode)
3940 {
3941         struct btrfs_root *root = BTRFS_I(inode)->root;
3942         int empty = 0;
3943
3944         spin_lock(&root->inode_lock);
3945         if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
3946                 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
3947                 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
3948                 empty = RB_EMPTY_ROOT(&root->inode_tree);
3949         }
3950         spin_unlock(&root->inode_lock);
3951
3952         /*
3953          * Free space cache has inodes in the tree root, but the tree root has a
3954          * root_refs of 0, so this could end up dropping the tree root as a
3955          * snapshot, so we need the extra !root->fs_info->tree_root check to
3956          * make sure we don't drop it.
3957          */
3958         if (empty && btrfs_root_refs(&root->root_item) == 0 &&
3959             root != root->fs_info->tree_root) {
3960                 synchronize_srcu(&root->fs_info->subvol_srcu);
3961                 spin_lock(&root->inode_lock);
3962                 empty = RB_EMPTY_ROOT(&root->inode_tree);
3963                 spin_unlock(&root->inode_lock);
3964                 if (empty)
3965                         btrfs_add_dead_root(root);
3966         }
3967 }
3968
3969 void btrfs_invalidate_inodes(struct btrfs_root *root)
3970 {
3971         struct rb_node *node;
3972         struct rb_node *prev;
3973         struct btrfs_inode *entry;
3974         struct inode *inode;
3975         u64 objectid = 0;
3976
3977         WARN_ON(btrfs_root_refs(&root->root_item) != 0);
3978
3979         spin_lock(&root->inode_lock);
3980 again:
3981         node = root->inode_tree.rb_node;
3982         prev = NULL;
3983         while (node) {
3984                 prev = node;
3985                 entry = rb_entry(node, struct btrfs_inode, rb_node);
3986
3987                 if (objectid < btrfs_ino(&entry->vfs_inode))
3988                         node = node->rb_left;
3989                 else if (objectid > btrfs_ino(&entry->vfs_inode))
3990                         node = node->rb_right;
3991                 else
3992                         break;
3993         }
3994         if (!node) {
3995                 while (prev) {
3996                         entry = rb_entry(prev, struct btrfs_inode, rb_node);
3997                         if (objectid <= btrfs_ino(&entry->vfs_inode)) {
3998                                 node = prev;
3999                                 break;
4000                         }
4001                         prev = rb_next(prev);
4002                 }
4003         }
4004         while (node) {
4005                 entry = rb_entry(node, struct btrfs_inode, rb_node);
4006                 objectid = btrfs_ino(&entry->vfs_inode) + 1;
4007                 inode = igrab(&entry->vfs_inode);
4008                 if (inode) {
4009                         spin_unlock(&root->inode_lock);
4010                         if (atomic_read(&inode->i_count) > 1)
4011                                 d_prune_aliases(inode);
4012                         /*
4013                          * btrfs_drop_inode will have it removed from
4014                          * the inode cache when its usage count
4015                          * hits zero.
4016                          */
4017                         iput(inode);
4018                         cond_resched();
4019                         spin_lock(&root->inode_lock);
4020                         goto again;
4021                 }
4022
4023                 if (cond_resched_lock(&root->inode_lock))
4024                         goto again;
4025
4026                 node = rb_next(node);
4027         }
4028         spin_unlock(&root->inode_lock);
4029 }
4030
4031 static int btrfs_init_locked_inode(struct inode *inode, void *p)
4032 {
4033         struct btrfs_iget_args *args = p;
4034         inode->i_ino = args->ino;
4035         BTRFS_I(inode)->root = args->root;
4036         btrfs_set_inode_space_info(args->root, inode);
4037         return 0;
4038 }
4039
4040 static int btrfs_find_actor(struct inode *inode, void *opaque)
4041 {
4042         struct btrfs_iget_args *args = opaque;
4043         return args->ino == btrfs_ino(inode) &&
4044                 args->root == BTRFS_I(inode)->root;
4045 }
4046
4047 static struct inode *btrfs_iget_locked(struct super_block *s,
4048                                        u64 objectid,
4049                                        struct btrfs_root *root)
4050 {
4051         struct inode *inode;
4052         struct btrfs_iget_args args;
4053         args.ino = objectid;
4054         args.root = root;
4055
4056         inode = iget5_locked(s, objectid, btrfs_find_actor,
4057                              btrfs_init_locked_inode,
4058                              (void *)&args);
4059         return inode;
4060 }
4061
4062 /* Get an inode object given its location and corresponding root.
4063  * Returns in *is_new if the inode was read from disk
4064  */
4065 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
4066                          struct btrfs_root *root, int *new)
4067 {
4068         struct inode *inode;
4069
4070         inode = btrfs_iget_locked(s, location->objectid, root);
4071         if (!inode)
4072                 return ERR_PTR(-ENOMEM);
4073
4074         if (inode->i_state & I_NEW) {
4075                 BTRFS_I(inode)->root = root;
4076                 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
4077                 btrfs_read_locked_inode(inode);
4078                 if (!is_bad_inode(inode)) {
4079                         inode_tree_add(inode);
4080                         unlock_new_inode(inode);
4081                         if (new)
4082                                 *new = 1;
4083                 } else {
4084                         unlock_new_inode(inode);
4085                         iput(inode);
4086                         inode = ERR_PTR(-ESTALE);
4087                 }
4088         }
4089
4090         return inode;
4091 }
4092
4093 static struct inode *new_simple_dir(struct super_block *s,
4094                                     struct btrfs_key *key,
4095                                     struct btrfs_root *root)
4096 {
4097         struct inode *inode = new_inode(s);
4098
4099         if (!inode)
4100                 return ERR_PTR(-ENOMEM);
4101
4102         BTRFS_I(inode)->root = root;
4103         memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
4104         set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
4105
4106         inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
4107         inode->i_op = &btrfs_dir_ro_inode_operations;
4108         inode->i_fop = &simple_dir_operations;
4109         inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
4110         inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4111
4112         return inode;
4113 }
4114
4115 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
4116 {
4117         struct inode *inode;
4118         struct btrfs_root *root = BTRFS_I(dir)->root;
4119         struct btrfs_root *sub_root = root;
4120         struct btrfs_key location;
4121         int index;
4122         int ret = 0;
4123
4124         if (dentry->d_name.len > BTRFS_NAME_LEN)
4125                 return ERR_PTR(-ENAMETOOLONG);
4126
4127         if (unlikely(d_need_lookup(dentry))) {
4128                 memcpy(&location, dentry->d_fsdata, sizeof(struct btrfs_key));
4129                 kfree(dentry->d_fsdata);
4130                 dentry->d_fsdata = NULL;
4131                 /* This thing is hashed, drop it for now */
4132                 d_drop(dentry);
4133         } else {
4134                 ret = btrfs_inode_by_name(dir, dentry, &location);
4135         }
4136
4137         if (ret < 0)
4138                 return ERR_PTR(ret);
4139
4140         if (location.objectid == 0)
4141                 return NULL;
4142
4143         if (location.type == BTRFS_INODE_ITEM_KEY) {
4144                 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
4145                 return inode;
4146         }
4147
4148         BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
4149
4150         index = srcu_read_lock(&root->fs_info->subvol_srcu);
4151         ret = fixup_tree_root_location(root, dir, dentry,
4152                                        &location, &sub_root);
4153         if (ret < 0) {
4154                 if (ret != -ENOENT)
4155                         inode = ERR_PTR(ret);
4156                 else
4157                         inode = new_simple_dir(dir->i_sb, &location, sub_root);
4158         } else {
4159                 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
4160         }
4161         srcu_read_unlock(&root->fs_info->subvol_srcu, index);
4162
4163         if (!IS_ERR(inode) && root != sub_root) {
4164                 down_read(&root->fs_info->cleanup_work_sem);
4165                 if (!(inode->i_sb->s_flags & MS_RDONLY))
4166                         ret = btrfs_orphan_cleanup(sub_root);
4167                 up_read(&root->fs_info->cleanup_work_sem);
4168                 if (ret)
4169                         inode = ERR_PTR(ret);
4170         }
4171
4172         return inode;
4173 }
4174
4175 static int btrfs_dentry_delete(const struct dentry *dentry)
4176 {
4177         struct btrfs_root *root;
4178         struct inode *inode = dentry->d_inode;
4179
4180         if (!inode && !IS_ROOT(dentry))
4181                 inode = dentry->d_parent->d_inode;
4182
4183         if (inode) {
4184                 root = BTRFS_I(inode)->root;
4185                 if (btrfs_root_refs(&root->root_item) == 0)
4186                         return 1;
4187
4188                 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
4189                         return 1;
4190         }
4191         return 0;
4192 }
4193
4194 static void btrfs_dentry_release(struct dentry *dentry)
4195 {
4196         if (dentry->d_fsdata)
4197                 kfree(dentry->d_fsdata);
4198 }
4199
4200 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
4201                                    struct nameidata *nd)
4202 {
4203         struct dentry *ret;
4204
4205         ret = d_splice_alias(btrfs_lookup_dentry(dir, dentry), dentry);
4206         if (unlikely(d_need_lookup(dentry))) {
4207                 spin_lock(&dentry->d_lock);
4208                 dentry->d_flags &= ~DCACHE_NEED_LOOKUP;
4209                 spin_unlock(&dentry->d_lock);
4210         }
4211         return ret;
4212 }
4213
4214 unsigned char btrfs_filetype_table[] = {
4215         DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
4216 };
4217
4218 static int btrfs_real_readdir(struct file *filp, void *dirent,
4219                               filldir_t filldir)
4220 {
4221         struct inode *inode = filp->f_dentry->d_inode;
4222         struct btrfs_root *root = BTRFS_I(inode)->root;
4223         struct btrfs_item *item;
4224         struct btrfs_dir_item *di;
4225         struct btrfs_key key;
4226         struct btrfs_key found_key;
4227         struct btrfs_path *path;
4228         struct list_head ins_list;
4229         struct list_head del_list;
4230         int ret;
4231         struct extent_buffer *leaf;
4232         int slot;
4233         unsigned char d_type;
4234         int over = 0;
4235         u32 di_cur;
4236         u32 di_total;
4237         u32 di_len;
4238         int key_type = BTRFS_DIR_INDEX_KEY;
4239         char tmp_name[32];
4240         char *name_ptr;
4241         int name_len;
4242         int is_curr = 0;        /* filp->f_pos points to the current index? */
4243
4244         /* FIXME, use a real flag for deciding about the key type */
4245         if (root->fs_info->tree_root == root)
4246                 key_type = BTRFS_DIR_ITEM_KEY;
4247
4248         /* special case for "." */
4249         if (filp->f_pos == 0) {
4250                 over = filldir(dirent, ".", 1,
4251                                filp->f_pos, btrfs_ino(inode), DT_DIR);
4252                 if (over)
4253                         return 0;
4254                 filp->f_pos = 1;
4255         }
4256         /* special case for .., just use the back ref */
4257         if (filp->f_pos == 1) {
4258                 u64 pino = parent_ino(filp->f_path.dentry);
4259                 over = filldir(dirent, "..", 2,
4260                                filp->f_pos, pino, DT_DIR);
4261                 if (over)
4262                         return 0;
4263                 filp->f_pos = 2;
4264         }
4265         path = btrfs_alloc_path();
4266         if (!path)
4267                 return -ENOMEM;
4268
4269         path->reada = 1;
4270
4271         if (key_type == BTRFS_DIR_INDEX_KEY) {
4272                 INIT_LIST_HEAD(&ins_list);
4273                 INIT_LIST_HEAD(&del_list);
4274                 btrfs_get_delayed_items(inode, &ins_list, &del_list);
4275         }
4276
4277         btrfs_set_key_type(&key, key_type);
4278         key.offset = filp->f_pos;
4279         key.objectid = btrfs_ino(inode);
4280
4281         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4282         if (ret < 0)
4283                 goto err;
4284
4285         while (1) {
4286                 leaf = path->nodes[0];
4287                 slot = path->slots[0];
4288                 if (slot >= btrfs_header_nritems(leaf)) {
4289                         ret = btrfs_next_leaf(root, path);
4290                         if (ret < 0)
4291                                 goto err;
4292                         else if (ret > 0)
4293                                 break;
4294                         continue;
4295                 }
4296
4297                 item = btrfs_item_nr(leaf, slot);
4298                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
4299
4300                 if (found_key.objectid != key.objectid)
4301                         break;
4302                 if (btrfs_key_type(&found_key) != key_type)
4303                         break;
4304                 if (found_key.offset < filp->f_pos)
4305                         goto next;
4306                 if (key_type == BTRFS_DIR_INDEX_KEY &&
4307                     btrfs_should_delete_dir_index(&del_list,
4308                                                   found_key.offset))
4309                         goto next;
4310
4311                 filp->f_pos = found_key.offset;
4312                 is_curr = 1;
4313
4314                 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
4315                 di_cur = 0;
4316                 di_total = btrfs_item_size(leaf, item);
4317
4318                 while (di_cur < di_total) {
4319                         struct btrfs_key location;
4320
4321                         if (verify_dir_item(root, leaf, di))
4322                                 break;
4323
4324                         name_len = btrfs_dir_name_len(leaf, di);
4325                         if (name_len <= sizeof(tmp_name)) {
4326                                 name_ptr = tmp_name;
4327                         } else {
4328                                 name_ptr = kmalloc(name_len, GFP_NOFS);
4329                                 if (!name_ptr) {
4330                                         ret = -ENOMEM;
4331                                         goto err;
4332                                 }
4333                         }
4334                         read_extent_buffer(leaf, name_ptr,
4335                                            (unsigned long)(di + 1), name_len);
4336
4337                         d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
4338                         btrfs_dir_item_key_to_cpu(leaf, di, &location);
4339
4340
4341                         /* is this a reference to our own snapshot? If so
4342                          * skip it.
4343                          *
4344                          * In contrast to old kernels, we insert the snapshot's
4345                          * dir item and dir index after it has been created, so
4346                          * we won't find a reference to our own snapshot. We
4347                          * still keep the following code for backward
4348                          * compatibility.
4349                          */
4350                         if (location.type == BTRFS_ROOT_ITEM_KEY &&
4351                             location.objectid == root->root_key.objectid) {
4352                                 over = 0;
4353                                 goto skip;
4354                         }
4355                         over = filldir(dirent, name_ptr, name_len,
4356                                        found_key.offset, location.objectid,
4357                                        d_type);
4358
4359 skip:
4360                         if (name_ptr != tmp_name)
4361                                 kfree(name_ptr);
4362
4363                         if (over)
4364                                 goto nopos;
4365                         di_len = btrfs_dir_name_len(leaf, di) +
4366                                  btrfs_dir_data_len(leaf, di) + sizeof(*di);
4367                         di_cur += di_len;
4368                         di = (struct btrfs_dir_item *)((char *)di + di_len);
4369                 }
4370 next:
4371                 path->slots[0]++;
4372         }
4373
4374         if (key_type == BTRFS_DIR_INDEX_KEY) {
4375                 if (is_curr)
4376                         filp->f_pos++;
4377                 ret = btrfs_readdir_delayed_dir_index(filp, dirent, filldir,
4378                                                       &ins_list);
4379                 if (ret)
4380                         goto nopos;
4381         }
4382
4383         /* Reached end of directory/root. Bump pos past the last item. */
4384         if (key_type == BTRFS_DIR_INDEX_KEY)
4385                 /*
4386                  * 32-bit glibc will use getdents64, but then strtol -
4387                  * so the last number we can serve is this.
4388                  */
4389                 filp->f_pos = 0x7fffffff;
4390         else
4391                 filp->f_pos++;
4392 nopos:
4393         ret = 0;
4394 err:
4395         if (key_type == BTRFS_DIR_INDEX_KEY)
4396                 btrfs_put_delayed_items(&ins_list, &del_list);
4397         btrfs_free_path(path);
4398         return ret;
4399 }
4400
4401 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
4402 {
4403         struct btrfs_root *root = BTRFS_I(inode)->root;
4404         struct btrfs_trans_handle *trans;
4405         int ret = 0;
4406         bool nolock = false;
4407
4408         if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
4409                 return 0;
4410
4411         if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(root, inode))
4412                 nolock = true;
4413
4414         if (wbc->sync_mode == WB_SYNC_ALL) {
4415                 if (nolock)
4416                         trans = btrfs_join_transaction_nolock(root);
4417                 else
4418                         trans = btrfs_join_transaction(root);
4419                 if (IS_ERR(trans))
4420                         return PTR_ERR(trans);
4421                 if (nolock)
4422                         ret = btrfs_end_transaction_nolock(trans, root);
4423                 else
4424                         ret = btrfs_commit_transaction(trans, root);
4425         }
4426         return ret;
4427 }
4428
4429 /*
4430  * This is somewhat expensive, updating the tree every time the
4431  * inode changes.  But, it is most likely to find the inode in cache.
4432  * FIXME, needs more benchmarking...there are no reasons other than performance
4433  * to keep or drop this code.
4434  */
4435 int btrfs_dirty_inode(struct inode *inode)
4436 {
4437         struct btrfs_root *root = BTRFS_I(inode)->root;
4438         struct btrfs_trans_handle *trans;
4439         int ret;
4440
4441         if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
4442                 return 0;
4443
4444         trans = btrfs_join_transaction(root);
4445         if (IS_ERR(trans))
4446                 return PTR_ERR(trans);
4447
4448         ret = btrfs_update_inode(trans, root, inode);
4449         if (ret && ret == -ENOSPC) {
4450                 /* whoops, lets try again with the full transaction */
4451                 btrfs_end_transaction(trans, root);
4452                 trans = btrfs_start_transaction(root, 1);
4453                 if (IS_ERR(trans))
4454                         return PTR_ERR(trans);
4455
4456                 ret = btrfs_update_inode(trans, root, inode);
4457         }
4458         btrfs_end_transaction(trans, root);
4459         if (BTRFS_I(inode)->delayed_node)
4460                 btrfs_balance_delayed_items(root);
4461
4462         return ret;
4463 }
4464
4465 /*
4466  * This is a copy of file_update_time.  We need this so we can return error on
4467  * ENOSPC for updating the inode in the case of file write and mmap writes.
4468  */
4469 int btrfs_update_time(struct file *file)
4470 {
4471         struct inode *inode = file->f_path.dentry->d_inode;
4472         struct timespec now;
4473         int ret;
4474         enum { S_MTIME = 1, S_CTIME = 2, S_VERSION = 4 } sync_it = 0;
4475
4476         /* First try to exhaust all avenues to not sync */
4477         if (IS_NOCMTIME(inode))
4478                 return 0;
4479
4480         now = current_fs_time(inode->i_sb);
4481         if (!timespec_equal(&inode->i_mtime, &now))
4482                 sync_it = S_MTIME;
4483
4484         if (!timespec_equal(&inode->i_ctime, &now))
4485                 sync_it |= S_CTIME;
4486
4487         if (IS_I_VERSION(inode))
4488                 sync_it |= S_VERSION;
4489
4490         if (!sync_it)
4491                 return 0;
4492
4493         /* Finally allowed to write? Takes lock. */
4494         if (mnt_want_write_file(file))
4495                 return 0;
4496
4497         /* Only change inode inside the lock region */
4498         if (sync_it & S_VERSION)
4499                 inode_inc_iversion(inode);
4500         if (sync_it & S_CTIME)
4501                 inode->i_ctime = now;
4502         if (sync_it & S_MTIME)
4503                 inode->i_mtime = now;
4504         ret = btrfs_dirty_inode(inode);
4505         if (!ret)
4506                 mark_inode_dirty_sync(inode);
4507         mnt_drop_write(file->f_path.mnt);
4508         return ret;
4509 }
4510
4511 /*
4512  * find the highest existing sequence number in a directory
4513  * and then set the in-memory index_cnt variable to reflect
4514  * free sequence numbers
4515  */
4516 static int btrfs_set_inode_index_count(struct inode *inode)
4517 {
4518         struct btrfs_root *root = BTRFS_I(inode)->root;
4519         struct btrfs_key key, found_key;
4520         struct btrfs_path *path;
4521         struct extent_buffer *leaf;
4522         int ret;
4523
4524         key.objectid = btrfs_ino(inode);
4525         btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
4526         key.offset = (u64)-1;
4527
4528         path = btrfs_alloc_path();
4529         if (!path)
4530                 return -ENOMEM;
4531
4532         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4533         if (ret < 0)
4534                 goto out;
4535         /* FIXME: we should be able to handle this */
4536         if (ret == 0)
4537                 goto out;
4538         ret = 0;
4539
4540         /*
4541          * MAGIC NUMBER EXPLANATION:
4542          * since we search a directory based on f_pos we have to start at 2
4543          * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
4544          * else has to start at 2
4545          */
4546         if (path->slots[0] == 0) {
4547                 BTRFS_I(inode)->index_cnt = 2;
4548                 goto out;
4549         }
4550
4551         path->slots[0]--;
4552
4553         leaf = path->nodes[0];
4554         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4555
4556         if (found_key.objectid != btrfs_ino(inode) ||
4557             btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
4558                 BTRFS_I(inode)->index_cnt = 2;
4559                 goto out;
4560         }
4561
4562         BTRFS_I(inode)->index_cnt = found_key.offset + 1;
4563 out:
4564         btrfs_free_path(path);
4565         return ret;
4566 }
4567
4568 /*
4569  * helper to find a free sequence number in a given directory.  This current
4570  * code is very simple, later versions will do smarter things in the btree
4571  */
4572 int btrfs_set_inode_index(struct inode *dir, u64 *index)
4573 {
4574         int ret = 0;
4575
4576         if (BTRFS_I(dir)->index_cnt == (u64)-1) {
4577                 ret = btrfs_inode_delayed_dir_index_count(dir);
4578                 if (ret) {
4579                         ret = btrfs_set_inode_index_count(dir);
4580                         if (ret)
4581                                 return ret;
4582                 }
4583         }
4584
4585         *index = BTRFS_I(dir)->index_cnt;
4586         BTRFS_I(dir)->index_cnt++;
4587
4588         return ret;
4589 }
4590
4591 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
4592                                      struct btrfs_root *root,
4593                                      struct inode *dir,
4594                                      const char *name, int name_len,
4595                                      u64 ref_objectid, u64 objectid,
4596                                      umode_t mode, u64 *index)
4597 {
4598         struct inode *inode;
4599         struct btrfs_inode_item *inode_item;
4600         struct btrfs_key *location;
4601         struct btrfs_path *path;
4602         struct btrfs_inode_ref *ref;
4603         struct btrfs_key key[2];
4604         u32 sizes[2];
4605         unsigned long ptr;
4606         int ret;
4607         int owner;
4608
4609         path = btrfs_alloc_path();
4610         if (!path)
4611                 return ERR_PTR(-ENOMEM);
4612
4613         inode = new_inode(root->fs_info->sb);
4614         if (!inode) {
4615                 btrfs_free_path(path);
4616                 return ERR_PTR(-ENOMEM);
4617         }
4618
4619         /*
4620          * we have to initialize this early, so we can reclaim the inode
4621          * number if we fail afterwards in this function.
4622          */
4623         inode->i_ino = objectid;
4624
4625         if (dir) {
4626                 trace_btrfs_inode_request(dir);
4627
4628                 ret = btrfs_set_inode_index(dir, index);
4629                 if (ret) {
4630                         btrfs_free_path(path);
4631                         iput(inode);
4632                         return ERR_PTR(ret);
4633                 }
4634         }
4635         /*
4636          * index_cnt is ignored for everything but a dir,
4637          * btrfs_get_inode_index_count has an explanation for the magic
4638          * number
4639          */
4640         BTRFS_I(inode)->index_cnt = 2;
4641         BTRFS_I(inode)->root = root;
4642         BTRFS_I(inode)->generation = trans->transid;
4643         inode->i_generation = BTRFS_I(inode)->generation;
4644         btrfs_set_inode_space_info(root, inode);
4645
4646         if (S_ISDIR(mode))
4647                 owner = 0;
4648         else
4649                 owner = 1;
4650
4651         key[0].objectid = objectid;
4652         btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
4653         key[0].offset = 0;
4654
4655         key[1].objectid = objectid;
4656         btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
4657         key[1].offset = ref_objectid;
4658
4659         sizes[0] = sizeof(struct btrfs_inode_item);
4660         sizes[1] = name_len + sizeof(*ref);
4661
4662         path->leave_spinning = 1;
4663         ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
4664         if (ret != 0)
4665                 goto fail;
4666
4667         inode_init_owner(inode, dir, mode);
4668         inode_set_bytes(inode, 0);
4669         inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4670         inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4671                                   struct btrfs_inode_item);
4672         fill_inode_item(trans, path->nodes[0], inode_item, inode);
4673
4674         ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
4675                              struct btrfs_inode_ref);
4676         btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
4677         btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
4678         ptr = (unsigned long)(ref + 1);
4679         write_extent_buffer(path->nodes[0], name, ptr, name_len);
4680
4681         btrfs_mark_buffer_dirty(path->nodes[0]);
4682         btrfs_free_path(path);
4683
4684         location = &BTRFS_I(inode)->location;
4685         location->objectid = objectid;
4686         location->offset = 0;
4687         btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
4688
4689         btrfs_inherit_iflags(inode, dir);
4690
4691         if (S_ISREG(mode)) {
4692                 if (btrfs_test_opt(root, NODATASUM))
4693                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
4694                 if (btrfs_test_opt(root, NODATACOW) ||
4695                     (BTRFS_I(dir)->flags & BTRFS_INODE_NODATACOW))
4696                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
4697         }
4698
4699         insert_inode_hash(inode);
4700         inode_tree_add(inode);
4701
4702         trace_btrfs_inode_new(inode);
4703         btrfs_set_inode_last_trans(trans, inode);
4704
4705         return inode;
4706 fail:
4707         if (dir)
4708                 BTRFS_I(dir)->index_cnt--;
4709         btrfs_free_path(path);
4710         iput(inode);
4711         return ERR_PTR(ret);
4712 }
4713
4714 static inline u8 btrfs_inode_type(struct inode *inode)
4715 {
4716         return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
4717 }
4718
4719 /*
4720  * utility function to add 'inode' into 'parent_inode' with
4721  * a give name and a given sequence number.
4722  * if 'add_backref' is true, also insert a backref from the
4723  * inode to the parent directory.
4724  */
4725 int btrfs_add_link(struct btrfs_trans_handle *trans,
4726                    struct inode *parent_inode, struct inode *inode,
4727                    const char *name, int name_len, int add_backref, u64 index)
4728 {
4729         int ret = 0;
4730         struct btrfs_key key;
4731         struct btrfs_root *root = BTRFS_I(parent_inode)->root;
4732         u64 ino = btrfs_ino(inode);
4733         u64 parent_ino = btrfs_ino(parent_inode);
4734
4735         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4736                 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
4737         } else {
4738                 key.objectid = ino;
4739                 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
4740                 key.offset = 0;
4741         }
4742
4743         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4744                 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
4745                                          key.objectid, root->root_key.objectid,
4746                                          parent_ino, index, name, name_len);
4747         } else if (add_backref) {
4748                 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
4749                                              parent_ino, index);
4750         }
4751
4752         /* Nothing to clean up yet */
4753         if (ret)
4754                 return ret;
4755
4756         ret = btrfs_insert_dir_item(trans, root, name, name_len,
4757                                     parent_inode, &key,
4758                                     btrfs_inode_type(inode), index);
4759         if (ret == -EEXIST)
4760                 goto fail_dir_item;
4761         else if (ret) {
4762                 btrfs_abort_transaction(trans, root, ret);
4763                 return ret;
4764         }
4765
4766         btrfs_i_size_write(parent_inode, parent_inode->i_size +
4767                            name_len * 2);
4768         inode_inc_iversion(parent_inode);
4769         parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
4770         ret = btrfs_update_inode(trans, root, parent_inode);
4771         if (ret)
4772                 btrfs_abort_transaction(trans, root, ret);
4773         return ret;
4774
4775 fail_dir_item:
4776         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4777                 u64 local_index;
4778                 int err;
4779                 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
4780                                  key.objectid, root->root_key.objectid,
4781                                  parent_ino, &local_index, name, name_len);
4782
4783         } else if (add_backref) {
4784                 u64 local_index;
4785                 int err;
4786
4787                 err = btrfs_del_inode_ref(trans, root, name, name_len,
4788                                           ino, parent_ino, &local_index);
4789         }
4790         return ret;
4791 }
4792
4793 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
4794                             struct inode *dir, struct dentry *dentry,
4795                             struct inode *inode, int backref, u64 index)
4796 {
4797         int err = btrfs_add_link(trans, dir, inode,
4798                                  dentry->d_name.name, dentry->d_name.len,
4799                                  backref, index);
4800         if (err > 0)
4801                 err = -EEXIST;
4802         return err;
4803 }
4804
4805 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
4806                         umode_t mode, dev_t rdev)
4807 {
4808         struct btrfs_trans_handle *trans;
4809         struct btrfs_root *root = BTRFS_I(dir)->root;
4810         struct inode *inode = NULL;
4811         int err;
4812         int drop_inode = 0;
4813         u64 objectid;
4814         unsigned long nr = 0;
4815         u64 index = 0;
4816
4817         if (!new_valid_dev(rdev))
4818                 return -EINVAL;
4819
4820         /*
4821          * 2 for inode item and ref
4822          * 2 for dir items
4823          * 1 for xattr if selinux is on
4824          */
4825         trans = btrfs_start_transaction(root, 5);
4826         if (IS_ERR(trans))
4827                 return PTR_ERR(trans);
4828
4829         err = btrfs_find_free_ino(root, &objectid);
4830         if (err)
4831                 goto out_unlock;
4832
4833         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4834                                 dentry->d_name.len, btrfs_ino(dir), objectid,
4835                                 mode, &index);
4836         if (IS_ERR(inode)) {
4837                 err = PTR_ERR(inode);
4838                 goto out_unlock;
4839         }
4840
4841         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
4842         if (err) {
4843                 drop_inode = 1;
4844                 goto out_unlock;
4845         }
4846
4847         /*
4848         * If the active LSM wants to access the inode during
4849         * d_instantiate it needs these. Smack checks to see
4850         * if the filesystem supports xattrs by looking at the
4851         * ops vector.
4852         */
4853
4854         inode->i_op = &btrfs_special_inode_operations;
4855         err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
4856         if (err)
4857                 drop_inode = 1;
4858         else {
4859                 init_special_inode(inode, inode->i_mode, rdev);
4860                 btrfs_update_inode(trans, root, inode);
4861                 d_instantiate(dentry, inode);
4862         }
4863 out_unlock:
4864         nr = trans->blocks_used;
4865         btrfs_end_transaction(trans, root);
4866         btrfs_btree_balance_dirty(root, nr);
4867         if (drop_inode) {
4868                 inode_dec_link_count(inode);
4869                 iput(inode);
4870         }
4871         return err;
4872 }
4873
4874 static int btrfs_create(struct inode *dir, struct dentry *dentry,
4875                         umode_t mode, struct nameidata *nd)
4876 {
4877         struct btrfs_trans_handle *trans;
4878         struct btrfs_root *root = BTRFS_I(dir)->root;
4879         struct inode *inode = NULL;
4880         int drop_inode = 0;
4881         int err;
4882         unsigned long nr = 0;
4883         u64 objectid;
4884         u64 index = 0;
4885
4886         /*
4887          * 2 for inode item and ref
4888          * 2 for dir items
4889          * 1 for xattr if selinux is on
4890          */
4891         trans = btrfs_start_transaction(root, 5);
4892         if (IS_ERR(trans))
4893                 return PTR_ERR(trans);
4894
4895         err = btrfs_find_free_ino(root, &objectid);
4896         if (err)
4897                 goto out_unlock;
4898
4899         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4900                                 dentry->d_name.len, btrfs_ino(dir), objectid,
4901                                 mode, &index);
4902         if (IS_ERR(inode)) {
4903                 err = PTR_ERR(inode);
4904                 goto out_unlock;
4905         }
4906
4907         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
4908         if (err) {
4909                 drop_inode = 1;
4910                 goto out_unlock;
4911         }
4912
4913         /*
4914         * If the active LSM wants to access the inode during
4915         * d_instantiate it needs these. Smack checks to see
4916         * if the filesystem supports xattrs by looking at the
4917         * ops vector.
4918         */
4919         inode->i_fop = &btrfs_file_operations;
4920         inode->i_op = &btrfs_file_inode_operations;
4921
4922         err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
4923         if (err)
4924                 drop_inode = 1;
4925         else {
4926                 inode->i_mapping->a_ops = &btrfs_aops;
4927                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
4928                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
4929                 d_instantiate(dentry, inode);
4930         }
4931 out_unlock:
4932         nr = trans->blocks_used;
4933         btrfs_end_transaction(trans, root);
4934         if (drop_inode) {
4935                 inode_dec_link_count(inode);
4936                 iput(inode);
4937         }
4938         btrfs_btree_balance_dirty(root, nr);
4939         return err;
4940 }
4941
4942 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
4943                       struct dentry *dentry)
4944 {
4945         struct btrfs_trans_handle *trans;
4946         struct btrfs_root *root = BTRFS_I(dir)->root;
4947         struct inode *inode = old_dentry->d_inode;
4948         u64 index;
4949         unsigned long nr = 0;
4950         int err;
4951         int drop_inode = 0;
4952
4953         /* do not allow sys_link's with other subvols of the same device */
4954         if (root->objectid != BTRFS_I(inode)->root->objectid)
4955                 return -EXDEV;
4956
4957         if (inode->i_nlink == ~0U)
4958                 return -EMLINK;
4959
4960         err = btrfs_set_inode_index(dir, &index);
4961         if (err)
4962                 goto fail;
4963
4964         /*
4965          * 2 items for inode and inode ref
4966          * 2 items for dir items
4967          * 1 item for parent inode
4968          */
4969         trans = btrfs_start_transaction(root, 5);
4970         if (IS_ERR(trans)) {
4971                 err = PTR_ERR(trans);
4972                 goto fail;
4973         }
4974
4975         btrfs_inc_nlink(inode);
4976         inode_inc_iversion(inode);
4977         inode->i_ctime = CURRENT_TIME;
4978         ihold(inode);
4979
4980         err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
4981
4982         if (err) {
4983                 drop_inode = 1;
4984         } else {
4985                 struct dentry *parent = dentry->d_parent;
4986                 err = btrfs_update_inode(trans, root, inode);
4987                 if (err)
4988                         goto fail;
4989                 d_instantiate(dentry, inode);
4990                 btrfs_log_new_name(trans, inode, NULL, parent);
4991         }
4992
4993         nr = trans->blocks_used;
4994         btrfs_end_transaction(trans, root);
4995 fail:
4996         if (drop_inode) {
4997                 inode_dec_link_count(inode);
4998                 iput(inode);
4999         }
5000         btrfs_btree_balance_dirty(root, nr);
5001         return err;
5002 }
5003
5004 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
5005 {
5006         struct inode *inode = NULL;
5007         struct btrfs_trans_handle *trans;
5008         struct btrfs_root *root = BTRFS_I(dir)->root;
5009         int err = 0;
5010         int drop_on_err = 0;
5011         u64 objectid = 0;
5012         u64 index = 0;
5013         unsigned long nr = 1;
5014
5015         /*
5016          * 2 items for inode and ref
5017          * 2 items for dir items
5018          * 1 for xattr if selinux is on
5019          */
5020         trans = btrfs_start_transaction(root, 5);
5021         if (IS_ERR(trans))
5022                 return PTR_ERR(trans);
5023
5024         err = btrfs_find_free_ino(root, &objectid);
5025         if (err)
5026                 goto out_fail;
5027
5028         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5029                                 dentry->d_name.len, btrfs_ino(dir), objectid,
5030                                 S_IFDIR | mode, &index);
5031         if (IS_ERR(inode)) {
5032                 err = PTR_ERR(inode);
5033                 goto out_fail;
5034         }
5035
5036         drop_on_err = 1;
5037
5038         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5039         if (err)
5040                 goto out_fail;
5041
5042         inode->i_op = &btrfs_dir_inode_operations;
5043         inode->i_fop = &btrfs_dir_file_operations;
5044
5045         btrfs_i_size_write(inode, 0);
5046         err = btrfs_update_inode(trans, root, inode);
5047         if (err)
5048                 goto out_fail;
5049
5050         err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
5051                              dentry->d_name.len, 0, index);
5052         if (err)
5053                 goto out_fail;
5054
5055         d_instantiate(dentry, inode);
5056         drop_on_err = 0;
5057
5058 out_fail:
5059         nr = trans->blocks_used;
5060         btrfs_end_transaction(trans, root);
5061         if (drop_on_err)
5062                 iput(inode);
5063         btrfs_btree_balance_dirty(root, nr);
5064         return err;
5065 }
5066
5067 /* helper for btfs_get_extent.  Given an existing extent in the tree,
5068  * and an extent that you want to insert, deal with overlap and insert
5069  * the new extent into the tree.
5070  */
5071 static int merge_extent_mapping(struct extent_map_tree *em_tree,
5072                                 struct extent_map *existing,
5073                                 struct extent_map *em,
5074                                 u64 map_start, u64 map_len)
5075 {
5076         u64 start_diff;
5077
5078         BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
5079         start_diff = map_start - em->start;
5080         em->start = map_start;
5081         em->len = map_len;
5082         if (em->block_start < EXTENT_MAP_LAST_BYTE &&
5083             !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
5084                 em->block_start += start_diff;
5085                 em->block_len -= start_diff;
5086         }
5087         return add_extent_mapping(em_tree, em);
5088 }
5089
5090 static noinline int uncompress_inline(struct btrfs_path *path,
5091                                       struct inode *inode, struct page *page,
5092                                       size_t pg_offset, u64 extent_offset,
5093                                       struct btrfs_file_extent_item *item)
5094 {
5095         int ret;
5096         struct extent_buffer *leaf = path->nodes[0];
5097         char *tmp;
5098         size_t max_size;
5099         unsigned long inline_size;
5100         unsigned long ptr;
5101         int compress_type;
5102
5103         WARN_ON(pg_offset != 0);
5104         compress_type = btrfs_file_extent_compression(leaf, item);
5105         max_size = btrfs_file_extent_ram_bytes(leaf, item);
5106         inline_size = btrfs_file_extent_inline_item_len(leaf,
5107                                         btrfs_item_nr(leaf, path->slots[0]));
5108         tmp = kmalloc(inline_size, GFP_NOFS);
5109         if (!tmp)
5110                 return -ENOMEM;
5111         ptr = btrfs_file_extent_inline_start(item);
5112
5113         read_extent_buffer(leaf, tmp, ptr, inline_size);
5114
5115         max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
5116         ret = btrfs_decompress(compress_type, tmp, page,
5117                                extent_offset, inline_size, max_size);
5118         if (ret) {
5119                 char *kaddr = kmap_atomic(page);
5120                 unsigned long copy_size = min_t(u64,
5121                                   PAGE_CACHE_SIZE - pg_offset,
5122                                   max_size - extent_offset);
5123                 memset(kaddr + pg_offset, 0, copy_size);
5124                 kunmap_atomic(kaddr);
5125         }
5126         kfree(tmp);
5127         return 0;
5128 }
5129
5130 /*
5131  * a bit scary, this does extent mapping from logical file offset to the disk.
5132  * the ugly parts come from merging extents from the disk with the in-ram
5133  * representation.  This gets more complex because of the data=ordered code,
5134  * where the in-ram extents might be locked pending data=ordered completion.
5135  *
5136  * This also copies inline extents directly into the page.
5137  */
5138
5139 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
5140                                     size_t pg_offset, u64 start, u64 len,
5141                                     int create)
5142 {
5143         int ret;
5144         int err = 0;
5145         u64 bytenr;
5146         u64 extent_start = 0;
5147         u64 extent_end = 0;
5148         u64 objectid = btrfs_ino(inode);
5149         u32 found_type;
5150         struct btrfs_path *path = NULL;
5151         struct btrfs_root *root = BTRFS_I(inode)->root;
5152         struct btrfs_file_extent_item *item;
5153         struct extent_buffer *leaf;
5154         struct btrfs_key found_key;
5155         struct extent_map *em = NULL;
5156         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5157         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5158         struct btrfs_trans_handle *trans = NULL;
5159         int compress_type;
5160
5161 again:
5162         read_lock(&em_tree->lock);
5163         em = lookup_extent_mapping(em_tree, start, len);
5164         if (em)
5165                 em->bdev = root->fs_info->fs_devices->latest_bdev;
5166         read_unlock(&em_tree->lock);
5167
5168         if (em) {
5169                 if (em->start > start || em->start + em->len <= start)
5170                         free_extent_map(em);
5171                 else if (em->block_start == EXTENT_MAP_INLINE && page)
5172                         free_extent_map(em);
5173                 else
5174                         goto out;
5175         }
5176         em = alloc_extent_map();
5177         if (!em) {
5178                 err = -ENOMEM;
5179                 goto out;
5180         }
5181         em->bdev = root->fs_info->fs_devices->latest_bdev;
5182         em->start = EXTENT_MAP_HOLE;
5183         em->orig_start = EXTENT_MAP_HOLE;
5184         em->len = (u64)-1;
5185         em->block_len = (u64)-1;
5186
5187         if (!path) {
5188                 path = btrfs_alloc_path();
5189                 if (!path) {
5190                         err = -ENOMEM;
5191                         goto out;
5192                 }
5193                 /*
5194                  * Chances are we'll be called again, so go ahead and do
5195                  * readahead
5196                  */
5197                 path->reada = 1;
5198         }
5199
5200         ret = btrfs_lookup_file_extent(trans, root, path,
5201                                        objectid, start, trans != NULL);
5202         if (ret < 0) {
5203                 err = ret;
5204                 goto out;
5205         }
5206
5207         if (ret != 0) {
5208                 if (path->slots[0] == 0)
5209                         goto not_found;
5210                 path->slots[0]--;
5211         }
5212
5213         leaf = path->nodes[0];
5214         item = btrfs_item_ptr(leaf, path->slots[0],
5215                               struct btrfs_file_extent_item);
5216         /* are we inside the extent that was found? */
5217         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5218         found_type = btrfs_key_type(&found_key);
5219         if (found_key.objectid != objectid ||
5220             found_type != BTRFS_EXTENT_DATA_KEY) {
5221                 goto not_found;
5222         }
5223
5224         found_type = btrfs_file_extent_type(leaf, item);
5225         extent_start = found_key.offset;
5226         compress_type = btrfs_file_extent_compression(leaf, item);
5227         if (found_type == BTRFS_FILE_EXTENT_REG ||
5228             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5229                 extent_end = extent_start +
5230                        btrfs_file_extent_num_bytes(leaf, item);
5231         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5232                 size_t size;
5233                 size = btrfs_file_extent_inline_len(leaf, item);
5234                 extent_end = (extent_start + size + root->sectorsize - 1) &
5235                         ~((u64)root->sectorsize - 1);
5236         }
5237
5238         if (start >= extent_end) {
5239                 path->slots[0]++;
5240                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
5241                         ret = btrfs_next_leaf(root, path);
5242                         if (ret < 0) {
5243                                 err = ret;
5244                                 goto out;
5245                         }
5246                         if (ret > 0)
5247                                 goto not_found;
5248                         leaf = path->nodes[0];
5249                 }
5250                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5251                 if (found_key.objectid != objectid ||
5252                     found_key.type != BTRFS_EXTENT_DATA_KEY)
5253                         goto not_found;
5254                 if (start + len <= found_key.offset)
5255                         goto not_found;
5256                 em->start = start;
5257                 em->len = found_key.offset - start;
5258                 goto not_found_em;
5259         }
5260
5261         if (found_type == BTRFS_FILE_EXTENT_REG ||
5262             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5263                 em->start = extent_start;
5264                 em->len = extent_end - extent_start;
5265                 em->orig_start = extent_start -
5266                                  btrfs_file_extent_offset(leaf, item);
5267                 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
5268                 if (bytenr == 0) {
5269                         em->block_start = EXTENT_MAP_HOLE;
5270                         goto insert;
5271                 }
5272                 if (compress_type != BTRFS_COMPRESS_NONE) {
5273                         set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5274                         em->compress_type = compress_type;
5275                         em->block_start = bytenr;
5276                         em->block_len = btrfs_file_extent_disk_num_bytes(leaf,
5277                                                                          item);
5278                 } else {
5279                         bytenr += btrfs_file_extent_offset(leaf, item);
5280                         em->block_start = bytenr;
5281                         em->block_len = em->len;
5282                         if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
5283                                 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
5284                 }
5285                 goto insert;
5286         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5287                 unsigned long ptr;
5288                 char *map;
5289                 size_t size;
5290                 size_t extent_offset;
5291                 size_t copy_size;
5292
5293                 em->block_start = EXTENT_MAP_INLINE;
5294                 if (!page || create) {
5295                         em->start = extent_start;
5296                         em->len = extent_end - extent_start;
5297                         goto out;
5298                 }
5299
5300                 size = btrfs_file_extent_inline_len(leaf, item);
5301                 extent_offset = page_offset(page) + pg_offset - extent_start;
5302                 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
5303                                 size - extent_offset);
5304                 em->start = extent_start + extent_offset;
5305                 em->len = (copy_size + root->sectorsize - 1) &
5306                         ~((u64)root->sectorsize - 1);
5307                 em->orig_start = EXTENT_MAP_INLINE;
5308                 if (compress_type) {
5309                         set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5310                         em->compress_type = compress_type;
5311                 }
5312                 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
5313                 if (create == 0 && !PageUptodate(page)) {
5314                         if (btrfs_file_extent_compression(leaf, item) !=
5315                             BTRFS_COMPRESS_NONE) {
5316                                 ret = uncompress_inline(path, inode, page,
5317                                                         pg_offset,
5318                                                         extent_offset, item);
5319                                 BUG_ON(ret); /* -ENOMEM */
5320                         } else {
5321                                 map = kmap(page);
5322                                 read_extent_buffer(leaf, map + pg_offset, ptr,
5323                                                    copy_size);
5324                                 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
5325                                         memset(map + pg_offset + copy_size, 0,
5326                                                PAGE_CACHE_SIZE - pg_offset -
5327                                                copy_size);
5328                                 }
5329                                 kunmap(page);
5330                         }
5331                         flush_dcache_page(page);
5332                 } else if (create && PageUptodate(page)) {
5333                         BUG();
5334                         if (!trans) {
5335                                 kunmap(page);
5336                                 free_extent_map(em);
5337                                 em = NULL;
5338
5339                                 btrfs_release_path(path);
5340                                 trans = btrfs_join_transaction(root);
5341
5342                                 if (IS_ERR(trans))
5343                                         return ERR_CAST(trans);
5344                                 goto again;
5345                         }
5346                         map = kmap(page);
5347                         write_extent_buffer(leaf, map + pg_offset, ptr,
5348                                             copy_size);
5349                         kunmap(page);
5350                         btrfs_mark_buffer_dirty(leaf);
5351                 }
5352                 set_extent_uptodate(io_tree, em->start,
5353                                     extent_map_end(em) - 1, NULL, GFP_NOFS);
5354                 goto insert;
5355         } else {
5356                 printk(KERN_ERR "btrfs unknown found_type %d\n", found_type);
5357                 WARN_ON(1);
5358         }
5359 not_found:
5360         em->start = start;
5361         em->len = len;
5362 not_found_em:
5363         em->block_start = EXTENT_MAP_HOLE;
5364         set_bit(EXTENT_FLAG_VACANCY, &em->flags);
5365 insert:
5366         btrfs_release_path(path);
5367         if (em->start > start || extent_map_end(em) <= start) {
5368                 printk(KERN_ERR "Btrfs: bad extent! em: [%llu %llu] passed "
5369                        "[%llu %llu]\n", (unsigned long long)em->start,
5370                        (unsigned long long)em->len,
5371                        (unsigned long long)start,
5372                        (unsigned long long)len);
5373                 err = -EIO;
5374                 goto out;
5375         }
5376
5377         err = 0;
5378         write_lock(&em_tree->lock);
5379         ret = add_extent_mapping(em_tree, em);
5380         /* it is possible that someone inserted the extent into the tree
5381          * while we had the lock dropped.  It is also possible that
5382          * an overlapping map exists in the tree
5383          */
5384         if (ret == -EEXIST) {
5385                 struct extent_map *existing;
5386
5387                 ret = 0;
5388
5389                 existing = lookup_extent_mapping(em_tree, start, len);
5390                 if (existing && (existing->start > start ||
5391                     existing->start + existing->len <= start)) {
5392                         free_extent_map(existing);
5393                         existing = NULL;
5394                 }
5395                 if (!existing) {
5396                         existing = lookup_extent_mapping(em_tree, em->start,
5397                                                          em->len);
5398                         if (existing) {
5399                                 err = merge_extent_mapping(em_tree, existing,
5400                                                            em, start,
5401                                                            root->sectorsize);
5402                                 free_extent_map(existing);
5403                                 if (err) {
5404                                         free_extent_map(em);
5405                                         em = NULL;
5406                                 }
5407                         } else {
5408                                 err = -EIO;
5409                                 free_extent_map(em);
5410                                 em = NULL;
5411                         }
5412                 } else {
5413                         free_extent_map(em);
5414                         em = existing;
5415                         err = 0;
5416                 }
5417         }
5418         write_unlock(&em_tree->lock);
5419 out:
5420
5421         trace_btrfs_get_extent(root, em);
5422
5423         if (path)
5424                 btrfs_free_path(path);
5425         if (trans) {
5426                 ret = btrfs_end_transaction(trans, root);
5427                 if (!err)
5428                         err = ret;
5429         }
5430         if (err) {
5431                 free_extent_map(em);
5432                 return ERR_PTR(err);
5433         }
5434         BUG_ON(!em); /* Error is always set */
5435         return em;
5436 }
5437
5438 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
5439                                            size_t pg_offset, u64 start, u64 len,
5440                                            int create)
5441 {
5442         struct extent_map *em;
5443         struct extent_map *hole_em = NULL;
5444         u64 range_start = start;
5445         u64 end;
5446         u64 found;
5447         u64 found_end;
5448         int err = 0;
5449
5450         em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
5451         if (IS_ERR(em))
5452                 return em;
5453         if (em) {
5454                 /*
5455                  * if our em maps to a hole, there might
5456                  * actually be delalloc bytes behind it
5457                  */
5458                 if (em->block_start != EXTENT_MAP_HOLE)
5459                         return em;
5460                 else
5461                         hole_em = em;
5462         }
5463
5464         /* check to see if we've wrapped (len == -1 or similar) */
5465         end = start + len;
5466         if (end < start)
5467                 end = (u64)-1;
5468         else
5469                 end -= 1;
5470
5471         em = NULL;
5472
5473         /* ok, we didn't find anything, lets look for delalloc */
5474         found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
5475                                  end, len, EXTENT_DELALLOC, 1);
5476         found_end = range_start + found;
5477         if (found_end < range_start)
5478                 found_end = (u64)-1;
5479
5480         /*
5481          * we didn't find anything useful, return
5482          * the original results from get_extent()
5483          */
5484         if (range_start > end || found_end <= start) {
5485                 em = hole_em;
5486                 hole_em = NULL;
5487                 goto out;
5488         }
5489
5490         /* adjust the range_start to make sure it doesn't
5491          * go backwards from the start they passed in
5492          */
5493         range_start = max(start,range_start);
5494         found = found_end - range_start;
5495
5496         if (found > 0) {
5497                 u64 hole_start = start;
5498                 u64 hole_len = len;
5499
5500                 em = alloc_extent_map();
5501                 if (!em) {
5502                         err = -ENOMEM;
5503                         goto out;
5504                 }
5505                 /*
5506                  * when btrfs_get_extent can't find anything it
5507                  * returns one huge hole
5508                  *
5509                  * make sure what it found really fits our range, and
5510                  * adjust to make sure it is based on the start from
5511                  * the caller
5512                  */
5513                 if (hole_em) {
5514                         u64 calc_end = extent_map_end(hole_em);
5515
5516                         if (calc_end <= start || (hole_em->start > end)) {
5517                                 free_extent_map(hole_em);
5518                                 hole_em = NULL;
5519                         } else {
5520                                 hole_start = max(hole_em->start, start);
5521                                 hole_len = calc_end - hole_start;
5522                         }
5523                 }
5524                 em->bdev = NULL;
5525                 if (hole_em && range_start > hole_start) {
5526                         /* our hole starts before our delalloc, so we
5527                          * have to return just the parts of the hole
5528                          * that go until  the delalloc starts
5529                          */
5530                         em->len = min(hole_len,
5531                                       range_start - hole_start);
5532                         em->start = hole_start;
5533                         em->orig_start = hole_start;
5534                         /*
5535                          * don't adjust block start at all,
5536                          * it is fixed at EXTENT_MAP_HOLE
5537                          */
5538                         em->block_start = hole_em->block_start;
5539                         em->block_len = hole_len;
5540                 } else {
5541                         em->start = range_start;
5542                         em->len = found;
5543                         em->orig_start = range_start;
5544                         em->block_start = EXTENT_MAP_DELALLOC;
5545                         em->block_len = found;
5546                 }
5547         } else if (hole_em) {
5548                 return hole_em;
5549         }
5550 out:
5551
5552         free_extent_map(hole_em);
5553         if (err) {
5554                 free_extent_map(em);
5555                 return ERR_PTR(err);
5556         }
5557         return em;
5558 }
5559
5560 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
5561                                                   struct extent_map *em,
5562                                                   u64 start, u64 len)
5563 {
5564         struct btrfs_root *root = BTRFS_I(inode)->root;
5565         struct btrfs_trans_handle *trans;
5566         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5567         struct btrfs_key ins;
5568         u64 alloc_hint;
5569         int ret;
5570         bool insert = false;
5571
5572         /*
5573          * Ok if the extent map we looked up is a hole and is for the exact
5574          * range we want, there is no reason to allocate a new one, however if
5575          * it is not right then we need to free this one and drop the cache for
5576          * our range.
5577          */
5578         if (em->block_start != EXTENT_MAP_HOLE || em->start != start ||
5579             em->len != len) {
5580                 free_extent_map(em);
5581                 em = NULL;
5582                 insert = true;
5583                 btrfs_drop_extent_cache(inode, start, start + len - 1, 0);
5584         }
5585
5586         trans = btrfs_join_transaction(root);
5587         if (IS_ERR(trans))
5588                 return ERR_CAST(trans);
5589
5590         if (start <= BTRFS_I(inode)->disk_i_size && len < 64 * 1024)
5591                 btrfs_add_inode_defrag(trans, inode);
5592
5593         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5594
5595         alloc_hint = get_extent_allocation_hint(inode, start, len);
5596         ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
5597                                    alloc_hint, &ins, 1);
5598         if (ret) {
5599                 em = ERR_PTR(ret);
5600                 goto out;
5601         }
5602
5603         if (!em) {
5604                 em = alloc_extent_map();
5605                 if (!em) {
5606                         em = ERR_PTR(-ENOMEM);
5607                         goto out;
5608                 }
5609         }
5610
5611         em->start = start;
5612         em->orig_start = em->start;
5613         em->len = ins.offset;
5614
5615         em->block_start = ins.objectid;
5616         em->block_len = ins.offset;
5617         em->bdev = root->fs_info->fs_devices->latest_bdev;
5618
5619         /*
5620          * We need to do this because if we're using the original em we searched
5621          * for, we could have EXTENT_FLAG_VACANCY set, and we don't want that.
5622          */
5623         em->flags = 0;
5624         set_bit(EXTENT_FLAG_PINNED, &em->flags);
5625
5626         while (insert) {
5627                 write_lock(&em_tree->lock);
5628                 ret = add_extent_mapping(em_tree, em);
5629                 write_unlock(&em_tree->lock);
5630                 if (ret != -EEXIST)
5631                         break;
5632                 btrfs_drop_extent_cache(inode, start, start + em->len - 1, 0);
5633         }
5634
5635         ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
5636                                            ins.offset, ins.offset, 0);
5637         if (ret) {
5638                 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
5639                 em = ERR_PTR(ret);
5640         }
5641 out:
5642         btrfs_end_transaction(trans, root);
5643         return em;
5644 }
5645
5646 /*
5647  * returns 1 when the nocow is safe, < 1 on error, 0 if the
5648  * block must be cow'd
5649  */
5650 static noinline int can_nocow_odirect(struct btrfs_trans_handle *trans,
5651                                       struct inode *inode, u64 offset, u64 len)
5652 {
5653         struct btrfs_path *path;
5654         int ret;
5655         struct extent_buffer *leaf;
5656         struct btrfs_root *root = BTRFS_I(inode)->root;
5657         struct btrfs_file_extent_item *fi;
5658         struct btrfs_key key;
5659         u64 disk_bytenr;
5660         u64 backref_offset;
5661         u64 extent_end;
5662         u64 num_bytes;
5663         int slot;
5664         int found_type;
5665
5666         path = btrfs_alloc_path();
5667         if (!path)
5668                 return -ENOMEM;
5669
5670         ret = btrfs_lookup_file_extent(trans, root, path, btrfs_ino(inode),
5671                                        offset, 0);
5672         if (ret < 0)
5673                 goto out;
5674
5675         slot = path->slots[0];
5676         if (ret == 1) {
5677                 if (slot == 0) {
5678                         /* can't find the item, must cow */
5679                         ret = 0;
5680                         goto out;
5681                 }
5682                 slot--;
5683         }
5684         ret = 0;
5685         leaf = path->nodes[0];
5686         btrfs_item_key_to_cpu(leaf, &key, slot);
5687         if (key.objectid != btrfs_ino(inode) ||
5688             key.type != BTRFS_EXTENT_DATA_KEY) {
5689                 /* not our file or wrong item type, must cow */
5690                 goto out;
5691         }
5692
5693         if (key.offset > offset) {
5694                 /* Wrong offset, must cow */
5695                 goto out;
5696         }
5697
5698         fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5699         found_type = btrfs_file_extent_type(leaf, fi);
5700         if (found_type != BTRFS_FILE_EXTENT_REG &&
5701             found_type != BTRFS_FILE_EXTENT_PREALLOC) {
5702                 /* not a regular extent, must cow */
5703                 goto out;
5704         }
5705         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
5706         backref_offset = btrfs_file_extent_offset(leaf, fi);
5707
5708         extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
5709         if (extent_end < offset + len) {
5710                 /* extent doesn't include our full range, must cow */
5711                 goto out;
5712         }
5713
5714         if (btrfs_extent_readonly(root, disk_bytenr))
5715                 goto out;
5716
5717         /*
5718          * look for other files referencing this extent, if we
5719          * find any we must cow
5720          */
5721         if (btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
5722                                   key.offset - backref_offset, disk_bytenr))
5723                 goto out;
5724
5725         /*
5726          * adjust disk_bytenr and num_bytes to cover just the bytes
5727          * in this extent we are about to write.  If there
5728          * are any csums in that range we have to cow in order
5729          * to keep the csums correct
5730          */
5731         disk_bytenr += backref_offset;
5732         disk_bytenr += offset - key.offset;
5733         num_bytes = min(offset + len, extent_end) - offset;
5734         if (csum_exist_in_range(root, disk_bytenr, num_bytes))
5735                                 goto out;
5736         /*
5737          * all of the above have passed, it is safe to overwrite this extent
5738          * without cow
5739          */
5740         ret = 1;
5741 out:
5742         btrfs_free_path(path);
5743         return ret;
5744 }
5745
5746 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
5747                                    struct buffer_head *bh_result, int create)
5748 {
5749         struct extent_map *em;
5750         struct btrfs_root *root = BTRFS_I(inode)->root;
5751         u64 start = iblock << inode->i_blkbits;
5752         u64 len = bh_result->b_size;
5753         struct btrfs_trans_handle *trans;
5754
5755         em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
5756         if (IS_ERR(em))
5757                 return PTR_ERR(em);
5758
5759         /*
5760          * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
5761          * io.  INLINE is special, and we could probably kludge it in here, but
5762          * it's still buffered so for safety lets just fall back to the generic
5763          * buffered path.
5764          *
5765          * For COMPRESSED we _have_ to read the entire extent in so we can
5766          * decompress it, so there will be buffering required no matter what we
5767          * do, so go ahead and fallback to buffered.
5768          *
5769          * We return -ENOTBLK because thats what makes DIO go ahead and go back
5770          * to buffered IO.  Don't blame me, this is the price we pay for using
5771          * the generic code.
5772          */
5773         if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
5774             em->block_start == EXTENT_MAP_INLINE) {
5775                 free_extent_map(em);
5776                 return -ENOTBLK;
5777         }
5778
5779         /* Just a good old fashioned hole, return */
5780         if (!create && (em->block_start == EXTENT_MAP_HOLE ||
5781                         test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
5782                 free_extent_map(em);
5783                 /* DIO will do one hole at a time, so just unlock a sector */
5784                 unlock_extent(&BTRFS_I(inode)->io_tree, start,
5785                               start + root->sectorsize - 1);
5786                 return 0;
5787         }
5788
5789         /*
5790          * We don't allocate a new extent in the following cases
5791          *
5792          * 1) The inode is marked as NODATACOW.  In this case we'll just use the
5793          * existing extent.
5794          * 2) The extent is marked as PREALLOC.  We're good to go here and can
5795          * just use the extent.
5796          *
5797          */
5798         if (!create) {
5799                 len = em->len - (start - em->start);
5800                 goto map;
5801         }
5802
5803         if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
5804             ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
5805              em->block_start != EXTENT_MAP_HOLE)) {
5806                 int type;
5807                 int ret;
5808                 u64 block_start;
5809
5810                 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5811                         type = BTRFS_ORDERED_PREALLOC;
5812                 else
5813                         type = BTRFS_ORDERED_NOCOW;
5814                 len = min(len, em->len - (start - em->start));
5815                 block_start = em->block_start + (start - em->start);
5816
5817                 /*
5818                  * we're not going to log anything, but we do need
5819                  * to make sure the current transaction stays open
5820                  * while we look for nocow cross refs
5821                  */
5822                 trans = btrfs_join_transaction(root);
5823                 if (IS_ERR(trans))
5824                         goto must_cow;
5825
5826                 if (can_nocow_odirect(trans, inode, start, len) == 1) {
5827                         ret = btrfs_add_ordered_extent_dio(inode, start,
5828                                            block_start, len, len, type);
5829                         btrfs_end_transaction(trans, root);
5830                         if (ret) {
5831                                 free_extent_map(em);
5832                                 return ret;
5833                         }
5834                         goto unlock;
5835                 }
5836                 btrfs_end_transaction(trans, root);
5837         }
5838 must_cow:
5839         /*
5840          * this will cow the extent, reset the len in case we changed
5841          * it above
5842          */
5843         len = bh_result->b_size;
5844         em = btrfs_new_extent_direct(inode, em, start, len);
5845         if (IS_ERR(em))
5846                 return PTR_ERR(em);
5847         len = min(len, em->len - (start - em->start));
5848 unlock:
5849         clear_extent_bit(&BTRFS_I(inode)->io_tree, start, start + len - 1,
5850                           EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DIRTY, 1,
5851                           0, NULL, GFP_NOFS);
5852 map:
5853         bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
5854                 inode->i_blkbits;
5855         bh_result->b_size = len;
5856         bh_result->b_bdev = em->bdev;
5857         set_buffer_mapped(bh_result);
5858         if (create && !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5859                 set_buffer_new(bh_result);
5860
5861         free_extent_map(em);
5862
5863         return 0;
5864 }
5865
5866 struct btrfs_dio_private {
5867         struct inode *inode;
5868         u64 logical_offset;
5869         u64 disk_bytenr;
5870         u64 bytes;
5871         u32 *csums;
5872         void *private;
5873
5874         /* number of bios pending for this dio */
5875         atomic_t pending_bios;
5876
5877         /* IO errors */
5878         int errors;
5879
5880         struct bio *orig_bio;
5881 };
5882
5883 static void btrfs_endio_direct_read(struct bio *bio, int err)
5884 {
5885         struct btrfs_dio_private *dip = bio->bi_private;
5886         struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
5887         struct bio_vec *bvec = bio->bi_io_vec;
5888         struct inode *inode = dip->inode;
5889         struct btrfs_root *root = BTRFS_I(inode)->root;
5890         u64 start;
5891         u32 *private = dip->csums;
5892
5893         start = dip->logical_offset;
5894         do {
5895                 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
5896                         struct page *page = bvec->bv_page;
5897                         char *kaddr;
5898                         u32 csum = ~(u32)0;
5899                         unsigned long flags;
5900
5901                         local_irq_save(flags);
5902                         kaddr = kmap_atomic(page);
5903                         csum = btrfs_csum_data(root, kaddr + bvec->bv_offset,
5904                                                csum, bvec->bv_len);
5905                         btrfs_csum_final(csum, (char *)&csum);
5906                         kunmap_atomic(kaddr);
5907                         local_irq_restore(flags);
5908
5909                         flush_dcache_page(bvec->bv_page);
5910                         if (csum != *private) {
5911                                 printk(KERN_ERR "btrfs csum failed ino %llu off"
5912                                       " %llu csum %u private %u\n",
5913                                       (unsigned long long)btrfs_ino(inode),
5914                                       (unsigned long long)start,
5915                                       csum, *private);
5916                                 err = -EIO;
5917                         }
5918                 }
5919
5920                 start += bvec->bv_len;
5921                 private++;
5922                 bvec++;
5923         } while (bvec <= bvec_end);
5924
5925         unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
5926                       dip->logical_offset + dip->bytes - 1);
5927         bio->bi_private = dip->private;
5928
5929         kfree(dip->csums);
5930         kfree(dip);
5931
5932         /* If we had a csum failure make sure to clear the uptodate flag */
5933         if (err)
5934                 clear_bit(BIO_UPTODATE, &bio->bi_flags);
5935         dio_end_io(bio, err);
5936 }
5937
5938 static void btrfs_endio_direct_write(struct bio *bio, int err)
5939 {
5940         struct btrfs_dio_private *dip = bio->bi_private;
5941         struct inode *inode = dip->inode;
5942         struct btrfs_root *root = BTRFS_I(inode)->root;
5943         struct btrfs_ordered_extent *ordered = NULL;
5944         u64 ordered_offset = dip->logical_offset;
5945         u64 ordered_bytes = dip->bytes;
5946         int ret;
5947
5948         if (err)
5949                 goto out_done;
5950 again:
5951         ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
5952                                                    &ordered_offset,
5953                                                    ordered_bytes, !err);
5954         if (!ret)
5955                 goto out_test;
5956
5957         ordered->work.func = finish_ordered_fn;
5958         ordered->work.flags = 0;
5959         btrfs_queue_worker(&root->fs_info->endio_write_workers,
5960                            &ordered->work);
5961 out_test:
5962         /*
5963          * our bio might span multiple ordered extents.  If we haven't
5964          * completed the accounting for the whole dio, go back and try again
5965          */
5966         if (ordered_offset < dip->logical_offset + dip->bytes) {
5967                 ordered_bytes = dip->logical_offset + dip->bytes -
5968                         ordered_offset;
5969                 ordered = NULL;
5970                 goto again;
5971         }
5972 out_done:
5973         bio->bi_private = dip->private;
5974
5975         kfree(dip);
5976
5977         /* If we had an error make sure to clear the uptodate flag */
5978         if (err)
5979                 clear_bit(BIO_UPTODATE, &bio->bi_flags);
5980         dio_end_io(bio, err);
5981 }
5982
5983 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
5984                                     struct bio *bio, int mirror_num,
5985                                     unsigned long bio_flags, u64 offset)
5986 {
5987         int ret;
5988         struct btrfs_root *root = BTRFS_I(inode)->root;
5989         ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
5990         BUG_ON(ret); /* -ENOMEM */
5991         return 0;
5992 }
5993
5994 static void btrfs_end_dio_bio(struct bio *bio, int err)
5995 {
5996         struct btrfs_dio_private *dip = bio->bi_private;
5997
5998         if (err) {
5999                 printk(KERN_ERR "btrfs direct IO failed ino %llu rw %lu "
6000                       "sector %#Lx len %u err no %d\n",
6001                       (unsigned long long)btrfs_ino(dip->inode), bio->bi_rw,
6002                       (unsigned long long)bio->bi_sector, bio->bi_size, err);
6003                 dip->errors = 1;
6004
6005                 /*
6006                  * before atomic variable goto zero, we must make sure
6007                  * dip->errors is perceived to be set.
6008                  */
6009                 smp_mb__before_atomic_dec();
6010         }
6011
6012         /* if there are more bios still pending for this dio, just exit */
6013         if (!atomic_dec_and_test(&dip->pending_bios))
6014                 goto out;
6015
6016         if (dip->errors)
6017                 bio_io_error(dip->orig_bio);
6018         else {
6019                 set_bit(BIO_UPTODATE, &dip->orig_bio->bi_flags);
6020                 bio_endio(dip->orig_bio, 0);
6021         }
6022 out:
6023         bio_put(bio);
6024 }
6025
6026 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
6027                                        u64 first_sector, gfp_t gfp_flags)
6028 {
6029         int nr_vecs = bio_get_nr_vecs(bdev);
6030         return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
6031 }
6032
6033 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
6034                                          int rw, u64 file_offset, int skip_sum,
6035                                          u32 *csums, int async_submit)
6036 {
6037         int write = rw & REQ_WRITE;
6038         struct btrfs_root *root = BTRFS_I(inode)->root;
6039         int ret;
6040
6041         bio_get(bio);
6042
6043         if (!write) {
6044                 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
6045                 if (ret)
6046                         goto err;
6047         }
6048
6049         if (skip_sum)
6050                 goto map;
6051
6052         if (write && async_submit) {
6053                 ret = btrfs_wq_submit_bio(root->fs_info,
6054                                    inode, rw, bio, 0, 0,
6055                                    file_offset,
6056                                    __btrfs_submit_bio_start_direct_io,
6057                                    __btrfs_submit_bio_done);
6058                 goto err;
6059         } else if (write) {
6060                 /*
6061                  * If we aren't doing async submit, calculate the csum of the
6062                  * bio now.
6063                  */
6064                 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
6065                 if (ret)
6066                         goto err;
6067         } else if (!skip_sum) {
6068                 ret = btrfs_lookup_bio_sums_dio(root, inode, bio,
6069                                           file_offset, csums);
6070                 if (ret)
6071                         goto err;
6072         }
6073
6074 map:
6075         ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
6076 err:
6077         bio_put(bio);
6078         return ret;
6079 }
6080
6081 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
6082                                     int skip_sum)
6083 {
6084         struct inode *inode = dip->inode;
6085         struct btrfs_root *root = BTRFS_I(inode)->root;
6086         struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
6087         struct bio *bio;
6088         struct bio *orig_bio = dip->orig_bio;
6089         struct bio_vec *bvec = orig_bio->bi_io_vec;
6090         u64 start_sector = orig_bio->bi_sector;
6091         u64 file_offset = dip->logical_offset;
6092         u64 submit_len = 0;
6093         u64 map_length;
6094         int nr_pages = 0;
6095         u32 *csums = dip->csums;
6096         int ret = 0;
6097         int async_submit = 0;
6098         int write = rw & REQ_WRITE;
6099
6100         map_length = orig_bio->bi_size;
6101         ret = btrfs_map_block(map_tree, READ, start_sector << 9,
6102                               &map_length, NULL, 0);
6103         if (ret) {
6104                 bio_put(orig_bio);
6105                 return -EIO;
6106         }
6107
6108         if (map_length >= orig_bio->bi_size) {
6109                 bio = orig_bio;
6110                 goto submit;
6111         }
6112
6113         async_submit = 1;
6114         bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
6115         if (!bio)
6116                 return -ENOMEM;
6117         bio->bi_private = dip;
6118         bio->bi_end_io = btrfs_end_dio_bio;
6119         atomic_inc(&dip->pending_bios);
6120
6121         while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
6122                 if (unlikely(map_length < submit_len + bvec->bv_len ||
6123                     bio_add_page(bio, bvec->bv_page, bvec->bv_len,
6124                                  bvec->bv_offset) < bvec->bv_len)) {
6125                         /*
6126                          * inc the count before we submit the bio so
6127                          * we know the end IO handler won't happen before
6128                          * we inc the count. Otherwise, the dip might get freed
6129                          * before we're done setting it up
6130                          */
6131                         atomic_inc(&dip->pending_bios);
6132                         ret = __btrfs_submit_dio_bio(bio, inode, rw,
6133                                                      file_offset, skip_sum,
6134                                                      csums, async_submit);
6135                         if (ret) {
6136                                 bio_put(bio);
6137                                 atomic_dec(&dip->pending_bios);
6138                                 goto out_err;
6139                         }
6140
6141                         /* Write's use the ordered csums */
6142                         if (!write && !skip_sum)
6143                                 csums = csums + nr_pages;
6144                         start_sector += submit_len >> 9;
6145                         file_offset += submit_len;
6146
6147                         submit_len = 0;
6148                         nr_pages = 0;
6149
6150                         bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
6151                                                   start_sector, GFP_NOFS);
6152                         if (!bio)
6153                                 goto out_err;
6154                         bio->bi_private = dip;
6155                         bio->bi_end_io = btrfs_end_dio_bio;
6156
6157                         map_length = orig_bio->bi_size;
6158                         ret = btrfs_map_block(map_tree, READ, start_sector << 9,
6159                                               &map_length, NULL, 0);
6160                         if (ret) {
6161                                 bio_put(bio);
6162                                 goto out_err;
6163                         }
6164                 } else {
6165                         submit_len += bvec->bv_len;
6166                         nr_pages ++;
6167                         bvec++;
6168                 }
6169         }
6170
6171 submit:
6172         ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
6173                                      csums, async_submit);
6174         if (!ret)
6175                 return 0;
6176
6177         bio_put(bio);
6178 out_err:
6179         dip->errors = 1;
6180         /*
6181          * before atomic variable goto zero, we must
6182          * make sure dip->errors is perceived to be set.
6183          */
6184         smp_mb__before_atomic_dec();
6185         if (atomic_dec_and_test(&dip->pending_bios))
6186                 bio_io_error(dip->orig_bio);
6187
6188         /* bio_end_io() will handle error, so we needn't return it */
6189         return 0;
6190 }
6191
6192 static void btrfs_submit_direct(int rw, struct bio *bio, struct inode *inode,
6193                                 loff_t file_offset)
6194 {
6195         struct btrfs_root *root = BTRFS_I(inode)->root;
6196         struct btrfs_dio_private *dip;
6197         struct bio_vec *bvec = bio->bi_io_vec;
6198         int skip_sum;
6199         int write = rw & REQ_WRITE;
6200         int ret = 0;
6201
6202         skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
6203
6204         dip = kmalloc(sizeof(*dip), GFP_NOFS);
6205         if (!dip) {
6206                 ret = -ENOMEM;
6207                 goto free_ordered;
6208         }
6209         dip->csums = NULL;
6210
6211         /* Write's use the ordered csum stuff, so we don't need dip->csums */
6212         if (!write && !skip_sum) {
6213                 dip->csums = kmalloc(sizeof(u32) * bio->bi_vcnt, GFP_NOFS);
6214                 if (!dip->csums) {
6215                         kfree(dip);
6216                         ret = -ENOMEM;
6217                         goto free_ordered;
6218                 }
6219         }
6220
6221         dip->private = bio->bi_private;
6222         dip->inode = inode;
6223         dip->logical_offset = file_offset;
6224
6225         dip->bytes = 0;
6226         do {
6227                 dip->bytes += bvec->bv_len;
6228                 bvec++;
6229         } while (bvec <= (bio->bi_io_vec + bio->bi_vcnt - 1));
6230
6231         dip->disk_bytenr = (u64)bio->bi_sector << 9;
6232         bio->bi_private = dip;
6233         dip->errors = 0;
6234         dip->orig_bio = bio;
6235         atomic_set(&dip->pending_bios, 0);
6236
6237         if (write)
6238                 bio->bi_end_io = btrfs_endio_direct_write;
6239         else
6240                 bio->bi_end_io = btrfs_endio_direct_read;
6241
6242         ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
6243         if (!ret)
6244                 return;
6245 free_ordered:
6246         /*
6247          * If this is a write, we need to clean up the reserved space and kill
6248          * the ordered extent.
6249          */
6250         if (write) {
6251                 struct btrfs_ordered_extent *ordered;
6252                 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
6253                 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
6254                     !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
6255                         btrfs_free_reserved_extent(root, ordered->start,
6256                                                    ordered->disk_len);
6257                 btrfs_put_ordered_extent(ordered);
6258                 btrfs_put_ordered_extent(ordered);
6259         }
6260         bio_endio(bio, ret);
6261 }
6262
6263 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
6264                         const struct iovec *iov, loff_t offset,
6265                         unsigned long nr_segs)
6266 {
6267         int seg;
6268         int i;
6269         size_t size;
6270         unsigned long addr;
6271         unsigned blocksize_mask = root->sectorsize - 1;
6272         ssize_t retval = -EINVAL;
6273         loff_t end = offset;
6274
6275         if (offset & blocksize_mask)
6276                 goto out;
6277
6278         /* Check the memory alignment.  Blocks cannot straddle pages */
6279         for (seg = 0; seg < nr_segs; seg++) {
6280                 addr = (unsigned long)iov[seg].iov_base;
6281                 size = iov[seg].iov_len;
6282                 end += size;
6283                 if ((addr & blocksize_mask) || (size & blocksize_mask))
6284                         goto out;
6285
6286                 /* If this is a write we don't need to check anymore */
6287                 if (rw & WRITE)
6288                         continue;
6289
6290                 /*
6291                  * Check to make sure we don't have duplicate iov_base's in this
6292                  * iovec, if so return EINVAL, otherwise we'll get csum errors
6293                  * when reading back.
6294                  */
6295                 for (i = seg + 1; i < nr_segs; i++) {
6296                         if (iov[seg].iov_base == iov[i].iov_base)
6297                                 goto out;
6298                 }
6299         }
6300         retval = 0;
6301 out:
6302         return retval;
6303 }
6304 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
6305                         const struct iovec *iov, loff_t offset,
6306                         unsigned long nr_segs)
6307 {
6308         struct file *file = iocb->ki_filp;
6309         struct inode *inode = file->f_mapping->host;
6310         struct btrfs_ordered_extent *ordered;
6311         struct extent_state *cached_state = NULL;
6312         u64 lockstart, lockend;
6313         ssize_t ret;
6314         int writing = rw & WRITE;
6315         int write_bits = 0;
6316         size_t count = iov_length(iov, nr_segs);
6317
6318         if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
6319                             offset, nr_segs)) {
6320                 return 0;
6321         }
6322
6323         lockstart = offset;
6324         lockend = offset + count - 1;
6325
6326         if (writing) {
6327                 ret = btrfs_delalloc_reserve_space(inode, count);
6328                 if (ret)
6329                         goto out;
6330         }
6331
6332         while (1) {
6333                 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6334                                  0, &cached_state);
6335                 /*
6336                  * We're concerned with the entire range that we're going to be
6337                  * doing DIO to, so we need to make sure theres no ordered
6338                  * extents in this range.
6339                  */
6340                 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6341                                                      lockend - lockstart + 1);
6342                 if (!ordered)
6343                         break;
6344                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6345                                      &cached_state, GFP_NOFS);
6346                 btrfs_start_ordered_extent(inode, ordered, 1);
6347                 btrfs_put_ordered_extent(ordered);
6348                 cond_resched();
6349         }
6350
6351         /*
6352          * we don't use btrfs_set_extent_delalloc because we don't want
6353          * the dirty or uptodate bits
6354          */
6355         if (writing) {
6356                 write_bits = EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING;
6357                 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6358                                      EXTENT_DELALLOC, NULL, &cached_state,
6359                                      GFP_NOFS);
6360                 if (ret) {
6361                         clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6362                                          lockend, EXTENT_LOCKED | write_bits,
6363                                          1, 0, &cached_state, GFP_NOFS);
6364                         goto out;
6365                 }
6366         }
6367
6368         free_extent_state(cached_state);
6369         cached_state = NULL;
6370
6371         ret = __blockdev_direct_IO(rw, iocb, inode,
6372                    BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
6373                    iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
6374                    btrfs_submit_direct, 0);
6375
6376         if (ret < 0 && ret != -EIOCBQUEUED) {
6377                 clear_extent_bit(&BTRFS_I(inode)->io_tree, offset,
6378                               offset + iov_length(iov, nr_segs) - 1,
6379                               EXTENT_LOCKED | write_bits, 1, 0,
6380                               &cached_state, GFP_NOFS);
6381         } else if (ret >= 0 && ret < iov_length(iov, nr_segs)) {
6382                 /*
6383                  * We're falling back to buffered, unlock the section we didn't
6384                  * do IO on.
6385                  */
6386                 clear_extent_bit(&BTRFS_I(inode)->io_tree, offset + ret,
6387                               offset + iov_length(iov, nr_segs) - 1,
6388                               EXTENT_LOCKED | write_bits, 1, 0,
6389                               &cached_state, GFP_NOFS);
6390         }
6391 out:
6392         free_extent_state(cached_state);
6393         return ret;
6394 }
6395
6396 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
6397                 __u64 start, __u64 len)
6398 {
6399         return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
6400 }
6401
6402 int btrfs_readpage(struct file *file, struct page *page)
6403 {
6404         struct extent_io_tree *tree;
6405         tree = &BTRFS_I(page->mapping->host)->io_tree;
6406         return extent_read_full_page(tree, page, btrfs_get_extent, 0);
6407 }
6408
6409 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
6410 {
6411         struct extent_io_tree *tree;
6412
6413
6414         if (current->flags & PF_MEMALLOC) {
6415                 redirty_page_for_writepage(wbc, page);
6416                 unlock_page(page);
6417                 return 0;
6418         }
6419         tree = &BTRFS_I(page->mapping->host)->io_tree;
6420         return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
6421 }
6422
6423 int btrfs_writepages(struct address_space *mapping,
6424                      struct writeback_control *wbc)
6425 {
6426         struct extent_io_tree *tree;
6427
6428         tree = &BTRFS_I(mapping->host)->io_tree;
6429         return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
6430 }
6431
6432 static int
6433 btrfs_readpages(struct file *file, struct address_space *mapping,
6434                 struct list_head *pages, unsigned nr_pages)
6435 {
6436         struct extent_io_tree *tree;
6437         tree = &BTRFS_I(mapping->host)->io_tree;
6438         return extent_readpages(tree, mapping, pages, nr_pages,
6439                                 btrfs_get_extent);
6440 }
6441 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6442 {
6443         struct extent_io_tree *tree;
6444         struct extent_map_tree *map;
6445         int ret;
6446
6447         tree = &BTRFS_I(page->mapping->host)->io_tree;
6448         map = &BTRFS_I(page->mapping->host)->extent_tree;
6449         ret = try_release_extent_mapping(map, tree, page, gfp_flags);
6450         if (ret == 1) {
6451                 ClearPagePrivate(page);
6452                 set_page_private(page, 0);
6453                 page_cache_release(page);
6454         }
6455         return ret;
6456 }
6457
6458 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6459 {
6460         if (PageWriteback(page) || PageDirty(page))
6461                 return 0;
6462         return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
6463 }
6464
6465 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
6466 {
6467         struct inode *inode = page->mapping->host;
6468         struct extent_io_tree *tree;
6469         struct btrfs_ordered_extent *ordered;
6470         struct extent_state *cached_state = NULL;
6471         u64 page_start = page_offset(page);
6472         u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
6473
6474         /*
6475          * we have the page locked, so new writeback can't start,
6476          * and the dirty bit won't be cleared while we are here.
6477          *
6478          * Wait for IO on this page so that we can safely clear
6479          * the PagePrivate2 bit and do ordered accounting
6480          */
6481         wait_on_page_writeback(page);
6482
6483         tree = &BTRFS_I(inode)->io_tree;
6484         if (offset) {
6485                 btrfs_releasepage(page, GFP_NOFS);
6486                 return;
6487         }
6488         lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
6489         ordered = btrfs_lookup_ordered_extent(inode,
6490                                            page_offset(page));
6491         if (ordered) {
6492                 /*
6493                  * IO on this page will never be started, so we need
6494                  * to account for any ordered extents now
6495                  */
6496                 clear_extent_bit(tree, page_start, page_end,
6497                                  EXTENT_DIRTY | EXTENT_DELALLOC |
6498                                  EXTENT_LOCKED | EXTENT_DO_ACCOUNTING, 1, 0,
6499                                  &cached_state, GFP_NOFS);
6500                 /*
6501                  * whoever cleared the private bit is responsible
6502                  * for the finish_ordered_io
6503                  */
6504                 if (TestClearPagePrivate2(page) &&
6505                     btrfs_dec_test_ordered_pending(inode, &ordered, page_start,
6506                                                    PAGE_CACHE_SIZE, 1)) {
6507                         btrfs_finish_ordered_io(ordered);
6508                 }
6509                 btrfs_put_ordered_extent(ordered);
6510                 cached_state = NULL;
6511                 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
6512         }
6513         clear_extent_bit(tree, page_start, page_end,
6514                  EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
6515                  EXTENT_DO_ACCOUNTING, 1, 1, &cached_state, GFP_NOFS);
6516         __btrfs_releasepage(page, GFP_NOFS);
6517
6518         ClearPageChecked(page);
6519         if (PagePrivate(page)) {
6520                 ClearPagePrivate(page);
6521                 set_page_private(page, 0);
6522                 page_cache_release(page);
6523         }
6524 }
6525
6526 /*
6527  * btrfs_page_mkwrite() is not allowed to change the file size as it gets
6528  * called from a page fault handler when a page is first dirtied. Hence we must
6529  * be careful to check for EOF conditions here. We set the page up correctly
6530  * for a written page which means we get ENOSPC checking when writing into
6531  * holes and correct delalloc and unwritten extent mapping on filesystems that
6532  * support these features.
6533  *
6534  * We are not allowed to take the i_mutex here so we have to play games to
6535  * protect against truncate races as the page could now be beyond EOF.  Because
6536  * vmtruncate() writes the inode size before removing pages, once we have the
6537  * page lock we can determine safely if the page is beyond EOF. If it is not
6538  * beyond EOF, then the page is guaranteed safe against truncation until we
6539  * unlock the page.
6540  */
6541 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
6542 {
6543         struct page *page = vmf->page;
6544         struct inode *inode = fdentry(vma->vm_file)->d_inode;
6545         struct btrfs_root *root = BTRFS_I(inode)->root;
6546         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6547         struct btrfs_ordered_extent *ordered;
6548         struct extent_state *cached_state = NULL;
6549         char *kaddr;
6550         unsigned long zero_start;
6551         loff_t size;
6552         int ret;
6553         int reserved = 0;
6554         u64 page_start;
6555         u64 page_end;
6556
6557         ret  = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
6558         if (!ret) {
6559                 ret = btrfs_update_time(vma->vm_file);
6560                 reserved = 1;
6561         }
6562         if (ret) {
6563                 if (ret == -ENOMEM)
6564                         ret = VM_FAULT_OOM;
6565                 else /* -ENOSPC, -EIO, etc */
6566                         ret = VM_FAULT_SIGBUS;
6567                 if (reserved)
6568                         goto out;
6569                 goto out_noreserve;
6570         }
6571
6572         ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
6573 again:
6574         lock_page(page);
6575         size = i_size_read(inode);
6576         page_start = page_offset(page);
6577         page_end = page_start + PAGE_CACHE_SIZE - 1;
6578
6579         if ((page->mapping != inode->i_mapping) ||
6580             (page_start >= size)) {
6581                 /* page got truncated out from underneath us */
6582                 goto out_unlock;
6583         }
6584         wait_on_page_writeback(page);
6585
6586         lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
6587         set_page_extent_mapped(page);
6588
6589         /*
6590          * we can't set the delalloc bits if there are pending ordered
6591          * extents.  Drop our locks and wait for them to finish
6592          */
6593         ordered = btrfs_lookup_ordered_extent(inode, page_start);
6594         if (ordered) {
6595                 unlock_extent_cached(io_tree, page_start, page_end,
6596                                      &cached_state, GFP_NOFS);
6597                 unlock_page(page);
6598                 btrfs_start_ordered_extent(inode, ordered, 1);
6599                 btrfs_put_ordered_extent(ordered);
6600                 goto again;
6601         }
6602
6603         /*
6604          * XXX - page_mkwrite gets called every time the page is dirtied, even
6605          * if it was already dirty, so for space accounting reasons we need to
6606          * clear any delalloc bits for the range we are fixing to save.  There
6607          * is probably a better way to do this, but for now keep consistent with
6608          * prepare_pages in the normal write path.
6609          */
6610         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
6611                           EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
6612                           0, 0, &cached_state, GFP_NOFS);
6613
6614         ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
6615                                         &cached_state);
6616         if (ret) {
6617                 unlock_extent_cached(io_tree, page_start, page_end,
6618                                      &cached_state, GFP_NOFS);
6619                 ret = VM_FAULT_SIGBUS;
6620                 goto out_unlock;
6621         }
6622         ret = 0;
6623
6624         /* page is wholly or partially inside EOF */
6625         if (page_start + PAGE_CACHE_SIZE > size)
6626                 zero_start = size & ~PAGE_CACHE_MASK;
6627         else
6628                 zero_start = PAGE_CACHE_SIZE;
6629
6630         if (zero_start != PAGE_CACHE_SIZE) {
6631                 kaddr = kmap(page);
6632                 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
6633                 flush_dcache_page(page);
6634                 kunmap(page);
6635         }
6636         ClearPageChecked(page);
6637         set_page_dirty(page);
6638         SetPageUptodate(page);
6639
6640         BTRFS_I(inode)->last_trans = root->fs_info->generation;
6641         BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
6642
6643         unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
6644
6645 out_unlock:
6646         if (!ret)
6647                 return VM_FAULT_LOCKED;
6648         unlock_page(page);
6649 out:
6650         btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
6651 out_noreserve:
6652         return ret;
6653 }
6654
6655 static int btrfs_truncate(struct inode *inode)
6656 {
6657         struct btrfs_root *root = BTRFS_I(inode)->root;
6658         struct btrfs_block_rsv *rsv;
6659         int ret;
6660         int err = 0;
6661         struct btrfs_trans_handle *trans;
6662         unsigned long nr;
6663         u64 mask = root->sectorsize - 1;
6664         u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
6665
6666         ret = btrfs_truncate_page(inode->i_mapping, inode->i_size);
6667         if (ret)
6668                 return ret;
6669
6670         btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
6671         btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
6672
6673         /*
6674          * Yes ladies and gentelment, this is indeed ugly.  The fact is we have
6675          * 3 things going on here
6676          *
6677          * 1) We need to reserve space for our orphan item and the space to
6678          * delete our orphan item.  Lord knows we don't want to have a dangling
6679          * orphan item because we didn't reserve space to remove it.
6680          *
6681          * 2) We need to reserve space to update our inode.
6682          *
6683          * 3) We need to have something to cache all the space that is going to
6684          * be free'd up by the truncate operation, but also have some slack
6685          * space reserved in case it uses space during the truncate (thank you
6686          * very much snapshotting).
6687          *
6688          * And we need these to all be seperate.  The fact is we can use alot of
6689          * space doing the truncate, and we have no earthly idea how much space
6690          * we will use, so we need the truncate reservation to be seperate so it
6691          * doesn't end up using space reserved for updating the inode or
6692          * removing the orphan item.  We also need to be able to stop the
6693          * transaction and start a new one, which means we need to be able to
6694          * update the inode several times, and we have no idea of knowing how
6695          * many times that will be, so we can't just reserve 1 item for the
6696          * entirety of the opration, so that has to be done seperately as well.
6697          * Then there is the orphan item, which does indeed need to be held on
6698          * to for the whole operation, and we need nobody to touch this reserved
6699          * space except the orphan code.
6700          *
6701          * So that leaves us with
6702          *
6703          * 1) root->orphan_block_rsv - for the orphan deletion.
6704          * 2) rsv - for the truncate reservation, which we will steal from the
6705          * transaction reservation.
6706          * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
6707          * updating the inode.
6708          */
6709         rsv = btrfs_alloc_block_rsv(root);
6710         if (!rsv)
6711                 return -ENOMEM;
6712         rsv->size = min_size;
6713
6714         /*
6715          * 1 for the truncate slack space
6716          * 1 for the orphan item we're going to add
6717          * 1 for the orphan item deletion
6718          * 1 for updating the inode.
6719          */
6720         trans = btrfs_start_transaction(root, 4);
6721         if (IS_ERR(trans)) {
6722                 err = PTR_ERR(trans);
6723                 goto out;
6724         }
6725
6726         /* Migrate the slack space for the truncate to our reserve */
6727         ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
6728                                       min_size);
6729         BUG_ON(ret);
6730
6731         ret = btrfs_orphan_add(trans, inode);
6732         if (ret) {
6733                 btrfs_end_transaction(trans, root);
6734                 goto out;
6735         }
6736
6737         /*
6738          * setattr is responsible for setting the ordered_data_close flag,
6739          * but that is only tested during the last file release.  That
6740          * could happen well after the next commit, leaving a great big
6741          * window where new writes may get lost if someone chooses to write
6742          * to this file after truncating to zero
6743          *
6744          * The inode doesn't have any dirty data here, and so if we commit
6745          * this is a noop.  If someone immediately starts writing to the inode
6746          * it is very likely we'll catch some of their writes in this
6747          * transaction, and the commit will find this file on the ordered
6748          * data list with good things to send down.
6749          *
6750          * This is a best effort solution, there is still a window where
6751          * using truncate to replace the contents of the file will
6752          * end up with a zero length file after a crash.
6753          */
6754         if (inode->i_size == 0 && test_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
6755                                            &BTRFS_I(inode)->runtime_flags))
6756                 btrfs_add_ordered_operation(trans, root, inode);
6757
6758         while (1) {
6759                 ret = btrfs_block_rsv_refill(root, rsv, min_size);
6760                 if (ret) {
6761                         /*
6762                          * This can only happen with the original transaction we
6763                          * started above, every other time we shouldn't have a
6764                          * transaction started yet.
6765                          */
6766                         if (ret == -EAGAIN)
6767                                 goto end_trans;
6768                         err = ret;
6769                         break;
6770                 }
6771
6772                 if (!trans) {
6773                         /* Just need the 1 for updating the inode */
6774                         trans = btrfs_start_transaction(root, 1);
6775                         if (IS_ERR(trans)) {
6776                                 ret = err = PTR_ERR(trans);
6777                                 trans = NULL;
6778                                 break;
6779                         }
6780                 }
6781
6782                 trans->block_rsv = rsv;
6783
6784                 ret = btrfs_truncate_inode_items(trans, root, inode,
6785                                                  inode->i_size,
6786                                                  BTRFS_EXTENT_DATA_KEY);
6787                 if (ret != -EAGAIN) {
6788                         err = ret;
6789                         break;
6790                 }
6791
6792                 trans->block_rsv = &root->fs_info->trans_block_rsv;
6793                 ret = btrfs_update_inode(trans, root, inode);
6794                 if (ret) {
6795                         err = ret;
6796                         break;
6797                 }
6798 end_trans:
6799                 nr = trans->blocks_used;
6800                 btrfs_end_transaction(trans, root);
6801                 trans = NULL;
6802                 btrfs_btree_balance_dirty(root, nr);
6803         }
6804
6805         if (ret == 0 && inode->i_nlink > 0) {
6806                 trans->block_rsv = root->orphan_block_rsv;
6807                 ret = btrfs_orphan_del(trans, inode);
6808                 if (ret)
6809                         err = ret;
6810         } else if (ret && inode->i_nlink > 0) {
6811                 /*
6812                  * Failed to do the truncate, remove us from the in memory
6813                  * orphan list.
6814                  */
6815                 ret = btrfs_orphan_del(NULL, inode);
6816         }
6817
6818         if (trans) {
6819                 trans->block_rsv = &root->fs_info->trans_block_rsv;
6820                 ret = btrfs_update_inode(trans, root, inode);
6821                 if (ret && !err)
6822                         err = ret;
6823
6824                 nr = trans->blocks_used;
6825                 ret = btrfs_end_transaction(trans, root);
6826                 btrfs_btree_balance_dirty(root, nr);
6827         }
6828
6829 out:
6830         btrfs_free_block_rsv(root, rsv);
6831
6832         if (ret && !err)
6833                 err = ret;
6834
6835         return err;
6836 }
6837
6838 /*
6839  * create a new subvolume directory/inode (helper for the ioctl).
6840  */
6841 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
6842                              struct btrfs_root *new_root, u64 new_dirid)
6843 {
6844         struct inode *inode;
6845         int err;
6846         u64 index = 0;
6847
6848         inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
6849                                 new_dirid, new_dirid,
6850                                 S_IFDIR | (~current_umask() & S_IRWXUGO),
6851                                 &index);
6852         if (IS_ERR(inode))
6853                 return PTR_ERR(inode);
6854         inode->i_op = &btrfs_dir_inode_operations;
6855         inode->i_fop = &btrfs_dir_file_operations;
6856
6857         set_nlink(inode, 1);
6858         btrfs_i_size_write(inode, 0);
6859
6860         err = btrfs_update_inode(trans, new_root, inode);
6861
6862         iput(inode);
6863         return err;
6864 }
6865
6866 struct inode *btrfs_alloc_inode(struct super_block *sb)
6867 {
6868         struct btrfs_inode *ei;
6869         struct inode *inode;
6870
6871         ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
6872         if (!ei)
6873                 return NULL;
6874
6875         ei->root = NULL;
6876         ei->space_info = NULL;
6877         ei->generation = 0;
6878         ei->last_trans = 0;
6879         ei->last_sub_trans = 0;
6880         ei->logged_trans = 0;
6881         ei->delalloc_bytes = 0;
6882         ei->disk_i_size = 0;
6883         ei->flags = 0;
6884         ei->csum_bytes = 0;
6885         ei->index_cnt = (u64)-1;
6886         ei->last_unlink_trans = 0;
6887
6888         spin_lock_init(&ei->lock);
6889         ei->outstanding_extents = 0;
6890         ei->reserved_extents = 0;
6891
6892         ei->runtime_flags = 0;
6893         ei->force_compress = BTRFS_COMPRESS_NONE;
6894
6895         ei->delayed_node = NULL;
6896
6897         inode = &ei->vfs_inode;
6898         extent_map_tree_init(&ei->extent_tree);
6899         extent_io_tree_init(&ei->io_tree, &inode->i_data);
6900         extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
6901         ei->io_tree.track_uptodate = 1;
6902         ei->io_failure_tree.track_uptodate = 1;
6903         mutex_init(&ei->log_mutex);
6904         mutex_init(&ei->delalloc_mutex);
6905         btrfs_ordered_inode_tree_init(&ei->ordered_tree);
6906         INIT_LIST_HEAD(&ei->i_orphan);
6907         INIT_LIST_HEAD(&ei->delalloc_inodes);
6908         INIT_LIST_HEAD(&ei->ordered_operations);
6909         RB_CLEAR_NODE(&ei->rb_node);
6910
6911         return inode;
6912 }
6913
6914 static void btrfs_i_callback(struct rcu_head *head)
6915 {
6916         struct inode *inode = container_of(head, struct inode, i_rcu);
6917         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
6918 }
6919
6920 void btrfs_destroy_inode(struct inode *inode)
6921 {
6922         struct btrfs_ordered_extent *ordered;
6923         struct btrfs_root *root = BTRFS_I(inode)->root;
6924
6925         WARN_ON(!list_empty(&inode->i_dentry));
6926         WARN_ON(inode->i_data.nrpages);
6927         WARN_ON(BTRFS_I(inode)->outstanding_extents);
6928         WARN_ON(BTRFS_I(inode)->reserved_extents);
6929         WARN_ON(BTRFS_I(inode)->delalloc_bytes);
6930         WARN_ON(BTRFS_I(inode)->csum_bytes);
6931
6932         /*
6933          * This can happen where we create an inode, but somebody else also
6934          * created the same inode and we need to destroy the one we already
6935          * created.
6936          */
6937         if (!root)
6938                 goto free;
6939
6940         /*
6941          * Make sure we're properly removed from the ordered operation
6942          * lists.
6943          */
6944         smp_mb();
6945         if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
6946                 spin_lock(&root->fs_info->ordered_extent_lock);
6947                 list_del_init(&BTRFS_I(inode)->ordered_operations);
6948                 spin_unlock(&root->fs_info->ordered_extent_lock);
6949         }
6950
6951         spin_lock(&root->orphan_lock);
6952         if (!list_empty(&BTRFS_I(inode)->i_orphan)) {
6953                 printk(KERN_INFO "BTRFS: inode %llu still on the orphan list\n",
6954                        (unsigned long long)btrfs_ino(inode));
6955                 list_del_init(&BTRFS_I(inode)->i_orphan);
6956         }
6957         spin_unlock(&root->orphan_lock);
6958
6959         while (1) {
6960                 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
6961                 if (!ordered)
6962                         break;
6963                 else {
6964                         printk(KERN_ERR "btrfs found ordered "
6965                                "extent %llu %llu on inode cleanup\n",
6966                                (unsigned long long)ordered->file_offset,
6967                                (unsigned long long)ordered->len);
6968                         btrfs_remove_ordered_extent(inode, ordered);
6969                         btrfs_put_ordered_extent(ordered);
6970                         btrfs_put_ordered_extent(ordered);
6971                 }
6972         }
6973         inode_tree_del(inode);
6974         btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
6975 free:
6976         btrfs_remove_delayed_node(inode);
6977         call_rcu(&inode->i_rcu, btrfs_i_callback);
6978 }
6979
6980 int btrfs_drop_inode(struct inode *inode)
6981 {
6982         struct btrfs_root *root = BTRFS_I(inode)->root;
6983
6984         if (btrfs_root_refs(&root->root_item) == 0 &&
6985             !btrfs_is_free_space_inode(root, inode))
6986                 return 1;
6987         else
6988                 return generic_drop_inode(inode);
6989 }
6990
6991 static void init_once(void *foo)
6992 {
6993         struct btrfs_inode *ei = (struct btrfs_inode *) foo;
6994
6995         inode_init_once(&ei->vfs_inode);
6996 }
6997
6998 void btrfs_destroy_cachep(void)
6999 {
7000         if (btrfs_inode_cachep)
7001                 kmem_cache_destroy(btrfs_inode_cachep);
7002         if (btrfs_trans_handle_cachep)
7003                 kmem_cache_destroy(btrfs_trans_handle_cachep);
7004         if (btrfs_transaction_cachep)
7005                 kmem_cache_destroy(btrfs_transaction_cachep);
7006         if (btrfs_path_cachep)
7007                 kmem_cache_destroy(btrfs_path_cachep);
7008         if (btrfs_free_space_cachep)
7009                 kmem_cache_destroy(btrfs_free_space_cachep);
7010 }
7011
7012 int btrfs_init_cachep(void)
7013 {
7014         btrfs_inode_cachep = kmem_cache_create("btrfs_inode_cache",
7015                         sizeof(struct btrfs_inode), 0,
7016                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
7017         if (!btrfs_inode_cachep)
7018                 goto fail;
7019
7020         btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle_cache",
7021                         sizeof(struct btrfs_trans_handle), 0,
7022                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7023         if (!btrfs_trans_handle_cachep)
7024                 goto fail;
7025
7026         btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction_cache",
7027                         sizeof(struct btrfs_transaction), 0,
7028                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7029         if (!btrfs_transaction_cachep)
7030                 goto fail;
7031
7032         btrfs_path_cachep = kmem_cache_create("btrfs_path_cache",
7033                         sizeof(struct btrfs_path), 0,
7034                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7035         if (!btrfs_path_cachep)
7036                 goto fail;
7037
7038         btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space_cache",
7039                         sizeof(struct btrfs_free_space), 0,
7040                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7041         if (!btrfs_free_space_cachep)
7042                 goto fail;
7043
7044         return 0;
7045 fail:
7046         btrfs_destroy_cachep();
7047         return -ENOMEM;
7048 }
7049
7050 static int btrfs_getattr(struct vfsmount *mnt,
7051                          struct dentry *dentry, struct kstat *stat)
7052 {
7053         struct inode *inode = dentry->d_inode;
7054         u32 blocksize = inode->i_sb->s_blocksize;
7055
7056         generic_fillattr(inode, stat);
7057         stat->dev = BTRFS_I(inode)->root->anon_dev;
7058         stat->blksize = PAGE_CACHE_SIZE;
7059         stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
7060                 ALIGN(BTRFS_I(inode)->delalloc_bytes, blocksize)) >> 9;
7061         return 0;
7062 }
7063
7064 /*
7065  * If a file is moved, it will inherit the cow and compression flags of the new
7066  * directory.
7067  */
7068 static void fixup_inode_flags(struct inode *dir, struct inode *inode)
7069 {
7070         struct btrfs_inode *b_dir = BTRFS_I(dir);
7071         struct btrfs_inode *b_inode = BTRFS_I(inode);
7072
7073         if (b_dir->flags & BTRFS_INODE_NODATACOW)
7074                 b_inode->flags |= BTRFS_INODE_NODATACOW;
7075         else
7076                 b_inode->flags &= ~BTRFS_INODE_NODATACOW;
7077
7078         if (b_dir->flags & BTRFS_INODE_COMPRESS)
7079                 b_inode->flags |= BTRFS_INODE_COMPRESS;
7080         else
7081                 b_inode->flags &= ~BTRFS_INODE_COMPRESS;
7082 }
7083
7084 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
7085                            struct inode *new_dir, struct dentry *new_dentry)
7086 {
7087         struct btrfs_trans_handle *trans;
7088         struct btrfs_root *root = BTRFS_I(old_dir)->root;
7089         struct btrfs_root *dest = BTRFS_I(new_dir)->root;
7090         struct inode *new_inode = new_dentry->d_inode;
7091         struct inode *old_inode = old_dentry->d_inode;
7092         struct timespec ctime = CURRENT_TIME;
7093         u64 index = 0;
7094         u64 root_objectid;
7095         int ret;
7096         u64 old_ino = btrfs_ino(old_inode);
7097
7098         if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
7099                 return -EPERM;
7100
7101         /* we only allow rename subvolume link between subvolumes */
7102         if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
7103                 return -EXDEV;
7104
7105         if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
7106             (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
7107                 return -ENOTEMPTY;
7108
7109         if (S_ISDIR(old_inode->i_mode) && new_inode &&
7110             new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
7111                 return -ENOTEMPTY;
7112         /*
7113          * we're using rename to replace one file with another.
7114          * and the replacement file is large.  Start IO on it now so
7115          * we don't add too much work to the end of the transaction
7116          */
7117         if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
7118             old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
7119                 filemap_flush(old_inode->i_mapping);
7120
7121         /* close the racy window with snapshot create/destroy ioctl */
7122         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
7123                 down_read(&root->fs_info->subvol_sem);
7124         /*
7125          * We want to reserve the absolute worst case amount of items.  So if
7126          * both inodes are subvols and we need to unlink them then that would
7127          * require 4 item modifications, but if they are both normal inodes it
7128          * would require 5 item modifications, so we'll assume their normal
7129          * inodes.  So 5 * 2 is 10, plus 1 for the new link, so 11 total items
7130          * should cover the worst case number of items we'll modify.
7131          */
7132         trans = btrfs_start_transaction(root, 20);
7133         if (IS_ERR(trans)) {
7134                 ret = PTR_ERR(trans);
7135                 goto out_notrans;
7136         }
7137
7138         if (dest != root)
7139                 btrfs_record_root_in_trans(trans, dest);
7140
7141         ret = btrfs_set_inode_index(new_dir, &index);
7142         if (ret)
7143                 goto out_fail;
7144
7145         if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
7146                 /* force full log commit if subvolume involved. */
7147                 root->fs_info->last_trans_log_full_commit = trans->transid;
7148         } else {
7149                 ret = btrfs_insert_inode_ref(trans, dest,
7150                                              new_dentry->d_name.name,
7151                                              new_dentry->d_name.len,
7152                                              old_ino,
7153                                              btrfs_ino(new_dir), index);
7154                 if (ret)
7155                         goto out_fail;
7156                 /*
7157                  * this is an ugly little race, but the rename is required
7158                  * to make sure that if we crash, the inode is either at the
7159                  * old name or the new one.  pinning the log transaction lets
7160                  * us make sure we don't allow a log commit to come in after
7161                  * we unlink the name but before we add the new name back in.
7162                  */
7163                 btrfs_pin_log_trans(root);
7164         }
7165         /*
7166          * make sure the inode gets flushed if it is replacing
7167          * something.
7168          */
7169         if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
7170                 btrfs_add_ordered_operation(trans, root, old_inode);
7171
7172         inode_inc_iversion(old_dir);
7173         inode_inc_iversion(new_dir);
7174         inode_inc_iversion(old_inode);
7175         old_dir->i_ctime = old_dir->i_mtime = ctime;
7176         new_dir->i_ctime = new_dir->i_mtime = ctime;
7177         old_inode->i_ctime = ctime;
7178
7179         if (old_dentry->d_parent != new_dentry->d_parent)
7180                 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
7181
7182         if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
7183                 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
7184                 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
7185                                         old_dentry->d_name.name,
7186                                         old_dentry->d_name.len);
7187         } else {
7188                 ret = __btrfs_unlink_inode(trans, root, old_dir,
7189                                         old_dentry->d_inode,
7190                                         old_dentry->d_name.name,
7191                                         old_dentry->d_name.len);
7192                 if (!ret)
7193                         ret = btrfs_update_inode(trans, root, old_inode);
7194         }
7195         if (ret) {
7196                 btrfs_abort_transaction(trans, root, ret);
7197                 goto out_fail;
7198         }
7199
7200         if (new_inode) {
7201                 inode_inc_iversion(new_inode);
7202                 new_inode->i_ctime = CURRENT_TIME;
7203                 if (unlikely(btrfs_ino(new_inode) ==
7204                              BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
7205                         root_objectid = BTRFS_I(new_inode)->location.objectid;
7206                         ret = btrfs_unlink_subvol(trans, dest, new_dir,
7207                                                 root_objectid,
7208                                                 new_dentry->d_name.name,
7209                                                 new_dentry->d_name.len);
7210                         BUG_ON(new_inode->i_nlink == 0);
7211                 } else {
7212                         ret = btrfs_unlink_inode(trans, dest, new_dir,
7213                                                  new_dentry->d_inode,
7214                                                  new_dentry->d_name.name,
7215                                                  new_dentry->d_name.len);
7216                 }
7217                 if (!ret && new_inode->i_nlink == 0) {
7218                         ret = btrfs_orphan_add(trans, new_dentry->d_inode);
7219                         BUG_ON(ret);
7220                 }
7221                 if (ret) {
7222                         btrfs_abort_transaction(trans, root, ret);
7223                         goto out_fail;
7224                 }
7225         }
7226
7227         fixup_inode_flags(new_dir, old_inode);
7228
7229         ret = btrfs_add_link(trans, new_dir, old_inode,
7230                              new_dentry->d_name.name,
7231                              new_dentry->d_name.len, 0, index);
7232         if (ret) {
7233                 btrfs_abort_transaction(trans, root, ret);
7234                 goto out_fail;
7235         }
7236
7237         if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
7238                 struct dentry *parent = new_dentry->d_parent;
7239                 btrfs_log_new_name(trans, old_inode, old_dir, parent);
7240                 btrfs_end_log_trans(root);
7241         }
7242 out_fail:
7243         btrfs_end_transaction(trans, root);
7244 out_notrans:
7245         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
7246                 up_read(&root->fs_info->subvol_sem);
7247
7248         return ret;
7249 }
7250
7251 /*
7252  * some fairly slow code that needs optimization. This walks the list
7253  * of all the inodes with pending delalloc and forces them to disk.
7254  */
7255 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
7256 {
7257         struct list_head *head = &root->fs_info->delalloc_inodes;
7258         struct btrfs_inode *binode;
7259         struct inode *inode;
7260
7261         if (root->fs_info->sb->s_flags & MS_RDONLY)
7262                 return -EROFS;
7263
7264         spin_lock(&root->fs_info->delalloc_lock);
7265         while (!list_empty(head)) {
7266                 binode = list_entry(head->next, struct btrfs_inode,
7267                                     delalloc_inodes);
7268                 inode = igrab(&binode->vfs_inode);
7269                 if (!inode)
7270                         list_del_init(&binode->delalloc_inodes);
7271                 spin_unlock(&root->fs_info->delalloc_lock);
7272                 if (inode) {
7273                         filemap_flush(inode->i_mapping);
7274                         if (delay_iput)
7275                                 btrfs_add_delayed_iput(inode);
7276                         else
7277                                 iput(inode);
7278                 }
7279                 cond_resched();
7280                 spin_lock(&root->fs_info->delalloc_lock);
7281         }
7282         spin_unlock(&root->fs_info->delalloc_lock);
7283
7284         /* the filemap_flush will queue IO into the worker threads, but
7285          * we have to make sure the IO is actually started and that
7286          * ordered extents get created before we return
7287          */
7288         atomic_inc(&root->fs_info->async_submit_draining);
7289         while (atomic_read(&root->fs_info->nr_async_submits) ||
7290               atomic_read(&root->fs_info->async_delalloc_pages)) {
7291                 wait_event(root->fs_info->async_submit_wait,
7292                    (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
7293                     atomic_read(&root->fs_info->async_delalloc_pages) == 0));
7294         }
7295         atomic_dec(&root->fs_info->async_submit_draining);
7296         return 0;
7297 }
7298
7299 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
7300                          const char *symname)
7301 {
7302         struct btrfs_trans_handle *trans;
7303         struct btrfs_root *root = BTRFS_I(dir)->root;
7304         struct btrfs_path *path;
7305         struct btrfs_key key;
7306         struct inode *inode = NULL;
7307         int err;
7308         int drop_inode = 0;
7309         u64 objectid;
7310         u64 index = 0 ;
7311         int name_len;
7312         int datasize;
7313         unsigned long ptr;
7314         struct btrfs_file_extent_item *ei;
7315         struct extent_buffer *leaf;
7316         unsigned long nr = 0;
7317
7318         name_len = strlen(symname) + 1;
7319         if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
7320                 return -ENAMETOOLONG;
7321
7322         /*
7323          * 2 items for inode item and ref
7324          * 2 items for dir items
7325          * 1 item for xattr if selinux is on
7326          */
7327         trans = btrfs_start_transaction(root, 5);
7328         if (IS_ERR(trans))
7329                 return PTR_ERR(trans);
7330
7331         err = btrfs_find_free_ino(root, &objectid);
7332         if (err)
7333                 goto out_unlock;
7334
7335         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
7336                                 dentry->d_name.len, btrfs_ino(dir), objectid,
7337                                 S_IFLNK|S_IRWXUGO, &index);
7338         if (IS_ERR(inode)) {
7339                 err = PTR_ERR(inode);
7340                 goto out_unlock;
7341         }
7342
7343         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
7344         if (err) {
7345                 drop_inode = 1;
7346                 goto out_unlock;
7347         }
7348
7349         /*
7350         * If the active LSM wants to access the inode during
7351         * d_instantiate it needs these. Smack checks to see
7352         * if the filesystem supports xattrs by looking at the
7353         * ops vector.
7354         */
7355         inode->i_fop = &btrfs_file_operations;
7356         inode->i_op = &btrfs_file_inode_operations;
7357
7358         err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
7359         if (err)
7360                 drop_inode = 1;
7361         else {
7362                 inode->i_mapping->a_ops = &btrfs_aops;
7363                 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
7364                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
7365         }
7366         if (drop_inode)
7367                 goto out_unlock;
7368
7369         path = btrfs_alloc_path();
7370         if (!path) {
7371                 err = -ENOMEM;
7372                 drop_inode = 1;
7373                 goto out_unlock;
7374         }
7375         key.objectid = btrfs_ino(inode);
7376         key.offset = 0;
7377         btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
7378         datasize = btrfs_file_extent_calc_inline_size(name_len);
7379         err = btrfs_insert_empty_item(trans, root, path, &key,
7380                                       datasize);
7381         if (err) {
7382                 drop_inode = 1;
7383                 btrfs_free_path(path);
7384                 goto out_unlock;
7385         }
7386         leaf = path->nodes[0];
7387         ei = btrfs_item_ptr(leaf, path->slots[0],
7388                             struct btrfs_file_extent_item);
7389         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
7390         btrfs_set_file_extent_type(leaf, ei,
7391                                    BTRFS_FILE_EXTENT_INLINE);
7392         btrfs_set_file_extent_encryption(leaf, ei, 0);
7393         btrfs_set_file_extent_compression(leaf, ei, 0);
7394         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
7395         btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
7396
7397         ptr = btrfs_file_extent_inline_start(ei);
7398         write_extent_buffer(leaf, symname, ptr, name_len);
7399         btrfs_mark_buffer_dirty(leaf);
7400         btrfs_free_path(path);
7401
7402         inode->i_op = &btrfs_symlink_inode_operations;
7403         inode->i_mapping->a_ops = &btrfs_symlink_aops;
7404         inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
7405         inode_set_bytes(inode, name_len);
7406         btrfs_i_size_write(inode, name_len - 1);
7407         err = btrfs_update_inode(trans, root, inode);
7408         if (err)
7409                 drop_inode = 1;
7410
7411 out_unlock:
7412         if (!err)
7413                 d_instantiate(dentry, inode);
7414         nr = trans->blocks_used;
7415         btrfs_end_transaction(trans, root);
7416         if (drop_inode) {
7417                 inode_dec_link_count(inode);
7418                 iput(inode);
7419         }
7420         btrfs_btree_balance_dirty(root, nr);
7421         return err;
7422 }
7423
7424 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
7425                                        u64 start, u64 num_bytes, u64 min_size,
7426                                        loff_t actual_len, u64 *alloc_hint,
7427                                        struct btrfs_trans_handle *trans)
7428 {
7429         struct btrfs_root *root = BTRFS_I(inode)->root;
7430         struct btrfs_key ins;
7431         u64 cur_offset = start;
7432         u64 i_size;
7433         int ret = 0;
7434         bool own_trans = true;
7435
7436         if (trans)
7437                 own_trans = false;
7438         while (num_bytes > 0) {
7439                 if (own_trans) {
7440                         trans = btrfs_start_transaction(root, 3);
7441                         if (IS_ERR(trans)) {
7442                                 ret = PTR_ERR(trans);
7443                                 break;
7444                         }
7445                 }
7446
7447                 ret = btrfs_reserve_extent(trans, root, num_bytes, min_size,
7448                                            0, *alloc_hint, &ins, 1);
7449                 if (ret) {
7450                         if (own_trans)
7451                                 btrfs_end_transaction(trans, root);
7452                         break;
7453                 }
7454
7455                 ret = insert_reserved_file_extent(trans, inode,
7456                                                   cur_offset, ins.objectid,
7457                                                   ins.offset, ins.offset,
7458                                                   ins.offset, 0, 0, 0,
7459                                                   BTRFS_FILE_EXTENT_PREALLOC);
7460                 if (ret) {
7461                         btrfs_abort_transaction(trans, root, ret);
7462                         if (own_trans)
7463                                 btrfs_end_transaction(trans, root);
7464                         break;
7465                 }
7466                 btrfs_drop_extent_cache(inode, cur_offset,
7467                                         cur_offset + ins.offset -1, 0);
7468
7469                 num_bytes -= ins.offset;
7470                 cur_offset += ins.offset;
7471                 *alloc_hint = ins.objectid + ins.offset;
7472
7473                 inode_inc_iversion(inode);
7474                 inode->i_ctime = CURRENT_TIME;
7475                 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
7476                 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
7477                     (actual_len > inode->i_size) &&
7478                     (cur_offset > inode->i_size)) {
7479                         if (cur_offset > actual_len)
7480                                 i_size = actual_len;
7481                         else
7482                                 i_size = cur_offset;
7483                         i_size_write(inode, i_size);
7484                         btrfs_ordered_update_i_size(inode, i_size, NULL);
7485                 }
7486
7487                 ret = btrfs_update_inode(trans, root, inode);
7488
7489                 if (ret) {
7490                         btrfs_abort_transaction(trans, root, ret);
7491                         if (own_trans)
7492                                 btrfs_end_transaction(trans, root);
7493                         break;
7494                 }
7495
7496                 if (own_trans)
7497                         btrfs_end_transaction(trans, root);
7498         }
7499         return ret;
7500 }
7501
7502 int btrfs_prealloc_file_range(struct inode *inode, int mode,
7503                               u64 start, u64 num_bytes, u64 min_size,
7504                               loff_t actual_len, u64 *alloc_hint)
7505 {
7506         return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7507                                            min_size, actual_len, alloc_hint,
7508                                            NULL);
7509 }
7510
7511 int btrfs_prealloc_file_range_trans(struct inode *inode,
7512                                     struct btrfs_trans_handle *trans, int mode,
7513                                     u64 start, u64 num_bytes, u64 min_size,
7514                                     loff_t actual_len, u64 *alloc_hint)
7515 {
7516         return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7517                                            min_size, actual_len, alloc_hint, trans);
7518 }
7519
7520 static int btrfs_set_page_dirty(struct page *page)
7521 {
7522         return __set_page_dirty_nobuffers(page);
7523 }
7524
7525 static int btrfs_permission(struct inode *inode, int mask)
7526 {
7527         struct btrfs_root *root = BTRFS_I(inode)->root;
7528         umode_t mode = inode->i_mode;
7529
7530         if (mask & MAY_WRITE &&
7531             (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
7532                 if (btrfs_root_readonly(root))
7533                         return -EROFS;
7534                 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
7535                         return -EACCES;
7536         }
7537         return generic_permission(inode, mask);
7538 }
7539
7540 static const struct inode_operations btrfs_dir_inode_operations = {
7541         .getattr        = btrfs_getattr,
7542         .lookup         = btrfs_lookup,
7543         .create         = btrfs_create,
7544         .unlink         = btrfs_unlink,
7545         .link           = btrfs_link,
7546         .mkdir          = btrfs_mkdir,
7547         .rmdir          = btrfs_rmdir,
7548         .rename         = btrfs_rename,
7549         .symlink        = btrfs_symlink,
7550         .setattr        = btrfs_setattr,
7551         .mknod          = btrfs_mknod,
7552         .setxattr       = btrfs_setxattr,
7553         .getxattr       = btrfs_getxattr,
7554         .listxattr      = btrfs_listxattr,
7555         .removexattr    = btrfs_removexattr,
7556         .permission     = btrfs_permission,
7557         .get_acl        = btrfs_get_acl,
7558 };
7559 static const struct inode_operations btrfs_dir_ro_inode_operations = {
7560         .lookup         = btrfs_lookup,
7561         .permission     = btrfs_permission,
7562         .get_acl        = btrfs_get_acl,
7563 };
7564
7565 static const struct file_operations btrfs_dir_file_operations = {
7566         .llseek         = generic_file_llseek,
7567         .read           = generic_read_dir,
7568         .readdir        = btrfs_real_readdir,
7569         .unlocked_ioctl = btrfs_ioctl,
7570 #ifdef CONFIG_COMPAT
7571         .compat_ioctl   = btrfs_ioctl,
7572 #endif
7573         .release        = btrfs_release_file,
7574         .fsync          = btrfs_sync_file,
7575 };
7576
7577 static struct extent_io_ops btrfs_extent_io_ops = {
7578         .fill_delalloc = run_delalloc_range,
7579         .submit_bio_hook = btrfs_submit_bio_hook,
7580         .merge_bio_hook = btrfs_merge_bio_hook,
7581         .readpage_end_io_hook = btrfs_readpage_end_io_hook,
7582         .writepage_end_io_hook = btrfs_writepage_end_io_hook,
7583         .writepage_start_hook = btrfs_writepage_start_hook,
7584         .set_bit_hook = btrfs_set_bit_hook,
7585         .clear_bit_hook = btrfs_clear_bit_hook,
7586         .merge_extent_hook = btrfs_merge_extent_hook,
7587         .split_extent_hook = btrfs_split_extent_hook,
7588 };
7589
7590 /*
7591  * btrfs doesn't support the bmap operation because swapfiles
7592  * use bmap to make a mapping of extents in the file.  They assume
7593  * these extents won't change over the life of the file and they
7594  * use the bmap result to do IO directly to the drive.
7595  *
7596  * the btrfs bmap call would return logical addresses that aren't
7597  * suitable for IO and they also will change frequently as COW
7598  * operations happen.  So, swapfile + btrfs == corruption.
7599  *
7600  * For now we're avoiding this by dropping bmap.
7601  */
7602 static const struct address_space_operations btrfs_aops = {
7603         .readpage       = btrfs_readpage,
7604         .writepage      = btrfs_writepage,
7605         .writepages     = btrfs_writepages,
7606         .readpages      = btrfs_readpages,
7607         .direct_IO      = btrfs_direct_IO,
7608         .invalidatepage = btrfs_invalidatepage,
7609         .releasepage    = btrfs_releasepage,
7610         .set_page_dirty = btrfs_set_page_dirty,
7611         .error_remove_page = generic_error_remove_page,
7612 };
7613
7614 static const struct address_space_operations btrfs_symlink_aops = {
7615         .readpage       = btrfs_readpage,
7616         .writepage      = btrfs_writepage,
7617         .invalidatepage = btrfs_invalidatepage,
7618         .releasepage    = btrfs_releasepage,
7619 };
7620
7621 static const struct inode_operations btrfs_file_inode_operations = {
7622         .getattr        = btrfs_getattr,
7623         .setattr        = btrfs_setattr,
7624         .setxattr       = btrfs_setxattr,
7625         .getxattr       = btrfs_getxattr,
7626         .listxattr      = btrfs_listxattr,
7627         .removexattr    = btrfs_removexattr,
7628         .permission     = btrfs_permission,
7629         .fiemap         = btrfs_fiemap,
7630         .get_acl        = btrfs_get_acl,
7631 };
7632 static const struct inode_operations btrfs_special_inode_operations = {
7633         .getattr        = btrfs_getattr,
7634         .setattr        = btrfs_setattr,
7635         .permission     = btrfs_permission,
7636         .setxattr       = btrfs_setxattr,
7637         .getxattr       = btrfs_getxattr,
7638         .listxattr      = btrfs_listxattr,
7639         .removexattr    = btrfs_removexattr,
7640         .get_acl        = btrfs_get_acl,
7641 };
7642 static const struct inode_operations btrfs_symlink_inode_operations = {
7643         .readlink       = generic_readlink,
7644         .follow_link    = page_follow_link_light,
7645         .put_link       = page_put_link,
7646         .getattr        = btrfs_getattr,
7647         .setattr        = btrfs_setattr,
7648         .permission     = btrfs_permission,
7649         .setxattr       = btrfs_setxattr,
7650         .getxattr       = btrfs_getxattr,
7651         .listxattr      = btrfs_listxattr,
7652         .removexattr    = btrfs_removexattr,
7653         .get_acl        = btrfs_get_acl,
7654 };
7655
7656 const struct dentry_operations btrfs_dentry_operations = {
7657         .d_delete       = btrfs_dentry_delete,
7658         .d_release      = btrfs_dentry_release,
7659 };