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