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