6dbab92934251b560dce267ac8870ca103ac4584
[sfrench/cifs-2.6.git] / fs / btrfs / inode.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2007 Oracle.  All rights reserved.
4  */
5
6 #include <crypto/hash.h>
7 #include <linux/kernel.h>
8 #include <linux/bio.h>
9 #include <linux/file.h>
10 #include <linux/fs.h>
11 #include <linux/pagemap.h>
12 #include <linux/highmem.h>
13 #include <linux/time.h>
14 #include <linux/init.h>
15 #include <linux/string.h>
16 #include <linux/backing-dev.h>
17 #include <linux/writeback.h>
18 #include <linux/compat.h>
19 #include <linux/xattr.h>
20 #include <linux/posix_acl.h>
21 #include <linux/falloc.h>
22 #include <linux/slab.h>
23 #include <linux/ratelimit.h>
24 #include <linux/btrfs.h>
25 #include <linux/blkdev.h>
26 #include <linux/posix_acl_xattr.h>
27 #include <linux/uio.h>
28 #include <linux/magic.h>
29 #include <linux/iversion.h>
30 #include <linux/swap.h>
31 #include <linux/migrate.h>
32 #include <linux/sched/mm.h>
33 #include <linux/iomap.h>
34 #include <asm/unaligned.h>
35 #include "misc.h"
36 #include "ctree.h"
37 #include "disk-io.h"
38 #include "transaction.h"
39 #include "btrfs_inode.h"
40 #include "print-tree.h"
41 #include "ordered-data.h"
42 #include "xattr.h"
43 #include "tree-log.h"
44 #include "volumes.h"
45 #include "compression.h"
46 #include "locking.h"
47 #include "free-space-cache.h"
48 #include "props.h"
49 #include "qgroup.h"
50 #include "delalloc-space.h"
51 #include "block-group.h"
52 #include "space-info.h"
53 #include "zoned.h"
54
55 struct btrfs_iget_args {
56         u64 ino;
57         struct btrfs_root *root;
58 };
59
60 struct btrfs_dio_data {
61         u64 reserve;
62         loff_t length;
63         ssize_t submitted;
64         struct extent_changeset *data_reserved;
65 };
66
67 static const struct inode_operations btrfs_dir_inode_operations;
68 static const struct inode_operations btrfs_symlink_inode_operations;
69 static const struct inode_operations btrfs_special_inode_operations;
70 static const struct inode_operations btrfs_file_inode_operations;
71 static const struct address_space_operations btrfs_aops;
72 static const struct file_operations btrfs_dir_file_operations;
73
74 static struct kmem_cache *btrfs_inode_cachep;
75 struct kmem_cache *btrfs_trans_handle_cachep;
76 struct kmem_cache *btrfs_path_cachep;
77 struct kmem_cache *btrfs_free_space_cachep;
78 struct kmem_cache *btrfs_free_space_bitmap_cachep;
79
80 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
81 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
82 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
83 static noinline int cow_file_range(struct btrfs_inode *inode,
84                                    struct page *locked_page,
85                                    u64 start, u64 end, int *page_started,
86                                    unsigned long *nr_written, int unlock);
87 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
88                                        u64 len, u64 orig_start, u64 block_start,
89                                        u64 block_len, u64 orig_block_len,
90                                        u64 ram_bytes, int compress_type,
91                                        int type);
92
93 static void __endio_write_update_ordered(struct btrfs_inode *inode,
94                                          const u64 offset, const u64 bytes,
95                                          const bool uptodate);
96
97 /*
98  * btrfs_inode_lock - lock inode i_rwsem based on arguments passed
99  *
100  * ilock_flags can have the following bit set:
101  *
102  * BTRFS_ILOCK_SHARED - acquire a shared lock on the inode
103  * BTRFS_ILOCK_TRY - try to acquire the lock, if fails on first attempt
104  *                   return -EAGAIN
105  */
106 int btrfs_inode_lock(struct inode *inode, unsigned int ilock_flags)
107 {
108         if (ilock_flags & BTRFS_ILOCK_SHARED) {
109                 if (ilock_flags & BTRFS_ILOCK_TRY) {
110                         if (!inode_trylock_shared(inode))
111                                 return -EAGAIN;
112                         else
113                                 return 0;
114                 }
115                 inode_lock_shared(inode);
116         } else {
117                 if (ilock_flags & BTRFS_ILOCK_TRY) {
118                         if (!inode_trylock(inode))
119                                 return -EAGAIN;
120                         else
121                                 return 0;
122                 }
123                 inode_lock(inode);
124         }
125         return 0;
126 }
127
128 /*
129  * btrfs_inode_unlock - unock inode i_rwsem
130  *
131  * ilock_flags should contain the same bits set as passed to btrfs_inode_lock()
132  * to decide whether the lock acquired is shared or exclusive.
133  */
134 void btrfs_inode_unlock(struct inode *inode, unsigned int ilock_flags)
135 {
136         if (ilock_flags & BTRFS_ILOCK_SHARED)
137                 inode_unlock_shared(inode);
138         else
139                 inode_unlock(inode);
140 }
141
142 /*
143  * Cleanup all submitted ordered extents in specified range to handle errors
144  * from the btrfs_run_delalloc_range() callback.
145  *
146  * NOTE: caller must ensure that when an error happens, it can not call
147  * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
148  * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
149  * to be released, which we want to happen only when finishing the ordered
150  * extent (btrfs_finish_ordered_io()).
151  */
152 static inline void btrfs_cleanup_ordered_extents(struct btrfs_inode *inode,
153                                                  struct page *locked_page,
154                                                  u64 offset, u64 bytes)
155 {
156         unsigned long index = offset >> PAGE_SHIFT;
157         unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
158         u64 page_start = page_offset(locked_page);
159         u64 page_end = page_start + PAGE_SIZE - 1;
160
161         struct page *page;
162
163         while (index <= end_index) {
164                 page = find_get_page(inode->vfs_inode.i_mapping, index);
165                 index++;
166                 if (!page)
167                         continue;
168                 ClearPagePrivate2(page);
169                 put_page(page);
170         }
171
172         /*
173          * In case this page belongs to the delalloc range being instantiated
174          * then skip it, since the first page of a range is going to be
175          * properly cleaned up by the caller of run_delalloc_range
176          */
177         if (page_start >= offset && page_end <= (offset + bytes - 1)) {
178                 offset += PAGE_SIZE;
179                 bytes -= PAGE_SIZE;
180         }
181
182         return __endio_write_update_ordered(inode, offset, bytes, false);
183 }
184
185 static int btrfs_dirty_inode(struct inode *inode);
186
187 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
188                                      struct inode *inode,  struct inode *dir,
189                                      const struct qstr *qstr)
190 {
191         int err;
192
193         err = btrfs_init_acl(trans, inode, dir);
194         if (!err)
195                 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
196         return err;
197 }
198
199 /*
200  * this does all the hard work for inserting an inline extent into
201  * the btree.  The caller should have done a btrfs_drop_extents so that
202  * no overlapping inline items exist in the btree
203  */
204 static int insert_inline_extent(struct btrfs_trans_handle *trans,
205                                 struct btrfs_path *path, bool extent_inserted,
206                                 struct btrfs_root *root, struct inode *inode,
207                                 u64 start, size_t size, size_t compressed_size,
208                                 int compress_type,
209                                 struct page **compressed_pages)
210 {
211         struct extent_buffer *leaf;
212         struct page *page = NULL;
213         char *kaddr;
214         unsigned long ptr;
215         struct btrfs_file_extent_item *ei;
216         int ret;
217         size_t cur_size = size;
218         unsigned long offset;
219
220         ASSERT((compressed_size > 0 && compressed_pages) ||
221                (compressed_size == 0 && !compressed_pages));
222
223         if (compressed_size && compressed_pages)
224                 cur_size = compressed_size;
225
226         if (!extent_inserted) {
227                 struct btrfs_key key;
228                 size_t datasize;
229
230                 key.objectid = btrfs_ino(BTRFS_I(inode));
231                 key.offset = start;
232                 key.type = BTRFS_EXTENT_DATA_KEY;
233
234                 datasize = btrfs_file_extent_calc_inline_size(cur_size);
235                 ret = btrfs_insert_empty_item(trans, root, path, &key,
236                                               datasize);
237                 if (ret)
238                         goto fail;
239         }
240         leaf = path->nodes[0];
241         ei = btrfs_item_ptr(leaf, path->slots[0],
242                             struct btrfs_file_extent_item);
243         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
244         btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
245         btrfs_set_file_extent_encryption(leaf, ei, 0);
246         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
247         btrfs_set_file_extent_ram_bytes(leaf, ei, size);
248         ptr = btrfs_file_extent_inline_start(ei);
249
250         if (compress_type != BTRFS_COMPRESS_NONE) {
251                 struct page *cpage;
252                 int i = 0;
253                 while (compressed_size > 0) {
254                         cpage = compressed_pages[i];
255                         cur_size = min_t(unsigned long, compressed_size,
256                                        PAGE_SIZE);
257
258                         kaddr = kmap_atomic(cpage);
259                         write_extent_buffer(leaf, kaddr, ptr, cur_size);
260                         kunmap_atomic(kaddr);
261
262                         i++;
263                         ptr += cur_size;
264                         compressed_size -= cur_size;
265                 }
266                 btrfs_set_file_extent_compression(leaf, ei,
267                                                   compress_type);
268         } else {
269                 page = find_get_page(inode->i_mapping,
270                                      start >> PAGE_SHIFT);
271                 btrfs_set_file_extent_compression(leaf, ei, 0);
272                 kaddr = kmap_atomic(page);
273                 offset = offset_in_page(start);
274                 write_extent_buffer(leaf, kaddr + offset, ptr, size);
275                 kunmap_atomic(kaddr);
276                 put_page(page);
277         }
278         btrfs_mark_buffer_dirty(leaf);
279         btrfs_release_path(path);
280
281         /*
282          * We align size to sectorsize for inline extents just for simplicity
283          * sake.
284          */
285         size = ALIGN(size, root->fs_info->sectorsize);
286         ret = btrfs_inode_set_file_extent_range(BTRFS_I(inode), start, size);
287         if (ret)
288                 goto fail;
289
290         /*
291          * we're an inline extent, so nobody can
292          * extend the file past i_size without locking
293          * a page we already have locked.
294          *
295          * We must do any isize and inode updates
296          * before we unlock the pages.  Otherwise we
297          * could end up racing with unlink.
298          */
299         BTRFS_I(inode)->disk_i_size = inode->i_size;
300 fail:
301         return ret;
302 }
303
304
305 /*
306  * conditionally insert an inline extent into the file.  This
307  * does the checks required to make sure the data is small enough
308  * to fit as an inline extent.
309  */
310 static noinline int cow_file_range_inline(struct btrfs_inode *inode, u64 start,
311                                           u64 end, size_t compressed_size,
312                                           int compress_type,
313                                           struct page **compressed_pages)
314 {
315         struct btrfs_drop_extents_args drop_args = { 0 };
316         struct btrfs_root *root = inode->root;
317         struct btrfs_fs_info *fs_info = root->fs_info;
318         struct btrfs_trans_handle *trans;
319         u64 isize = i_size_read(&inode->vfs_inode);
320         u64 actual_end = min(end + 1, isize);
321         u64 inline_len = actual_end - start;
322         u64 aligned_end = ALIGN(end, fs_info->sectorsize);
323         u64 data_len = inline_len;
324         int ret;
325         struct btrfs_path *path;
326
327         if (compressed_size)
328                 data_len = compressed_size;
329
330         if (start > 0 ||
331             actual_end > fs_info->sectorsize ||
332             data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
333             (!compressed_size &&
334             (actual_end & (fs_info->sectorsize - 1)) == 0) ||
335             end + 1 < isize ||
336             data_len > fs_info->max_inline) {
337                 return 1;
338         }
339
340         path = btrfs_alloc_path();
341         if (!path)
342                 return -ENOMEM;
343
344         trans = btrfs_join_transaction(root);
345         if (IS_ERR(trans)) {
346                 btrfs_free_path(path);
347                 return PTR_ERR(trans);
348         }
349         trans->block_rsv = &inode->block_rsv;
350
351         drop_args.path = path;
352         drop_args.start = start;
353         drop_args.end = aligned_end;
354         drop_args.drop_cache = true;
355         drop_args.replace_extent = true;
356
357         if (compressed_size && compressed_pages)
358                 drop_args.extent_item_size = btrfs_file_extent_calc_inline_size(
359                    compressed_size);
360         else
361                 drop_args.extent_item_size = btrfs_file_extent_calc_inline_size(
362                     inline_len);
363
364         ret = btrfs_drop_extents(trans, root, inode, &drop_args);
365         if (ret) {
366                 btrfs_abort_transaction(trans, ret);
367                 goto out;
368         }
369
370         if (isize > actual_end)
371                 inline_len = min_t(u64, isize, actual_end);
372         ret = insert_inline_extent(trans, path, drop_args.extent_inserted,
373                                    root, &inode->vfs_inode, start,
374                                    inline_len, compressed_size,
375                                    compress_type, compressed_pages);
376         if (ret && ret != -ENOSPC) {
377                 btrfs_abort_transaction(trans, ret);
378                 goto out;
379         } else if (ret == -ENOSPC) {
380                 ret = 1;
381                 goto out;
382         }
383
384         btrfs_update_inode_bytes(inode, inline_len, drop_args.bytes_found);
385         ret = btrfs_update_inode(trans, root, inode);
386         if (ret && ret != -ENOSPC) {
387                 btrfs_abort_transaction(trans, ret);
388                 goto out;
389         } else if (ret == -ENOSPC) {
390                 ret = 1;
391                 goto out;
392         }
393
394         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
395 out:
396         /*
397          * Don't forget to free the reserved space, as for inlined extent
398          * it won't count as data extent, free them directly here.
399          * And at reserve time, it's always aligned to page size, so
400          * just free one page here.
401          */
402         btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
403         btrfs_free_path(path);
404         btrfs_end_transaction(trans);
405         return ret;
406 }
407
408 struct async_extent {
409         u64 start;
410         u64 ram_size;
411         u64 compressed_size;
412         struct page **pages;
413         unsigned long nr_pages;
414         int compress_type;
415         struct list_head list;
416 };
417
418 struct async_chunk {
419         struct inode *inode;
420         struct page *locked_page;
421         u64 start;
422         u64 end;
423         unsigned int write_flags;
424         struct list_head extents;
425         struct cgroup_subsys_state *blkcg_css;
426         struct btrfs_work work;
427         atomic_t *pending;
428 };
429
430 struct async_cow {
431         /* Number of chunks in flight; must be first in the structure */
432         atomic_t num_chunks;
433         struct async_chunk chunks[];
434 };
435
436 static noinline int add_async_extent(struct async_chunk *cow,
437                                      u64 start, u64 ram_size,
438                                      u64 compressed_size,
439                                      struct page **pages,
440                                      unsigned long nr_pages,
441                                      int compress_type)
442 {
443         struct async_extent *async_extent;
444
445         async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
446         BUG_ON(!async_extent); /* -ENOMEM */
447         async_extent->start = start;
448         async_extent->ram_size = ram_size;
449         async_extent->compressed_size = compressed_size;
450         async_extent->pages = pages;
451         async_extent->nr_pages = nr_pages;
452         async_extent->compress_type = compress_type;
453         list_add_tail(&async_extent->list, &cow->extents);
454         return 0;
455 }
456
457 /*
458  * Check if the inode has flags compatible with compression
459  */
460 static inline bool inode_can_compress(struct btrfs_inode *inode)
461 {
462         if (inode->flags & BTRFS_INODE_NODATACOW ||
463             inode->flags & BTRFS_INODE_NODATASUM)
464                 return false;
465         return true;
466 }
467
468 /*
469  * Check if the inode needs to be submitted to compression, based on mount
470  * options, defragmentation, properties or heuristics.
471  */
472 static inline int inode_need_compress(struct btrfs_inode *inode, u64 start,
473                                       u64 end)
474 {
475         struct btrfs_fs_info *fs_info = inode->root->fs_info;
476
477         if (!inode_can_compress(inode)) {
478                 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
479                         KERN_ERR "BTRFS: unexpected compression for ino %llu\n",
480                         btrfs_ino(inode));
481                 return 0;
482         }
483         /* force compress */
484         if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
485                 return 1;
486         /* defrag ioctl */
487         if (inode->defrag_compress)
488                 return 1;
489         /* bad compression ratios */
490         if (inode->flags & BTRFS_INODE_NOCOMPRESS)
491                 return 0;
492         if (btrfs_test_opt(fs_info, COMPRESS) ||
493             inode->flags & BTRFS_INODE_COMPRESS ||
494             inode->prop_compress)
495                 return btrfs_compress_heuristic(&inode->vfs_inode, start, end);
496         return 0;
497 }
498
499 static inline void inode_should_defrag(struct btrfs_inode *inode,
500                 u64 start, u64 end, u64 num_bytes, u64 small_write)
501 {
502         /* If this is a small write inside eof, kick off a defrag */
503         if (num_bytes < small_write &&
504             (start > 0 || end + 1 < inode->disk_i_size))
505                 btrfs_add_inode_defrag(NULL, inode);
506 }
507
508 /*
509  * we create compressed extents in two phases.  The first
510  * phase compresses a range of pages that have already been
511  * locked (both pages and state bits are locked).
512  *
513  * This is done inside an ordered work queue, and the compression
514  * is spread across many cpus.  The actual IO submission is step
515  * two, and the ordered work queue takes care of making sure that
516  * happens in the same order things were put onto the queue by
517  * writepages and friends.
518  *
519  * If this code finds it can't get good compression, it puts an
520  * entry onto the work queue to write the uncompressed bytes.  This
521  * makes sure that both compressed inodes and uncompressed inodes
522  * are written in the same order that the flusher thread sent them
523  * down.
524  */
525 static noinline int compress_file_range(struct async_chunk *async_chunk)
526 {
527         struct inode *inode = async_chunk->inode;
528         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
529         u64 blocksize = fs_info->sectorsize;
530         u64 start = async_chunk->start;
531         u64 end = async_chunk->end;
532         u64 actual_end;
533         u64 i_size;
534         int ret = 0;
535         struct page **pages = NULL;
536         unsigned long nr_pages;
537         unsigned long total_compressed = 0;
538         unsigned long total_in = 0;
539         int i;
540         int will_compress;
541         int compress_type = fs_info->compress_type;
542         int compressed_extents = 0;
543         int redirty = 0;
544
545         inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
546                         SZ_16K);
547
548         /*
549          * We need to save i_size before now because it could change in between
550          * us evaluating the size and assigning it.  This is because we lock and
551          * unlock the page in truncate and fallocate, and then modify the i_size
552          * later on.
553          *
554          * The barriers are to emulate READ_ONCE, remove that once i_size_read
555          * does that for us.
556          */
557         barrier();
558         i_size = i_size_read(inode);
559         barrier();
560         actual_end = min_t(u64, i_size, end + 1);
561 again:
562         will_compress = 0;
563         nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
564         BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
565         nr_pages = min_t(unsigned long, nr_pages,
566                         BTRFS_MAX_COMPRESSED / PAGE_SIZE);
567
568         /*
569          * we don't want to send crud past the end of i_size through
570          * compression, that's just a waste of CPU time.  So, if the
571          * end of the file is before the start of our current
572          * requested range of bytes, we bail out to the uncompressed
573          * cleanup code that can deal with all of this.
574          *
575          * It isn't really the fastest way to fix things, but this is a
576          * very uncommon corner.
577          */
578         if (actual_end <= start)
579                 goto cleanup_and_bail_uncompressed;
580
581         total_compressed = actual_end - start;
582
583         /*
584          * skip compression for a small file range(<=blocksize) that
585          * isn't an inline extent, since it doesn't save disk space at all.
586          */
587         if (total_compressed <= blocksize &&
588            (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
589                 goto cleanup_and_bail_uncompressed;
590
591         total_compressed = min_t(unsigned long, total_compressed,
592                         BTRFS_MAX_UNCOMPRESSED);
593         total_in = 0;
594         ret = 0;
595
596         /*
597          * we do compression for mount -o compress and when the
598          * inode has not been flagged as nocompress.  This flag can
599          * change at any time if we discover bad compression ratios.
600          */
601         if (inode_need_compress(BTRFS_I(inode), start, end)) {
602                 WARN_ON(pages);
603                 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
604                 if (!pages) {
605                         /* just bail out to the uncompressed code */
606                         nr_pages = 0;
607                         goto cont;
608                 }
609
610                 if (BTRFS_I(inode)->defrag_compress)
611                         compress_type = BTRFS_I(inode)->defrag_compress;
612                 else if (BTRFS_I(inode)->prop_compress)
613                         compress_type = BTRFS_I(inode)->prop_compress;
614
615                 /*
616                  * we need to call clear_page_dirty_for_io on each
617                  * page in the range.  Otherwise applications with the file
618                  * mmap'd can wander in and change the page contents while
619                  * we are compressing them.
620                  *
621                  * If the compression fails for any reason, we set the pages
622                  * dirty again later on.
623                  *
624                  * Note that the remaining part is redirtied, the start pointer
625                  * has moved, the end is the original one.
626                  */
627                 if (!redirty) {
628                         extent_range_clear_dirty_for_io(inode, start, end);
629                         redirty = 1;
630                 }
631
632                 /* Compression level is applied here and only here */
633                 ret = btrfs_compress_pages(
634                         compress_type | (fs_info->compress_level << 4),
635                                            inode->i_mapping, start,
636                                            pages,
637                                            &nr_pages,
638                                            &total_in,
639                                            &total_compressed);
640
641                 if (!ret) {
642                         unsigned long offset = offset_in_page(total_compressed);
643                         struct page *page = pages[nr_pages - 1];
644                         char *kaddr;
645
646                         /* zero the tail end of the last page, we might be
647                          * sending it down to disk
648                          */
649                         if (offset) {
650                                 kaddr = kmap_atomic(page);
651                                 memset(kaddr + offset, 0,
652                                        PAGE_SIZE - offset);
653                                 kunmap_atomic(kaddr);
654                         }
655                         will_compress = 1;
656                 }
657         }
658 cont:
659         if (start == 0) {
660                 /* lets try to make an inline extent */
661                 if (ret || total_in < actual_end) {
662                         /* we didn't compress the entire range, try
663                          * to make an uncompressed inline extent.
664                          */
665                         ret = cow_file_range_inline(BTRFS_I(inode), start, end,
666                                                     0, BTRFS_COMPRESS_NONE,
667                                                     NULL);
668                 } else {
669                         /* try making a compressed inline extent */
670                         ret = cow_file_range_inline(BTRFS_I(inode), start, end,
671                                                     total_compressed,
672                                                     compress_type, pages);
673                 }
674                 if (ret <= 0) {
675                         unsigned long clear_flags = EXTENT_DELALLOC |
676                                 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
677                                 EXTENT_DO_ACCOUNTING;
678                         unsigned long page_error_op;
679
680                         page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
681
682                         /*
683                          * inline extent creation worked or returned error,
684                          * we don't need to create any more async work items.
685                          * Unlock and free up our temp pages.
686                          *
687                          * We use DO_ACCOUNTING here because we need the
688                          * delalloc_release_metadata to be done _after_ we drop
689                          * our outstanding extent for clearing delalloc for this
690                          * range.
691                          */
692                         extent_clear_unlock_delalloc(BTRFS_I(inode), start, end,
693                                                      NULL,
694                                                      clear_flags,
695                                                      PAGE_UNLOCK |
696                                                      PAGE_START_WRITEBACK |
697                                                      page_error_op |
698                                                      PAGE_END_WRITEBACK);
699
700                         /*
701                          * Ensure we only free the compressed pages if we have
702                          * them allocated, as we can still reach here with
703                          * inode_need_compress() == false.
704                          */
705                         if (pages) {
706                                 for (i = 0; i < nr_pages; i++) {
707                                         WARN_ON(pages[i]->mapping);
708                                         put_page(pages[i]);
709                                 }
710                                 kfree(pages);
711                         }
712                         return 0;
713                 }
714         }
715
716         if (will_compress) {
717                 /*
718                  * we aren't doing an inline extent round the compressed size
719                  * up to a block size boundary so the allocator does sane
720                  * things
721                  */
722                 total_compressed = ALIGN(total_compressed, blocksize);
723
724                 /*
725                  * one last check to make sure the compression is really a
726                  * win, compare the page count read with the blocks on disk,
727                  * compression must free at least one sector size
728                  */
729                 total_in = ALIGN(total_in, PAGE_SIZE);
730                 if (total_compressed + blocksize <= total_in) {
731                         compressed_extents++;
732
733                         /*
734                          * The async work queues will take care of doing actual
735                          * allocation on disk for these compressed pages, and
736                          * will submit them to the elevator.
737                          */
738                         add_async_extent(async_chunk, start, total_in,
739                                         total_compressed, pages, nr_pages,
740                                         compress_type);
741
742                         if (start + total_in < end) {
743                                 start += total_in;
744                                 pages = NULL;
745                                 cond_resched();
746                                 goto again;
747                         }
748                         return compressed_extents;
749                 }
750         }
751         if (pages) {
752                 /*
753                  * the compression code ran but failed to make things smaller,
754                  * free any pages it allocated and our page pointer array
755                  */
756                 for (i = 0; i < nr_pages; i++) {
757                         WARN_ON(pages[i]->mapping);
758                         put_page(pages[i]);
759                 }
760                 kfree(pages);
761                 pages = NULL;
762                 total_compressed = 0;
763                 nr_pages = 0;
764
765                 /* flag the file so we don't compress in the future */
766                 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
767                     !(BTRFS_I(inode)->prop_compress)) {
768                         BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
769                 }
770         }
771 cleanup_and_bail_uncompressed:
772         /*
773          * No compression, but we still need to write the pages in the file
774          * we've been given so far.  redirty the locked page if it corresponds
775          * to our extent and set things up for the async work queue to run
776          * cow_file_range to do the normal delalloc dance.
777          */
778         if (async_chunk->locked_page &&
779             (page_offset(async_chunk->locked_page) >= start &&
780              page_offset(async_chunk->locked_page)) <= end) {
781                 __set_page_dirty_nobuffers(async_chunk->locked_page);
782                 /* unlocked later on in the async handlers */
783         }
784
785         if (redirty)
786                 extent_range_redirty_for_io(inode, start, end);
787         add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
788                          BTRFS_COMPRESS_NONE);
789         compressed_extents++;
790
791         return compressed_extents;
792 }
793
794 static void free_async_extent_pages(struct async_extent *async_extent)
795 {
796         int i;
797
798         if (!async_extent->pages)
799                 return;
800
801         for (i = 0; i < async_extent->nr_pages; i++) {
802                 WARN_ON(async_extent->pages[i]->mapping);
803                 put_page(async_extent->pages[i]);
804         }
805         kfree(async_extent->pages);
806         async_extent->nr_pages = 0;
807         async_extent->pages = NULL;
808 }
809
810 /*
811  * phase two of compressed writeback.  This is the ordered portion
812  * of the code, which only gets called in the order the work was
813  * queued.  We walk all the async extents created by compress_file_range
814  * and send them down to the disk.
815  */
816 static noinline void submit_compressed_extents(struct async_chunk *async_chunk)
817 {
818         struct btrfs_inode *inode = BTRFS_I(async_chunk->inode);
819         struct btrfs_fs_info *fs_info = inode->root->fs_info;
820         struct async_extent *async_extent;
821         u64 alloc_hint = 0;
822         struct btrfs_key ins;
823         struct extent_map *em;
824         struct btrfs_root *root = inode->root;
825         struct extent_io_tree *io_tree = &inode->io_tree;
826         int ret = 0;
827
828 again:
829         while (!list_empty(&async_chunk->extents)) {
830                 async_extent = list_entry(async_chunk->extents.next,
831                                           struct async_extent, list);
832                 list_del(&async_extent->list);
833
834 retry:
835                 lock_extent(io_tree, async_extent->start,
836                             async_extent->start + async_extent->ram_size - 1);
837                 /* did the compression code fall back to uncompressed IO? */
838                 if (!async_extent->pages) {
839                         int page_started = 0;
840                         unsigned long nr_written = 0;
841
842                         /* allocate blocks */
843                         ret = cow_file_range(inode, async_chunk->locked_page,
844                                              async_extent->start,
845                                              async_extent->start +
846                                              async_extent->ram_size - 1,
847                                              &page_started, &nr_written, 0);
848
849                         /* JDM XXX */
850
851                         /*
852                          * if page_started, cow_file_range inserted an
853                          * inline extent and took care of all the unlocking
854                          * and IO for us.  Otherwise, we need to submit
855                          * all those pages down to the drive.
856                          */
857                         if (!page_started && !ret)
858                                 extent_write_locked_range(&inode->vfs_inode,
859                                                   async_extent->start,
860                                                   async_extent->start +
861                                                   async_extent->ram_size - 1,
862                                                   WB_SYNC_ALL);
863                         else if (ret && async_chunk->locked_page)
864                                 unlock_page(async_chunk->locked_page);
865                         kfree(async_extent);
866                         cond_resched();
867                         continue;
868                 }
869
870                 ret = btrfs_reserve_extent(root, async_extent->ram_size,
871                                            async_extent->compressed_size,
872                                            async_extent->compressed_size,
873                                            0, alloc_hint, &ins, 1, 1);
874                 if (ret) {
875                         free_async_extent_pages(async_extent);
876
877                         if (ret == -ENOSPC) {
878                                 unlock_extent(io_tree, async_extent->start,
879                                               async_extent->start +
880                                               async_extent->ram_size - 1);
881
882                                 /*
883                                  * we need to redirty the pages if we decide to
884                                  * fallback to uncompressed IO, otherwise we
885                                  * will not submit these pages down to lower
886                                  * layers.
887                                  */
888                                 extent_range_redirty_for_io(&inode->vfs_inode,
889                                                 async_extent->start,
890                                                 async_extent->start +
891                                                 async_extent->ram_size - 1);
892
893                                 goto retry;
894                         }
895                         goto out_free;
896                 }
897                 /*
898                  * here we're doing allocation and writeback of the
899                  * compressed pages
900                  */
901                 em = create_io_em(inode, async_extent->start,
902                                   async_extent->ram_size, /* len */
903                                   async_extent->start, /* orig_start */
904                                   ins.objectid, /* block_start */
905                                   ins.offset, /* block_len */
906                                   ins.offset, /* orig_block_len */
907                                   async_extent->ram_size, /* ram_bytes */
908                                   async_extent->compress_type,
909                                   BTRFS_ORDERED_COMPRESSED);
910                 if (IS_ERR(em))
911                         /* ret value is not necessary due to void function */
912                         goto out_free_reserve;
913                 free_extent_map(em);
914
915                 ret = btrfs_add_ordered_extent_compress(inode,
916                                                 async_extent->start,
917                                                 ins.objectid,
918                                                 async_extent->ram_size,
919                                                 ins.offset,
920                                                 async_extent->compress_type);
921                 if (ret) {
922                         btrfs_drop_extent_cache(inode, async_extent->start,
923                                                 async_extent->start +
924                                                 async_extent->ram_size - 1, 0);
925                         goto out_free_reserve;
926                 }
927                 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
928
929                 /*
930                  * clear dirty, set writeback and unlock the pages.
931                  */
932                 extent_clear_unlock_delalloc(inode, async_extent->start,
933                                 async_extent->start +
934                                 async_extent->ram_size - 1,
935                                 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
936                                 PAGE_UNLOCK | PAGE_START_WRITEBACK);
937                 if (btrfs_submit_compressed_write(inode, async_extent->start,
938                                     async_extent->ram_size,
939                                     ins.objectid,
940                                     ins.offset, async_extent->pages,
941                                     async_extent->nr_pages,
942                                     async_chunk->write_flags,
943                                     async_chunk->blkcg_css)) {
944                         struct page *p = async_extent->pages[0];
945                         const u64 start = async_extent->start;
946                         const u64 end = start + async_extent->ram_size - 1;
947
948                         p->mapping = inode->vfs_inode.i_mapping;
949                         btrfs_writepage_endio_finish_ordered(p, start, end, 0);
950
951                         p->mapping = NULL;
952                         extent_clear_unlock_delalloc(inode, start, end, NULL, 0,
953                                                      PAGE_END_WRITEBACK |
954                                                      PAGE_SET_ERROR);
955                         free_async_extent_pages(async_extent);
956                 }
957                 alloc_hint = ins.objectid + ins.offset;
958                 kfree(async_extent);
959                 cond_resched();
960         }
961         return;
962 out_free_reserve:
963         btrfs_dec_block_group_reservations(fs_info, ins.objectid);
964         btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
965 out_free:
966         extent_clear_unlock_delalloc(inode, async_extent->start,
967                                      async_extent->start +
968                                      async_extent->ram_size - 1,
969                                      NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
970                                      EXTENT_DELALLOC_NEW |
971                                      EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
972                                      PAGE_UNLOCK | PAGE_START_WRITEBACK |
973                                      PAGE_END_WRITEBACK | PAGE_SET_ERROR);
974         free_async_extent_pages(async_extent);
975         kfree(async_extent);
976         goto again;
977 }
978
979 static u64 get_extent_allocation_hint(struct btrfs_inode *inode, u64 start,
980                                       u64 num_bytes)
981 {
982         struct extent_map_tree *em_tree = &inode->extent_tree;
983         struct extent_map *em;
984         u64 alloc_hint = 0;
985
986         read_lock(&em_tree->lock);
987         em = search_extent_mapping(em_tree, start, num_bytes);
988         if (em) {
989                 /*
990                  * if block start isn't an actual block number then find the
991                  * first block in this inode and use that as a hint.  If that
992                  * block is also bogus then just don't worry about it.
993                  */
994                 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
995                         free_extent_map(em);
996                         em = search_extent_mapping(em_tree, 0, 0);
997                         if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
998                                 alloc_hint = em->block_start;
999                         if (em)
1000                                 free_extent_map(em);
1001                 } else {
1002                         alloc_hint = em->block_start;
1003                         free_extent_map(em);
1004                 }
1005         }
1006         read_unlock(&em_tree->lock);
1007
1008         return alloc_hint;
1009 }
1010
1011 /*
1012  * when extent_io.c finds a delayed allocation range in the file,
1013  * the call backs end up in this code.  The basic idea is to
1014  * allocate extents on disk for the range, and create ordered data structs
1015  * in ram to track those extents.
1016  *
1017  * locked_page is the page that writepage had locked already.  We use
1018  * it to make sure we don't do extra locks or unlocks.
1019  *
1020  * *page_started is set to one if we unlock locked_page and do everything
1021  * required to start IO on it.  It may be clean and already done with
1022  * IO when we return.
1023  */
1024 static noinline int cow_file_range(struct btrfs_inode *inode,
1025                                    struct page *locked_page,
1026                                    u64 start, u64 end, int *page_started,
1027                                    unsigned long *nr_written, int unlock)
1028 {
1029         struct btrfs_root *root = inode->root;
1030         struct btrfs_fs_info *fs_info = root->fs_info;
1031         u64 alloc_hint = 0;
1032         u64 num_bytes;
1033         unsigned long ram_size;
1034         u64 cur_alloc_size = 0;
1035         u64 min_alloc_size;
1036         u64 blocksize = fs_info->sectorsize;
1037         struct btrfs_key ins;
1038         struct extent_map *em;
1039         unsigned clear_bits;
1040         unsigned long page_ops;
1041         bool extent_reserved = false;
1042         int ret = 0;
1043
1044         if (btrfs_is_free_space_inode(inode)) {
1045                 WARN_ON_ONCE(1);
1046                 ret = -EINVAL;
1047                 goto out_unlock;
1048         }
1049
1050         num_bytes = ALIGN(end - start + 1, blocksize);
1051         num_bytes = max(blocksize,  num_bytes);
1052         ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
1053
1054         inode_should_defrag(inode, start, end, num_bytes, SZ_64K);
1055
1056         if (start == 0) {
1057                 /* lets try to make an inline extent */
1058                 ret = cow_file_range_inline(inode, start, end, 0,
1059                                             BTRFS_COMPRESS_NONE, NULL);
1060                 if (ret == 0) {
1061                         /*
1062                          * We use DO_ACCOUNTING here because we need the
1063                          * delalloc_release_metadata to be run _after_ we drop
1064                          * our outstanding extent for clearing delalloc for this
1065                          * range.
1066                          */
1067                         extent_clear_unlock_delalloc(inode, start, end, NULL,
1068                                      EXTENT_LOCKED | EXTENT_DELALLOC |
1069                                      EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1070                                      EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1071                                      PAGE_START_WRITEBACK | PAGE_END_WRITEBACK);
1072                         *nr_written = *nr_written +
1073                              (end - start + PAGE_SIZE) / PAGE_SIZE;
1074                         *page_started = 1;
1075                         goto out;
1076                 } else if (ret < 0) {
1077                         goto out_unlock;
1078                 }
1079         }
1080
1081         alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1082         btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
1083
1084         /*
1085          * Relocation relies on the relocated extents to have exactly the same
1086          * size as the original extents. Normally writeback for relocation data
1087          * extents follows a NOCOW path because relocation preallocates the
1088          * extents. However, due to an operation such as scrub turning a block
1089          * group to RO mode, it may fallback to COW mode, so we must make sure
1090          * an extent allocated during COW has exactly the requested size and can
1091          * not be split into smaller extents, otherwise relocation breaks and
1092          * fails during the stage where it updates the bytenr of file extent
1093          * items.
1094          */
1095         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1096                 min_alloc_size = num_bytes;
1097         else
1098                 min_alloc_size = fs_info->sectorsize;
1099
1100         while (num_bytes > 0) {
1101                 cur_alloc_size = num_bytes;
1102                 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1103                                            min_alloc_size, 0, alloc_hint,
1104                                            &ins, 1, 1);
1105                 if (ret < 0)
1106                         goto out_unlock;
1107                 cur_alloc_size = ins.offset;
1108                 extent_reserved = true;
1109
1110                 ram_size = ins.offset;
1111                 em = create_io_em(inode, start, ins.offset, /* len */
1112                                   start, /* orig_start */
1113                                   ins.objectid, /* block_start */
1114                                   ins.offset, /* block_len */
1115                                   ins.offset, /* orig_block_len */
1116                                   ram_size, /* ram_bytes */
1117                                   BTRFS_COMPRESS_NONE, /* compress_type */
1118                                   BTRFS_ORDERED_REGULAR /* type */);
1119                 if (IS_ERR(em)) {
1120                         ret = PTR_ERR(em);
1121                         goto out_reserve;
1122                 }
1123                 free_extent_map(em);
1124
1125                 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1126                                                ram_size, cur_alloc_size,
1127                                                BTRFS_ORDERED_REGULAR);
1128                 if (ret)
1129                         goto out_drop_extent_cache;
1130
1131                 if (root->root_key.objectid ==
1132                     BTRFS_DATA_RELOC_TREE_OBJECTID) {
1133                         ret = btrfs_reloc_clone_csums(inode, start,
1134                                                       cur_alloc_size);
1135                         /*
1136                          * Only drop cache here, and process as normal.
1137                          *
1138                          * We must not allow extent_clear_unlock_delalloc()
1139                          * at out_unlock label to free meta of this ordered
1140                          * extent, as its meta should be freed by
1141                          * btrfs_finish_ordered_io().
1142                          *
1143                          * So we must continue until @start is increased to
1144                          * skip current ordered extent.
1145                          */
1146                         if (ret)
1147                                 btrfs_drop_extent_cache(inode, start,
1148                                                 start + ram_size - 1, 0);
1149                 }
1150
1151                 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1152
1153                 /* we're not doing compressed IO, don't unlock the first
1154                  * page (which the caller expects to stay locked), don't
1155                  * clear any dirty bits and don't set any writeback bits
1156                  *
1157                  * Do set the Private2 bit so we know this page was properly
1158                  * setup for writepage
1159                  */
1160                 page_ops = unlock ? PAGE_UNLOCK : 0;
1161                 page_ops |= PAGE_SET_PRIVATE2;
1162
1163                 extent_clear_unlock_delalloc(inode, start, start + ram_size - 1,
1164                                              locked_page,
1165                                              EXTENT_LOCKED | EXTENT_DELALLOC,
1166                                              page_ops);
1167                 if (num_bytes < cur_alloc_size)
1168                         num_bytes = 0;
1169                 else
1170                         num_bytes -= cur_alloc_size;
1171                 alloc_hint = ins.objectid + ins.offset;
1172                 start += cur_alloc_size;
1173                 extent_reserved = false;
1174
1175                 /*
1176                  * btrfs_reloc_clone_csums() error, since start is increased
1177                  * extent_clear_unlock_delalloc() at out_unlock label won't
1178                  * free metadata of current ordered extent, we're OK to exit.
1179                  */
1180                 if (ret)
1181                         goto out_unlock;
1182         }
1183 out:
1184         return ret;
1185
1186 out_drop_extent_cache:
1187         btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0);
1188 out_reserve:
1189         btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1190         btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1191 out_unlock:
1192         clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1193                 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1194         page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK | PAGE_END_WRITEBACK;
1195         /*
1196          * If we reserved an extent for our delalloc range (or a subrange) and
1197          * failed to create the respective ordered extent, then it means that
1198          * when we reserved the extent we decremented the extent's size from
1199          * the data space_info's bytes_may_use counter and incremented the
1200          * space_info's bytes_reserved counter by the same amount. We must make
1201          * sure extent_clear_unlock_delalloc() does not try to decrement again
1202          * the data space_info's bytes_may_use counter, therefore we do not pass
1203          * it the flag EXTENT_CLEAR_DATA_RESV.
1204          */
1205         if (extent_reserved) {
1206                 extent_clear_unlock_delalloc(inode, start,
1207                                              start + cur_alloc_size - 1,
1208                                              locked_page,
1209                                              clear_bits,
1210                                              page_ops);
1211                 start += cur_alloc_size;
1212                 if (start >= end)
1213                         goto out;
1214         }
1215         extent_clear_unlock_delalloc(inode, start, end, locked_page,
1216                                      clear_bits | EXTENT_CLEAR_DATA_RESV,
1217                                      page_ops);
1218         goto out;
1219 }
1220
1221 /*
1222  * work queue call back to started compression on a file and pages
1223  */
1224 static noinline void async_cow_start(struct btrfs_work *work)
1225 {
1226         struct async_chunk *async_chunk;
1227         int compressed_extents;
1228
1229         async_chunk = container_of(work, struct async_chunk, work);
1230
1231         compressed_extents = compress_file_range(async_chunk);
1232         if (compressed_extents == 0) {
1233                 btrfs_add_delayed_iput(async_chunk->inode);
1234                 async_chunk->inode = NULL;
1235         }
1236 }
1237
1238 /*
1239  * work queue call back to submit previously compressed pages
1240  */
1241 static noinline void async_cow_submit(struct btrfs_work *work)
1242 {
1243         struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1244                                                      work);
1245         struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1246         unsigned long nr_pages;
1247
1248         nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1249                 PAGE_SHIFT;
1250
1251         /* atomic_sub_return implies a barrier */
1252         if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1253             5 * SZ_1M)
1254                 cond_wake_up_nomb(&fs_info->async_submit_wait);
1255
1256         /*
1257          * ->inode could be NULL if async_chunk_start has failed to compress,
1258          * in which case we don't have anything to submit, yet we need to
1259          * always adjust ->async_delalloc_pages as its paired with the init
1260          * happening in cow_file_range_async
1261          */
1262         if (async_chunk->inode)
1263                 submit_compressed_extents(async_chunk);
1264 }
1265
1266 static noinline void async_cow_free(struct btrfs_work *work)
1267 {
1268         struct async_chunk *async_chunk;
1269
1270         async_chunk = container_of(work, struct async_chunk, work);
1271         if (async_chunk->inode)
1272                 btrfs_add_delayed_iput(async_chunk->inode);
1273         if (async_chunk->blkcg_css)
1274                 css_put(async_chunk->blkcg_css);
1275         /*
1276          * Since the pointer to 'pending' is at the beginning of the array of
1277          * async_chunk's, freeing it ensures the whole array has been freed.
1278          */
1279         if (atomic_dec_and_test(async_chunk->pending))
1280                 kvfree(async_chunk->pending);
1281 }
1282
1283 static int cow_file_range_async(struct btrfs_inode *inode,
1284                                 struct writeback_control *wbc,
1285                                 struct page *locked_page,
1286                                 u64 start, u64 end, int *page_started,
1287                                 unsigned long *nr_written)
1288 {
1289         struct btrfs_fs_info *fs_info = inode->root->fs_info;
1290         struct cgroup_subsys_state *blkcg_css = wbc_blkcg_css(wbc);
1291         struct async_cow *ctx;
1292         struct async_chunk *async_chunk;
1293         unsigned long nr_pages;
1294         u64 cur_end;
1295         u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1296         int i;
1297         bool should_compress;
1298         unsigned nofs_flag;
1299         const unsigned int write_flags = wbc_to_write_flags(wbc);
1300
1301         unlock_extent(&inode->io_tree, start, end);
1302
1303         if (inode->flags & BTRFS_INODE_NOCOMPRESS &&
1304             !btrfs_test_opt(fs_info, FORCE_COMPRESS)) {
1305                 num_chunks = 1;
1306                 should_compress = false;
1307         } else {
1308                 should_compress = true;
1309         }
1310
1311         nofs_flag = memalloc_nofs_save();
1312         ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
1313         memalloc_nofs_restore(nofs_flag);
1314
1315         if (!ctx) {
1316                 unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC |
1317                         EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1318                         EXTENT_DO_ACCOUNTING;
1319                 unsigned long page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK |
1320                                          PAGE_END_WRITEBACK | PAGE_SET_ERROR;
1321
1322                 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1323                                              clear_bits, page_ops);
1324                 return -ENOMEM;
1325         }
1326
1327         async_chunk = ctx->chunks;
1328         atomic_set(&ctx->num_chunks, num_chunks);
1329
1330         for (i = 0; i < num_chunks; i++) {
1331                 if (should_compress)
1332                         cur_end = min(end, start + SZ_512K - 1);
1333                 else
1334                         cur_end = end;
1335
1336                 /*
1337                  * igrab is called higher up in the call chain, take only the
1338                  * lightweight reference for the callback lifetime
1339                  */
1340                 ihold(&inode->vfs_inode);
1341                 async_chunk[i].pending = &ctx->num_chunks;
1342                 async_chunk[i].inode = &inode->vfs_inode;
1343                 async_chunk[i].start = start;
1344                 async_chunk[i].end = cur_end;
1345                 async_chunk[i].write_flags = write_flags;
1346                 INIT_LIST_HEAD(&async_chunk[i].extents);
1347
1348                 /*
1349                  * The locked_page comes all the way from writepage and its
1350                  * the original page we were actually given.  As we spread
1351                  * this large delalloc region across multiple async_chunk
1352                  * structs, only the first struct needs a pointer to locked_page
1353                  *
1354                  * This way we don't need racey decisions about who is supposed
1355                  * to unlock it.
1356                  */
1357                 if (locked_page) {
1358                         /*
1359                          * Depending on the compressibility, the pages might or
1360                          * might not go through async.  We want all of them to
1361                          * be accounted against wbc once.  Let's do it here
1362                          * before the paths diverge.  wbc accounting is used
1363                          * only for foreign writeback detection and doesn't
1364                          * need full accuracy.  Just account the whole thing
1365                          * against the first page.
1366                          */
1367                         wbc_account_cgroup_owner(wbc, locked_page,
1368                                                  cur_end - start);
1369                         async_chunk[i].locked_page = locked_page;
1370                         locked_page = NULL;
1371                 } else {
1372                         async_chunk[i].locked_page = NULL;
1373                 }
1374
1375                 if (blkcg_css != blkcg_root_css) {
1376                         css_get(blkcg_css);
1377                         async_chunk[i].blkcg_css = blkcg_css;
1378                 } else {
1379                         async_chunk[i].blkcg_css = NULL;
1380                 }
1381
1382                 btrfs_init_work(&async_chunk[i].work, async_cow_start,
1383                                 async_cow_submit, async_cow_free);
1384
1385                 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1386                 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1387
1388                 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1389
1390                 *nr_written += nr_pages;
1391                 start = cur_end + 1;
1392         }
1393         *page_started = 1;
1394         return 0;
1395 }
1396
1397 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1398                                         u64 bytenr, u64 num_bytes)
1399 {
1400         int ret;
1401         struct btrfs_ordered_sum *sums;
1402         LIST_HEAD(list);
1403
1404         ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1405                                        bytenr + num_bytes - 1, &list, 0);
1406         if (ret == 0 && list_empty(&list))
1407                 return 0;
1408
1409         while (!list_empty(&list)) {
1410                 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1411                 list_del(&sums->list);
1412                 kfree(sums);
1413         }
1414         if (ret < 0)
1415                 return ret;
1416         return 1;
1417 }
1418
1419 static int fallback_to_cow(struct btrfs_inode *inode, struct page *locked_page,
1420                            const u64 start, const u64 end,
1421                            int *page_started, unsigned long *nr_written)
1422 {
1423         const bool is_space_ino = btrfs_is_free_space_inode(inode);
1424         const bool is_reloc_ino = (inode->root->root_key.objectid ==
1425                                    BTRFS_DATA_RELOC_TREE_OBJECTID);
1426         const u64 range_bytes = end + 1 - start;
1427         struct extent_io_tree *io_tree = &inode->io_tree;
1428         u64 range_start = start;
1429         u64 count;
1430
1431         /*
1432          * If EXTENT_NORESERVE is set it means that when the buffered write was
1433          * made we had not enough available data space and therefore we did not
1434          * reserve data space for it, since we though we could do NOCOW for the
1435          * respective file range (either there is prealloc extent or the inode
1436          * has the NOCOW bit set).
1437          *
1438          * However when we need to fallback to COW mode (because for example the
1439          * block group for the corresponding extent was turned to RO mode by a
1440          * scrub or relocation) we need to do the following:
1441          *
1442          * 1) We increment the bytes_may_use counter of the data space info.
1443          *    If COW succeeds, it allocates a new data extent and after doing
1444          *    that it decrements the space info's bytes_may_use counter and
1445          *    increments its bytes_reserved counter by the same amount (we do
1446          *    this at btrfs_add_reserved_bytes()). So we need to increment the
1447          *    bytes_may_use counter to compensate (when space is reserved at
1448          *    buffered write time, the bytes_may_use counter is incremented);
1449          *
1450          * 2) We clear the EXTENT_NORESERVE bit from the range. We do this so
1451          *    that if the COW path fails for any reason, it decrements (through
1452          *    extent_clear_unlock_delalloc()) the bytes_may_use counter of the
1453          *    data space info, which we incremented in the step above.
1454          *
1455          * If we need to fallback to cow and the inode corresponds to a free
1456          * space cache inode or an inode of the data relocation tree, we must
1457          * also increment bytes_may_use of the data space_info for the same
1458          * reason. Space caches and relocated data extents always get a prealloc
1459          * extent for them, however scrub or balance may have set the block
1460          * group that contains that extent to RO mode and therefore force COW
1461          * when starting writeback.
1462          */
1463         count = count_range_bits(io_tree, &range_start, end, range_bytes,
1464                                  EXTENT_NORESERVE, 0);
1465         if (count > 0 || is_space_ino || is_reloc_ino) {
1466                 u64 bytes = count;
1467                 struct btrfs_fs_info *fs_info = inode->root->fs_info;
1468                 struct btrfs_space_info *sinfo = fs_info->data_sinfo;
1469
1470                 if (is_space_ino || is_reloc_ino)
1471                         bytes = range_bytes;
1472
1473                 spin_lock(&sinfo->lock);
1474                 btrfs_space_info_update_bytes_may_use(fs_info, sinfo, bytes);
1475                 spin_unlock(&sinfo->lock);
1476
1477                 if (count > 0)
1478                         clear_extent_bit(io_tree, start, end, EXTENT_NORESERVE,
1479                                          0, 0, NULL);
1480         }
1481
1482         return cow_file_range(inode, locked_page, start, end, page_started,
1483                               nr_written, 1);
1484 }
1485
1486 /*
1487  * when nowcow writeback call back.  This checks for snapshots or COW copies
1488  * of the extents that exist in the file, and COWs the file as required.
1489  *
1490  * If no cow copies or snapshots exist, we write directly to the existing
1491  * blocks on disk
1492  */
1493 static noinline int run_delalloc_nocow(struct btrfs_inode *inode,
1494                                        struct page *locked_page,
1495                                        const u64 start, const u64 end,
1496                                        int *page_started, int force,
1497                                        unsigned long *nr_written)
1498 {
1499         struct btrfs_fs_info *fs_info = inode->root->fs_info;
1500         struct btrfs_root *root = inode->root;
1501         struct btrfs_path *path;
1502         u64 cow_start = (u64)-1;
1503         u64 cur_offset = start;
1504         int ret;
1505         bool check_prev = true;
1506         const bool freespace_inode = btrfs_is_free_space_inode(inode);
1507         u64 ino = btrfs_ino(inode);
1508         bool nocow = false;
1509         u64 disk_bytenr = 0;
1510
1511         path = btrfs_alloc_path();
1512         if (!path) {
1513                 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1514                                              EXTENT_LOCKED | EXTENT_DELALLOC |
1515                                              EXTENT_DO_ACCOUNTING |
1516                                              EXTENT_DEFRAG, PAGE_UNLOCK |
1517                                              PAGE_START_WRITEBACK |
1518                                              PAGE_END_WRITEBACK);
1519                 return -ENOMEM;
1520         }
1521
1522         while (1) {
1523                 struct btrfs_key found_key;
1524                 struct btrfs_file_extent_item *fi;
1525                 struct extent_buffer *leaf;
1526                 u64 extent_end;
1527                 u64 extent_offset;
1528                 u64 num_bytes = 0;
1529                 u64 disk_num_bytes;
1530                 u64 ram_bytes;
1531                 int extent_type;
1532
1533                 nocow = false;
1534
1535                 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1536                                                cur_offset, 0);
1537                 if (ret < 0)
1538                         goto error;
1539
1540                 /*
1541                  * If there is no extent for our range when doing the initial
1542                  * search, then go back to the previous slot as it will be the
1543                  * one containing the search offset
1544                  */
1545                 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1546                         leaf = path->nodes[0];
1547                         btrfs_item_key_to_cpu(leaf, &found_key,
1548                                               path->slots[0] - 1);
1549                         if (found_key.objectid == ino &&
1550                             found_key.type == BTRFS_EXTENT_DATA_KEY)
1551                                 path->slots[0]--;
1552                 }
1553                 check_prev = false;
1554 next_slot:
1555                 /* Go to next leaf if we have exhausted the current one */
1556                 leaf = path->nodes[0];
1557                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1558                         ret = btrfs_next_leaf(root, path);
1559                         if (ret < 0) {
1560                                 if (cow_start != (u64)-1)
1561                                         cur_offset = cow_start;
1562                                 goto error;
1563                         }
1564                         if (ret > 0)
1565                                 break;
1566                         leaf = path->nodes[0];
1567                 }
1568
1569                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1570
1571                 /* Didn't find anything for our INO */
1572                 if (found_key.objectid > ino)
1573                         break;
1574                 /*
1575                  * Keep searching until we find an EXTENT_ITEM or there are no
1576                  * more extents for this inode
1577                  */
1578                 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1579                     found_key.type < BTRFS_EXTENT_DATA_KEY) {
1580                         path->slots[0]++;
1581                         goto next_slot;
1582                 }
1583
1584                 /* Found key is not EXTENT_DATA_KEY or starts after req range */
1585                 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1586                     found_key.offset > end)
1587                         break;
1588
1589                 /*
1590                  * If the found extent starts after requested offset, then
1591                  * adjust extent_end to be right before this extent begins
1592                  */
1593                 if (found_key.offset > cur_offset) {
1594                         extent_end = found_key.offset;
1595                         extent_type = 0;
1596                         goto out_check;
1597                 }
1598
1599                 /*
1600                  * Found extent which begins before our range and potentially
1601                  * intersect it
1602                  */
1603                 fi = btrfs_item_ptr(leaf, path->slots[0],
1604                                     struct btrfs_file_extent_item);
1605                 extent_type = btrfs_file_extent_type(leaf, fi);
1606
1607                 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1608                 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1609                     extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1610                         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1611                         extent_offset = btrfs_file_extent_offset(leaf, fi);
1612                         extent_end = found_key.offset +
1613                                 btrfs_file_extent_num_bytes(leaf, fi);
1614                         disk_num_bytes =
1615                                 btrfs_file_extent_disk_num_bytes(leaf, fi);
1616                         /*
1617                          * If the extent we got ends before our current offset,
1618                          * skip to the next extent.
1619                          */
1620                         if (extent_end <= cur_offset) {
1621                                 path->slots[0]++;
1622                                 goto next_slot;
1623                         }
1624                         /* Skip holes */
1625                         if (disk_bytenr == 0)
1626                                 goto out_check;
1627                         /* Skip compressed/encrypted/encoded extents */
1628                         if (btrfs_file_extent_compression(leaf, fi) ||
1629                             btrfs_file_extent_encryption(leaf, fi) ||
1630                             btrfs_file_extent_other_encoding(leaf, fi))
1631                                 goto out_check;
1632                         /*
1633                          * If extent is created before the last volume's snapshot
1634                          * this implies the extent is shared, hence we can't do
1635                          * nocow. This is the same check as in
1636                          * btrfs_cross_ref_exist but without calling
1637                          * btrfs_search_slot.
1638                          */
1639                         if (!freespace_inode &&
1640                             btrfs_file_extent_generation(leaf, fi) <=
1641                             btrfs_root_last_snapshot(&root->root_item))
1642                                 goto out_check;
1643                         if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1644                                 goto out_check;
1645
1646                         /*
1647                          * The following checks can be expensive, as they need to
1648                          * take other locks and do btree or rbtree searches, so
1649                          * release the path to avoid blocking other tasks for too
1650                          * long.
1651                          */
1652                         btrfs_release_path(path);
1653
1654                         /* If extent is RO, we must COW it */
1655                         if (btrfs_extent_readonly(fs_info, disk_bytenr))
1656                                 goto out_check;
1657                         ret = btrfs_cross_ref_exist(root, ino,
1658                                                     found_key.offset -
1659                                                     extent_offset, disk_bytenr, false);
1660                         if (ret) {
1661                                 /*
1662                                  * ret could be -EIO if the above fails to read
1663                                  * metadata.
1664                                  */
1665                                 if (ret < 0) {
1666                                         if (cow_start != (u64)-1)
1667                                                 cur_offset = cow_start;
1668                                         goto error;
1669                                 }
1670
1671                                 WARN_ON_ONCE(freespace_inode);
1672                                 goto out_check;
1673                         }
1674                         disk_bytenr += extent_offset;
1675                         disk_bytenr += cur_offset - found_key.offset;
1676                         num_bytes = min(end + 1, extent_end) - cur_offset;
1677                         /*
1678                          * If there are pending snapshots for this root, we
1679                          * fall into common COW way
1680                          */
1681                         if (!freespace_inode && atomic_read(&root->snapshot_force_cow))
1682                                 goto out_check;
1683                         /*
1684                          * force cow if csum exists in the range.
1685                          * this ensure that csum for a given extent are
1686                          * either valid or do not exist.
1687                          */
1688                         ret = csum_exist_in_range(fs_info, disk_bytenr,
1689                                                   num_bytes);
1690                         if (ret) {
1691                                 /*
1692                                  * ret could be -EIO if the above fails to read
1693                                  * metadata.
1694                                  */
1695                                 if (ret < 0) {
1696                                         if (cow_start != (u64)-1)
1697                                                 cur_offset = cow_start;
1698                                         goto error;
1699                                 }
1700                                 WARN_ON_ONCE(freespace_inode);
1701                                 goto out_check;
1702                         }
1703                         if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1704                                 goto out_check;
1705                         nocow = true;
1706                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1707                         extent_end = found_key.offset + ram_bytes;
1708                         extent_end = ALIGN(extent_end, fs_info->sectorsize);
1709                         /* Skip extents outside of our requested range */
1710                         if (extent_end <= start) {
1711                                 path->slots[0]++;
1712                                 goto next_slot;
1713                         }
1714                 } else {
1715                         /* If this triggers then we have a memory corruption */
1716                         BUG();
1717                 }
1718 out_check:
1719                 /*
1720                  * If nocow is false then record the beginning of the range
1721                  * that needs to be COWed
1722                  */
1723                 if (!nocow) {
1724                         if (cow_start == (u64)-1)
1725                                 cow_start = cur_offset;
1726                         cur_offset = extent_end;
1727                         if (cur_offset > end)
1728                                 break;
1729                         if (!path->nodes[0])
1730                                 continue;
1731                         path->slots[0]++;
1732                         goto next_slot;
1733                 }
1734
1735                 /*
1736                  * COW range from cow_start to found_key.offset - 1. As the key
1737                  * will contain the beginning of the first extent that can be
1738                  * NOCOW, following one which needs to be COW'ed
1739                  */
1740                 if (cow_start != (u64)-1) {
1741                         ret = fallback_to_cow(inode, locked_page,
1742                                               cow_start, found_key.offset - 1,
1743                                               page_started, nr_written);
1744                         if (ret)
1745                                 goto error;
1746                         cow_start = (u64)-1;
1747                 }
1748
1749                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1750                         u64 orig_start = found_key.offset - extent_offset;
1751                         struct extent_map *em;
1752
1753                         em = create_io_em(inode, cur_offset, num_bytes,
1754                                           orig_start,
1755                                           disk_bytenr, /* block_start */
1756                                           num_bytes, /* block_len */
1757                                           disk_num_bytes, /* orig_block_len */
1758                                           ram_bytes, BTRFS_COMPRESS_NONE,
1759                                           BTRFS_ORDERED_PREALLOC);
1760                         if (IS_ERR(em)) {
1761                                 ret = PTR_ERR(em);
1762                                 goto error;
1763                         }
1764                         free_extent_map(em);
1765                         ret = btrfs_add_ordered_extent(inode, cur_offset,
1766                                                        disk_bytenr, num_bytes,
1767                                                        num_bytes,
1768                                                        BTRFS_ORDERED_PREALLOC);
1769                         if (ret) {
1770                                 btrfs_drop_extent_cache(inode, cur_offset,
1771                                                         cur_offset + num_bytes - 1,
1772                                                         0);
1773                                 goto error;
1774                         }
1775                 } else {
1776                         ret = btrfs_add_ordered_extent(inode, cur_offset,
1777                                                        disk_bytenr, num_bytes,
1778                                                        num_bytes,
1779                                                        BTRFS_ORDERED_NOCOW);
1780                         if (ret)
1781                                 goto error;
1782                 }
1783
1784                 if (nocow)
1785                         btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1786                 nocow = false;
1787
1788                 if (root->root_key.objectid ==
1789                     BTRFS_DATA_RELOC_TREE_OBJECTID)
1790                         /*
1791                          * Error handled later, as we must prevent
1792                          * extent_clear_unlock_delalloc() in error handler
1793                          * from freeing metadata of created ordered extent.
1794                          */
1795                         ret = btrfs_reloc_clone_csums(inode, cur_offset,
1796                                                       num_bytes);
1797
1798                 extent_clear_unlock_delalloc(inode, cur_offset,
1799                                              cur_offset + num_bytes - 1,
1800                                              locked_page, EXTENT_LOCKED |
1801                                              EXTENT_DELALLOC |
1802                                              EXTENT_CLEAR_DATA_RESV,
1803                                              PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1804
1805                 cur_offset = extent_end;
1806
1807                 /*
1808                  * btrfs_reloc_clone_csums() error, now we're OK to call error
1809                  * handler, as metadata for created ordered extent will only
1810                  * be freed by btrfs_finish_ordered_io().
1811                  */
1812                 if (ret)
1813                         goto error;
1814                 if (cur_offset > end)
1815                         break;
1816         }
1817         btrfs_release_path(path);
1818
1819         if (cur_offset <= end && cow_start == (u64)-1)
1820                 cow_start = cur_offset;
1821
1822         if (cow_start != (u64)-1) {
1823                 cur_offset = end;
1824                 ret = fallback_to_cow(inode, locked_page, cow_start, end,
1825                                       page_started, nr_written);
1826                 if (ret)
1827                         goto error;
1828         }
1829
1830 error:
1831         if (nocow)
1832                 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1833
1834         if (ret && cur_offset < end)
1835                 extent_clear_unlock_delalloc(inode, cur_offset, end,
1836                                              locked_page, EXTENT_LOCKED |
1837                                              EXTENT_DELALLOC | EXTENT_DEFRAG |
1838                                              EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1839                                              PAGE_START_WRITEBACK |
1840                                              PAGE_END_WRITEBACK);
1841         btrfs_free_path(path);
1842         return ret;
1843 }
1844
1845 static inline int need_force_cow(struct btrfs_inode *inode, u64 start, u64 end)
1846 {
1847
1848         if (!(inode->flags & BTRFS_INODE_NODATACOW) &&
1849             !(inode->flags & BTRFS_INODE_PREALLOC))
1850                 return 0;
1851
1852         /*
1853          * @defrag_bytes is a hint value, no spinlock held here,
1854          * if is not zero, it means the file is defragging.
1855          * Force cow if given extent needs to be defragged.
1856          */
1857         if (inode->defrag_bytes &&
1858             test_range_bit(&inode->io_tree, start, end, EXTENT_DEFRAG, 0, NULL))
1859                 return 1;
1860
1861         return 0;
1862 }
1863
1864 /*
1865  * Function to process delayed allocation (create CoW) for ranges which are
1866  * being touched for the first time.
1867  */
1868 int btrfs_run_delalloc_range(struct btrfs_inode *inode, struct page *locked_page,
1869                 u64 start, u64 end, int *page_started, unsigned long *nr_written,
1870                 struct writeback_control *wbc)
1871 {
1872         int ret;
1873         int force_cow = need_force_cow(inode, start, end);
1874
1875         if (inode->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1876                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1877                                          page_started, 1, nr_written);
1878         } else if (inode->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1879                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1880                                          page_started, 0, nr_written);
1881         } else if (!inode_can_compress(inode) ||
1882                    !inode_need_compress(inode, start, end)) {
1883                 ret = cow_file_range(inode, locked_page, start, end,
1884                                      page_started, nr_written, 1);
1885         } else {
1886                 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &inode->runtime_flags);
1887                 ret = cow_file_range_async(inode, wbc, locked_page, start, end,
1888                                            page_started, nr_written);
1889         }
1890         if (ret)
1891                 btrfs_cleanup_ordered_extents(inode, locked_page, start,
1892                                               end - start + 1);
1893         return ret;
1894 }
1895
1896 void btrfs_split_delalloc_extent(struct inode *inode,
1897                                  struct extent_state *orig, u64 split)
1898 {
1899         u64 size;
1900
1901         /* not delalloc, ignore it */
1902         if (!(orig->state & EXTENT_DELALLOC))
1903                 return;
1904
1905         size = orig->end - orig->start + 1;
1906         if (size > BTRFS_MAX_EXTENT_SIZE) {
1907                 u32 num_extents;
1908                 u64 new_size;
1909
1910                 /*
1911                  * See the explanation in btrfs_merge_delalloc_extent, the same
1912                  * applies here, just in reverse.
1913                  */
1914                 new_size = orig->end - split + 1;
1915                 num_extents = count_max_extents(new_size);
1916                 new_size = split - orig->start;
1917                 num_extents += count_max_extents(new_size);
1918                 if (count_max_extents(size) >= num_extents)
1919                         return;
1920         }
1921
1922         spin_lock(&BTRFS_I(inode)->lock);
1923         btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1924         spin_unlock(&BTRFS_I(inode)->lock);
1925 }
1926
1927 /*
1928  * Handle merged delayed allocation extents so we can keep track of new extents
1929  * that are just merged onto old extents, such as when we are doing sequential
1930  * writes, so we can properly account for the metadata space we'll need.
1931  */
1932 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
1933                                  struct extent_state *other)
1934 {
1935         u64 new_size, old_size;
1936         u32 num_extents;
1937
1938         /* not delalloc, ignore it */
1939         if (!(other->state & EXTENT_DELALLOC))
1940                 return;
1941
1942         if (new->start > other->start)
1943                 new_size = new->end - other->start + 1;
1944         else
1945                 new_size = other->end - new->start + 1;
1946
1947         /* we're not bigger than the max, unreserve the space and go */
1948         if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1949                 spin_lock(&BTRFS_I(inode)->lock);
1950                 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1951                 spin_unlock(&BTRFS_I(inode)->lock);
1952                 return;
1953         }
1954
1955         /*
1956          * We have to add up either side to figure out how many extents were
1957          * accounted for before we merged into one big extent.  If the number of
1958          * extents we accounted for is <= the amount we need for the new range
1959          * then we can return, otherwise drop.  Think of it like this
1960          *
1961          * [ 4k][MAX_SIZE]
1962          *
1963          * So we've grown the extent by a MAX_SIZE extent, this would mean we
1964          * need 2 outstanding extents, on one side we have 1 and the other side
1965          * we have 1 so they are == and we can return.  But in this case
1966          *
1967          * [MAX_SIZE+4k][MAX_SIZE+4k]
1968          *
1969          * Each range on their own accounts for 2 extents, but merged together
1970          * they are only 3 extents worth of accounting, so we need to drop in
1971          * this case.
1972          */
1973         old_size = other->end - other->start + 1;
1974         num_extents = count_max_extents(old_size);
1975         old_size = new->end - new->start + 1;
1976         num_extents += count_max_extents(old_size);
1977         if (count_max_extents(new_size) >= num_extents)
1978                 return;
1979
1980         spin_lock(&BTRFS_I(inode)->lock);
1981         btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1982         spin_unlock(&BTRFS_I(inode)->lock);
1983 }
1984
1985 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1986                                       struct inode *inode)
1987 {
1988         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1989
1990         spin_lock(&root->delalloc_lock);
1991         if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1992                 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1993                               &root->delalloc_inodes);
1994                 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1995                         &BTRFS_I(inode)->runtime_flags);
1996                 root->nr_delalloc_inodes++;
1997                 if (root->nr_delalloc_inodes == 1) {
1998                         spin_lock(&fs_info->delalloc_root_lock);
1999                         BUG_ON(!list_empty(&root->delalloc_root));
2000                         list_add_tail(&root->delalloc_root,
2001                                       &fs_info->delalloc_roots);
2002                         spin_unlock(&fs_info->delalloc_root_lock);
2003                 }
2004         }
2005         spin_unlock(&root->delalloc_lock);
2006 }
2007
2008
2009 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
2010                                 struct btrfs_inode *inode)
2011 {
2012         struct btrfs_fs_info *fs_info = root->fs_info;
2013
2014         if (!list_empty(&inode->delalloc_inodes)) {
2015                 list_del_init(&inode->delalloc_inodes);
2016                 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2017                           &inode->runtime_flags);
2018                 root->nr_delalloc_inodes--;
2019                 if (!root->nr_delalloc_inodes) {
2020                         ASSERT(list_empty(&root->delalloc_inodes));
2021                         spin_lock(&fs_info->delalloc_root_lock);
2022                         BUG_ON(list_empty(&root->delalloc_root));
2023                         list_del_init(&root->delalloc_root);
2024                         spin_unlock(&fs_info->delalloc_root_lock);
2025                 }
2026         }
2027 }
2028
2029 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
2030                                      struct btrfs_inode *inode)
2031 {
2032         spin_lock(&root->delalloc_lock);
2033         __btrfs_del_delalloc_inode(root, inode);
2034         spin_unlock(&root->delalloc_lock);
2035 }
2036
2037 /*
2038  * Properly track delayed allocation bytes in the inode and to maintain the
2039  * list of inodes that have pending delalloc work to be done.
2040  */
2041 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
2042                                unsigned *bits)
2043 {
2044         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2045
2046         if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
2047                 WARN_ON(1);
2048         /*
2049          * set_bit and clear bit hooks normally require _irqsave/restore
2050          * but in this case, we are only testing for the DELALLOC
2051          * bit, which is only set or cleared with irqs on
2052          */
2053         if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
2054                 struct btrfs_root *root = BTRFS_I(inode)->root;
2055                 u64 len = state->end + 1 - state->start;
2056                 u32 num_extents = count_max_extents(len);
2057                 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
2058
2059                 spin_lock(&BTRFS_I(inode)->lock);
2060                 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
2061                 spin_unlock(&BTRFS_I(inode)->lock);
2062
2063                 /* For sanity tests */
2064                 if (btrfs_is_testing(fs_info))
2065                         return;
2066
2067                 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
2068                                          fs_info->delalloc_batch);
2069                 spin_lock(&BTRFS_I(inode)->lock);
2070                 BTRFS_I(inode)->delalloc_bytes += len;
2071                 if (*bits & EXTENT_DEFRAG)
2072                         BTRFS_I(inode)->defrag_bytes += len;
2073                 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2074                                          &BTRFS_I(inode)->runtime_flags))
2075                         btrfs_add_delalloc_inodes(root, inode);
2076                 spin_unlock(&BTRFS_I(inode)->lock);
2077         }
2078
2079         if (!(state->state & EXTENT_DELALLOC_NEW) &&
2080             (*bits & EXTENT_DELALLOC_NEW)) {
2081                 spin_lock(&BTRFS_I(inode)->lock);
2082                 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
2083                         state->start;
2084                 spin_unlock(&BTRFS_I(inode)->lock);
2085         }
2086 }
2087
2088 /*
2089  * Once a range is no longer delalloc this function ensures that proper
2090  * accounting happens.
2091  */
2092 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
2093                                  struct extent_state *state, unsigned *bits)
2094 {
2095         struct btrfs_inode *inode = BTRFS_I(vfs_inode);
2096         struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
2097         u64 len = state->end + 1 - state->start;
2098         u32 num_extents = count_max_extents(len);
2099
2100         if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
2101                 spin_lock(&inode->lock);
2102                 inode->defrag_bytes -= len;
2103                 spin_unlock(&inode->lock);
2104         }
2105
2106         /*
2107          * set_bit and clear bit hooks normally require _irqsave/restore
2108          * but in this case, we are only testing for the DELALLOC
2109          * bit, which is only set or cleared with irqs on
2110          */
2111         if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
2112                 struct btrfs_root *root = inode->root;
2113                 bool do_list = !btrfs_is_free_space_inode(inode);
2114
2115                 spin_lock(&inode->lock);
2116                 btrfs_mod_outstanding_extents(inode, -num_extents);
2117                 spin_unlock(&inode->lock);
2118
2119                 /*
2120                  * We don't reserve metadata space for space cache inodes so we
2121                  * don't need to call delalloc_release_metadata if there is an
2122                  * error.
2123                  */
2124                 if (*bits & EXTENT_CLEAR_META_RESV &&
2125                     root != fs_info->tree_root)
2126                         btrfs_delalloc_release_metadata(inode, len, false);
2127
2128                 /* For sanity tests. */
2129                 if (btrfs_is_testing(fs_info))
2130                         return;
2131
2132                 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
2133                     do_list && !(state->state & EXTENT_NORESERVE) &&
2134                     (*bits & EXTENT_CLEAR_DATA_RESV))
2135                         btrfs_free_reserved_data_space_noquota(fs_info, len);
2136
2137                 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
2138                                          fs_info->delalloc_batch);
2139                 spin_lock(&inode->lock);
2140                 inode->delalloc_bytes -= len;
2141                 if (do_list && inode->delalloc_bytes == 0 &&
2142                     test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2143                                         &inode->runtime_flags))
2144                         btrfs_del_delalloc_inode(root, inode);
2145                 spin_unlock(&inode->lock);
2146         }
2147
2148         if ((state->state & EXTENT_DELALLOC_NEW) &&
2149             (*bits & EXTENT_DELALLOC_NEW)) {
2150                 spin_lock(&inode->lock);
2151                 ASSERT(inode->new_delalloc_bytes >= len);
2152                 inode->new_delalloc_bytes -= len;
2153                 if (*bits & EXTENT_ADD_INODE_BYTES)
2154                         inode_add_bytes(&inode->vfs_inode, len);
2155                 spin_unlock(&inode->lock);
2156         }
2157 }
2158
2159 /*
2160  * btrfs_bio_fits_in_stripe - Checks whether the size of the given bio will fit
2161  * in a chunk's stripe. This function ensures that bios do not span a
2162  * stripe/chunk
2163  *
2164  * @page - The page we are about to add to the bio
2165  * @size - size we want to add to the bio
2166  * @bio - bio we want to ensure is smaller than a stripe
2167  * @bio_flags - flags of the bio
2168  *
2169  * return 1 if page cannot be added to the bio
2170  * return 0 if page can be added to the bio
2171  * return error otherwise
2172  */
2173 int btrfs_bio_fits_in_stripe(struct page *page, size_t size, struct bio *bio,
2174                              unsigned long bio_flags)
2175 {
2176         struct inode *inode = page->mapping->host;
2177         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2178         u64 logical = bio->bi_iter.bi_sector << 9;
2179         struct extent_map *em;
2180         u64 length = 0;
2181         u64 map_length;
2182         int ret = 0;
2183         struct btrfs_io_geometry geom;
2184
2185         if (bio_flags & EXTENT_BIO_COMPRESSED)
2186                 return 0;
2187
2188         length = bio->bi_iter.bi_size;
2189         map_length = length;
2190         em = btrfs_get_chunk_map(fs_info, logical, map_length);
2191         if (IS_ERR(em))
2192                 return PTR_ERR(em);
2193         ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(bio), logical,
2194                                     map_length, &geom);
2195         if (ret < 0)
2196                 goto out;
2197
2198         if (geom.len < length + size)
2199                 ret = 1;
2200 out:
2201         free_extent_map(em);
2202         return ret;
2203 }
2204
2205 /*
2206  * in order to insert checksums into the metadata in large chunks,
2207  * we wait until bio submission time.   All the pages in the bio are
2208  * checksummed and sums are attached onto the ordered extent record.
2209  *
2210  * At IO completion time the cums attached on the ordered extent record
2211  * are inserted into the btree
2212  */
2213 static blk_status_t btrfs_submit_bio_start(struct inode *inode, struct bio *bio,
2214                                            u64 dio_file_offset)
2215 {
2216         return btrfs_csum_one_bio(BTRFS_I(inode), bio, 0, 0);
2217 }
2218
2219 bool btrfs_bio_fits_in_ordered_extent(struct page *page, struct bio *bio,
2220                                       unsigned int size)
2221 {
2222         struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
2223         struct btrfs_fs_info *fs_info = inode->root->fs_info;
2224         struct btrfs_ordered_extent *ordered;
2225         u64 len = bio->bi_iter.bi_size + size;
2226         bool ret = true;
2227
2228         ASSERT(btrfs_is_zoned(fs_info));
2229         ASSERT(fs_info->max_zone_append_size > 0);
2230         ASSERT(bio_op(bio) == REQ_OP_ZONE_APPEND);
2231
2232         /* Ordered extent not yet created, so we're good */
2233         ordered = btrfs_lookup_ordered_extent(inode, page_offset(page));
2234         if (!ordered)
2235                 return ret;
2236
2237         if ((bio->bi_iter.bi_sector << SECTOR_SHIFT) + len >
2238             ordered->disk_bytenr + ordered->disk_num_bytes)
2239                 ret = false;
2240
2241         btrfs_put_ordered_extent(ordered);
2242
2243         return ret;
2244 }
2245
2246 static blk_status_t extract_ordered_extent(struct btrfs_inode *inode,
2247                                            struct bio *bio, loff_t file_offset)
2248 {
2249         struct btrfs_ordered_extent *ordered;
2250         struct extent_map *em = NULL, *em_new = NULL;
2251         struct extent_map_tree *em_tree = &inode->extent_tree;
2252         u64 start = (u64)bio->bi_iter.bi_sector << SECTOR_SHIFT;
2253         u64 len = bio->bi_iter.bi_size;
2254         u64 end = start + len;
2255         u64 ordered_end;
2256         u64 pre, post;
2257         int ret = 0;
2258
2259         ordered = btrfs_lookup_ordered_extent(inode, file_offset);
2260         if (WARN_ON_ONCE(!ordered))
2261                 return BLK_STS_IOERR;
2262
2263         /* No need to split */
2264         if (ordered->disk_num_bytes == len)
2265                 goto out;
2266
2267         /* We cannot split once end_bio'd ordered extent */
2268         if (WARN_ON_ONCE(ordered->bytes_left != ordered->disk_num_bytes)) {
2269                 ret = -EINVAL;
2270                 goto out;
2271         }
2272
2273         /* We cannot split a compressed ordered extent */
2274         if (WARN_ON_ONCE(ordered->disk_num_bytes != ordered->num_bytes)) {
2275                 ret = -EINVAL;
2276                 goto out;
2277         }
2278
2279         ordered_end = ordered->disk_bytenr + ordered->disk_num_bytes;
2280         /* bio must be in one ordered extent */
2281         if (WARN_ON_ONCE(start < ordered->disk_bytenr || end > ordered_end)) {
2282                 ret = -EINVAL;
2283                 goto out;
2284         }
2285
2286         /* Checksum list should be empty */
2287         if (WARN_ON_ONCE(!list_empty(&ordered->list))) {
2288                 ret = -EINVAL;
2289                 goto out;
2290         }
2291
2292         pre = start - ordered->disk_bytenr;
2293         post = ordered_end - end;
2294
2295         ret = btrfs_split_ordered_extent(ordered, pre, post);
2296         if (ret)
2297                 goto out;
2298
2299         read_lock(&em_tree->lock);
2300         em = lookup_extent_mapping(em_tree, ordered->file_offset, len);
2301         if (!em) {
2302                 read_unlock(&em_tree->lock);
2303                 ret = -EIO;
2304                 goto out;
2305         }
2306         read_unlock(&em_tree->lock);
2307
2308         ASSERT(!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags));
2309         /*
2310          * We cannot reuse em_new here but have to create a new one, as
2311          * unpin_extent_cache() expects the start of the extent map to be the
2312          * logical offset of the file, which does not hold true anymore after
2313          * splitting.
2314          */
2315         em_new = create_io_em(inode, em->start + pre, len,
2316                               em->start + pre, em->block_start + pre, len,
2317                               len, len, BTRFS_COMPRESS_NONE,
2318                               BTRFS_ORDERED_REGULAR);
2319         if (IS_ERR(em_new)) {
2320                 ret = PTR_ERR(em_new);
2321                 goto out;
2322         }
2323         free_extent_map(em_new);
2324
2325 out:
2326         free_extent_map(em);
2327         btrfs_put_ordered_extent(ordered);
2328
2329         return errno_to_blk_status(ret);
2330 }
2331
2332 /*
2333  * extent_io.c submission hook. This does the right thing for csum calculation
2334  * on write, or reading the csums from the tree before a read.
2335  *
2336  * Rules about async/sync submit,
2337  * a) read:                             sync submit
2338  *
2339  * b) write without checksum:           sync submit
2340  *
2341  * c) write with checksum:
2342  *    c-1) if bio is issued by fsync:   sync submit
2343  *         (sync_writers != 0)
2344  *
2345  *    c-2) if root is reloc root:       sync submit
2346  *         (only in case of buffered IO)
2347  *
2348  *    c-3) otherwise:                   async submit
2349  */
2350 blk_status_t btrfs_submit_data_bio(struct inode *inode, struct bio *bio,
2351                                    int mirror_num, unsigned long bio_flags)
2352
2353 {
2354         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2355         struct btrfs_root *root = BTRFS_I(inode)->root;
2356         enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
2357         blk_status_t ret = 0;
2358         int skip_sum;
2359         int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2360
2361         skip_sum = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM) ||
2362                    !fs_info->csum_root;
2363
2364         if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2365                 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2366
2367         if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
2368                 struct page *page = bio_first_bvec_all(bio)->bv_page;
2369                 loff_t file_offset = page_offset(page);
2370
2371                 ret = extract_ordered_extent(BTRFS_I(inode), bio, file_offset);
2372                 if (ret)
2373                         goto out;
2374         }
2375
2376         if (btrfs_op(bio) != BTRFS_MAP_WRITE) {
2377                 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2378                 if (ret)
2379                         goto out;
2380
2381                 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2382                         ret = btrfs_submit_compressed_read(inode, bio,
2383                                                            mirror_num,
2384                                                            bio_flags);
2385                         goto out;
2386                 } else {
2387                         /*
2388                          * Lookup bio sums does extra checks around whether we
2389                          * need to csum or not, which is why we ignore skip_sum
2390                          * here.
2391                          */
2392                         ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2393                         if (ret)
2394                                 goto out;
2395                 }
2396                 goto mapit;
2397         } else if (async && !skip_sum) {
2398                 /* csum items have already been cloned */
2399                 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2400                         goto mapit;
2401                 /* we're doing a write, do the async checksumming */
2402                 ret = btrfs_wq_submit_bio(inode, bio, mirror_num, bio_flags,
2403                                           0, btrfs_submit_bio_start);
2404                 goto out;
2405         } else if (!skip_sum) {
2406                 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, 0, 0);
2407                 if (ret)
2408                         goto out;
2409         }
2410
2411 mapit:
2412         ret = btrfs_map_bio(fs_info, bio, mirror_num);
2413
2414 out:
2415         if (ret) {
2416                 bio->bi_status = ret;
2417                 bio_endio(bio);
2418         }
2419         return ret;
2420 }
2421
2422 /*
2423  * given a list of ordered sums record them in the inode.  This happens
2424  * at IO completion time based on sums calculated at bio submission time.
2425  */
2426 static int add_pending_csums(struct btrfs_trans_handle *trans,
2427                              struct list_head *list)
2428 {
2429         struct btrfs_ordered_sum *sum;
2430         int ret;
2431
2432         list_for_each_entry(sum, list, list) {
2433                 trans->adding_csums = true;
2434                 ret = btrfs_csum_file_blocks(trans, trans->fs_info->csum_root, sum);
2435                 trans->adding_csums = false;
2436                 if (ret)
2437                         return ret;
2438         }
2439         return 0;
2440 }
2441
2442 static int btrfs_find_new_delalloc_bytes(struct btrfs_inode *inode,
2443                                          const u64 start,
2444                                          const u64 len,
2445                                          struct extent_state **cached_state)
2446 {
2447         u64 search_start = start;
2448         const u64 end = start + len - 1;
2449
2450         while (search_start < end) {
2451                 const u64 search_len = end - search_start + 1;
2452                 struct extent_map *em;
2453                 u64 em_len;
2454                 int ret = 0;
2455
2456                 em = btrfs_get_extent(inode, NULL, 0, search_start, search_len);
2457                 if (IS_ERR(em))
2458                         return PTR_ERR(em);
2459
2460                 if (em->block_start != EXTENT_MAP_HOLE)
2461                         goto next;
2462
2463                 em_len = em->len;
2464                 if (em->start < search_start)
2465                         em_len -= search_start - em->start;
2466                 if (em_len > search_len)
2467                         em_len = search_len;
2468
2469                 ret = set_extent_bit(&inode->io_tree, search_start,
2470                                      search_start + em_len - 1,
2471                                      EXTENT_DELALLOC_NEW, 0, NULL, cached_state,
2472                                      GFP_NOFS, NULL);
2473 next:
2474                 search_start = extent_map_end(em);
2475                 free_extent_map(em);
2476                 if (ret)
2477                         return ret;
2478         }
2479         return 0;
2480 }
2481
2482 int btrfs_set_extent_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2483                               unsigned int extra_bits,
2484                               struct extent_state **cached_state)
2485 {
2486         WARN_ON(PAGE_ALIGNED(end));
2487
2488         if (start >= i_size_read(&inode->vfs_inode) &&
2489             !(inode->flags & BTRFS_INODE_PREALLOC)) {
2490                 /*
2491                  * There can't be any extents following eof in this case so just
2492                  * set the delalloc new bit for the range directly.
2493                  */
2494                 extra_bits |= EXTENT_DELALLOC_NEW;
2495         } else {
2496                 int ret;
2497
2498                 ret = btrfs_find_new_delalloc_bytes(inode, start,
2499                                                     end + 1 - start,
2500                                                     cached_state);
2501                 if (ret)
2502                         return ret;
2503         }
2504
2505         return set_extent_delalloc(&inode->io_tree, start, end, extra_bits,
2506                                    cached_state);
2507 }
2508
2509 /* see btrfs_writepage_start_hook for details on why this is required */
2510 struct btrfs_writepage_fixup {
2511         struct page *page;
2512         struct inode *inode;
2513         struct btrfs_work work;
2514 };
2515
2516 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2517 {
2518         struct btrfs_writepage_fixup *fixup;
2519         struct btrfs_ordered_extent *ordered;
2520         struct extent_state *cached_state = NULL;
2521         struct extent_changeset *data_reserved = NULL;
2522         struct page *page;
2523         struct btrfs_inode *inode;
2524         u64 page_start;
2525         u64 page_end;
2526         int ret = 0;
2527         bool free_delalloc_space = true;
2528
2529         fixup = container_of(work, struct btrfs_writepage_fixup, work);
2530         page = fixup->page;
2531         inode = BTRFS_I(fixup->inode);
2532         page_start = page_offset(page);
2533         page_end = page_offset(page) + PAGE_SIZE - 1;
2534
2535         /*
2536          * This is similar to page_mkwrite, we need to reserve the space before
2537          * we take the page lock.
2538          */
2539         ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2540                                            PAGE_SIZE);
2541 again:
2542         lock_page(page);
2543
2544         /*
2545          * Before we queued this fixup, we took a reference on the page.
2546          * page->mapping may go NULL, but it shouldn't be moved to a different
2547          * address space.
2548          */
2549         if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2550                 /*
2551                  * Unfortunately this is a little tricky, either
2552                  *
2553                  * 1) We got here and our page had already been dealt with and
2554                  *    we reserved our space, thus ret == 0, so we need to just
2555                  *    drop our space reservation and bail.  This can happen the
2556                  *    first time we come into the fixup worker, or could happen
2557                  *    while waiting for the ordered extent.
2558                  * 2) Our page was already dealt with, but we happened to get an
2559                  *    ENOSPC above from the btrfs_delalloc_reserve_space.  In
2560                  *    this case we obviously don't have anything to release, but
2561                  *    because the page was already dealt with we don't want to
2562                  *    mark the page with an error, so make sure we're resetting
2563                  *    ret to 0.  This is why we have this check _before_ the ret
2564                  *    check, because we do not want to have a surprise ENOSPC
2565                  *    when the page was already properly dealt with.
2566                  */
2567                 if (!ret) {
2568                         btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2569                         btrfs_delalloc_release_space(inode, data_reserved,
2570                                                      page_start, PAGE_SIZE,
2571                                                      true);
2572                 }
2573                 ret = 0;
2574                 goto out_page;
2575         }
2576
2577         /*
2578          * We can't mess with the page state unless it is locked, so now that
2579          * it is locked bail if we failed to make our space reservation.
2580          */
2581         if (ret)
2582                 goto out_page;
2583
2584         lock_extent_bits(&inode->io_tree, page_start, page_end, &cached_state);
2585
2586         /* already ordered? We're done */
2587         if (PagePrivate2(page))
2588                 goto out_reserved;
2589
2590         ordered = btrfs_lookup_ordered_range(inode, page_start, PAGE_SIZE);
2591         if (ordered) {
2592                 unlock_extent_cached(&inode->io_tree, page_start, page_end,
2593                                      &cached_state);
2594                 unlock_page(page);
2595                 btrfs_start_ordered_extent(ordered, 1);
2596                 btrfs_put_ordered_extent(ordered);
2597                 goto again;
2598         }
2599
2600         ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2601                                         &cached_state);
2602         if (ret)
2603                 goto out_reserved;
2604
2605         /*
2606          * Everything went as planned, we're now the owner of a dirty page with
2607          * delayed allocation bits set and space reserved for our COW
2608          * destination.
2609          *
2610          * The page was dirty when we started, nothing should have cleaned it.
2611          */
2612         BUG_ON(!PageDirty(page));
2613         free_delalloc_space = false;
2614 out_reserved:
2615         btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2616         if (free_delalloc_space)
2617                 btrfs_delalloc_release_space(inode, data_reserved, page_start,
2618                                              PAGE_SIZE, true);
2619         unlock_extent_cached(&inode->io_tree, page_start, page_end,
2620                              &cached_state);
2621 out_page:
2622         if (ret) {
2623                 /*
2624                  * We hit ENOSPC or other errors.  Update the mapping and page
2625                  * to reflect the errors and clean the page.
2626                  */
2627                 mapping_set_error(page->mapping, ret);
2628                 end_extent_writepage(page, ret, page_start, page_end);
2629                 clear_page_dirty_for_io(page);
2630                 SetPageError(page);
2631         }
2632         ClearPageChecked(page);
2633         unlock_page(page);
2634         put_page(page);
2635         kfree(fixup);
2636         extent_changeset_free(data_reserved);
2637         /*
2638          * As a precaution, do a delayed iput in case it would be the last iput
2639          * that could need flushing space. Recursing back to fixup worker would
2640          * deadlock.
2641          */
2642         btrfs_add_delayed_iput(&inode->vfs_inode);
2643 }
2644
2645 /*
2646  * There are a few paths in the higher layers of the kernel that directly
2647  * set the page dirty bit without asking the filesystem if it is a
2648  * good idea.  This causes problems because we want to make sure COW
2649  * properly happens and the data=ordered rules are followed.
2650  *
2651  * In our case any range that doesn't have the ORDERED bit set
2652  * hasn't been properly setup for IO.  We kick off an async process
2653  * to fix it up.  The async helper will wait for ordered extents, set
2654  * the delalloc bit and make it safe to write the page.
2655  */
2656 int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end)
2657 {
2658         struct inode *inode = page->mapping->host;
2659         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2660         struct btrfs_writepage_fixup *fixup;
2661
2662         /* this page is properly in the ordered list */
2663         if (TestClearPagePrivate2(page))
2664                 return 0;
2665
2666         /*
2667          * PageChecked is set below when we create a fixup worker for this page,
2668          * don't try to create another one if we're already PageChecked()
2669          *
2670          * The extent_io writepage code will redirty the page if we send back
2671          * EAGAIN.
2672          */
2673         if (PageChecked(page))
2674                 return -EAGAIN;
2675
2676         fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2677         if (!fixup)
2678                 return -EAGAIN;
2679
2680         /*
2681          * We are already holding a reference to this inode from
2682          * write_cache_pages.  We need to hold it because the space reservation
2683          * takes place outside of the page lock, and we can't trust
2684          * page->mapping outside of the page lock.
2685          */
2686         ihold(inode);
2687         SetPageChecked(page);
2688         get_page(page);
2689         btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL, NULL);
2690         fixup->page = page;
2691         fixup->inode = inode;
2692         btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2693
2694         return -EAGAIN;
2695 }
2696
2697 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2698                                        struct btrfs_inode *inode, u64 file_pos,
2699                                        struct btrfs_file_extent_item *stack_fi,
2700                                        const bool update_inode_bytes,
2701                                        u64 qgroup_reserved)
2702 {
2703         struct btrfs_root *root = inode->root;
2704         const u64 sectorsize = root->fs_info->sectorsize;
2705         struct btrfs_path *path;
2706         struct extent_buffer *leaf;
2707         struct btrfs_key ins;
2708         u64 disk_num_bytes = btrfs_stack_file_extent_disk_num_bytes(stack_fi);
2709         u64 disk_bytenr = btrfs_stack_file_extent_disk_bytenr(stack_fi);
2710         u64 num_bytes = btrfs_stack_file_extent_num_bytes(stack_fi);
2711         u64 ram_bytes = btrfs_stack_file_extent_ram_bytes(stack_fi);
2712         struct btrfs_drop_extents_args drop_args = { 0 };
2713         int ret;
2714
2715         path = btrfs_alloc_path();
2716         if (!path)
2717                 return -ENOMEM;
2718
2719         /*
2720          * we may be replacing one extent in the tree with another.
2721          * The new extent is pinned in the extent map, and we don't want
2722          * to drop it from the cache until it is completely in the btree.
2723          *
2724          * So, tell btrfs_drop_extents to leave this extent in the cache.
2725          * the caller is expected to unpin it and allow it to be merged
2726          * with the others.
2727          */
2728         drop_args.path = path;
2729         drop_args.start = file_pos;
2730         drop_args.end = file_pos + num_bytes;
2731         drop_args.replace_extent = true;
2732         drop_args.extent_item_size = sizeof(*stack_fi);
2733         ret = btrfs_drop_extents(trans, root, inode, &drop_args);
2734         if (ret)
2735                 goto out;
2736
2737         if (!drop_args.extent_inserted) {
2738                 ins.objectid = btrfs_ino(inode);
2739                 ins.offset = file_pos;
2740                 ins.type = BTRFS_EXTENT_DATA_KEY;
2741
2742                 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2743                                               sizeof(*stack_fi));
2744                 if (ret)
2745                         goto out;
2746         }
2747         leaf = path->nodes[0];
2748         btrfs_set_stack_file_extent_generation(stack_fi, trans->transid);
2749         write_extent_buffer(leaf, stack_fi,
2750                         btrfs_item_ptr_offset(leaf, path->slots[0]),
2751                         sizeof(struct btrfs_file_extent_item));
2752
2753         btrfs_mark_buffer_dirty(leaf);
2754         btrfs_release_path(path);
2755
2756         /*
2757          * If we dropped an inline extent here, we know the range where it is
2758          * was not marked with the EXTENT_DELALLOC_NEW bit, so we update the
2759          * number of bytes only for that range contaning the inline extent.
2760          * The remaining of the range will be processed when clearning the
2761          * EXTENT_DELALLOC_BIT bit through the ordered extent completion.
2762          */
2763         if (file_pos == 0 && !IS_ALIGNED(drop_args.bytes_found, sectorsize)) {
2764                 u64 inline_size = round_down(drop_args.bytes_found, sectorsize);
2765
2766                 inline_size = drop_args.bytes_found - inline_size;
2767                 btrfs_update_inode_bytes(inode, sectorsize, inline_size);
2768                 drop_args.bytes_found -= inline_size;
2769                 num_bytes -= sectorsize;
2770         }
2771
2772         if (update_inode_bytes)
2773                 btrfs_update_inode_bytes(inode, num_bytes, drop_args.bytes_found);
2774
2775         ins.objectid = disk_bytenr;
2776         ins.offset = disk_num_bytes;
2777         ins.type = BTRFS_EXTENT_ITEM_KEY;
2778
2779         ret = btrfs_inode_set_file_extent_range(inode, file_pos, ram_bytes);
2780         if (ret)
2781                 goto out;
2782
2783         ret = btrfs_alloc_reserved_file_extent(trans, root, btrfs_ino(inode),
2784                                                file_pos, qgroup_reserved, &ins);
2785 out:
2786         btrfs_free_path(path);
2787
2788         return ret;
2789 }
2790
2791 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2792                                          u64 start, u64 len)
2793 {
2794         struct btrfs_block_group *cache;
2795
2796         cache = btrfs_lookup_block_group(fs_info, start);
2797         ASSERT(cache);
2798
2799         spin_lock(&cache->lock);
2800         cache->delalloc_bytes -= len;
2801         spin_unlock(&cache->lock);
2802
2803         btrfs_put_block_group(cache);
2804 }
2805
2806 static int insert_ordered_extent_file_extent(struct btrfs_trans_handle *trans,
2807                                              struct btrfs_ordered_extent *oe)
2808 {
2809         struct btrfs_file_extent_item stack_fi;
2810         u64 logical_len;
2811         bool update_inode_bytes;
2812
2813         memset(&stack_fi, 0, sizeof(stack_fi));
2814         btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_REG);
2815         btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, oe->disk_bytenr);
2816         btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi,
2817                                                    oe->disk_num_bytes);
2818         if (test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags))
2819                 logical_len = oe->truncated_len;
2820         else
2821                 logical_len = oe->num_bytes;
2822         btrfs_set_stack_file_extent_num_bytes(&stack_fi, logical_len);
2823         btrfs_set_stack_file_extent_ram_bytes(&stack_fi, logical_len);
2824         btrfs_set_stack_file_extent_compression(&stack_fi, oe->compress_type);
2825         /* Encryption and other encoding is reserved and all 0 */
2826
2827         /*
2828          * For delalloc, when completing an ordered extent we update the inode's
2829          * bytes when clearing the range in the inode's io tree, so pass false
2830          * as the argument 'update_inode_bytes' to insert_reserved_file_extent(),
2831          * except if the ordered extent was truncated.
2832          */
2833         update_inode_bytes = test_bit(BTRFS_ORDERED_DIRECT, &oe->flags) ||
2834                              test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags);
2835
2836         return insert_reserved_file_extent(trans, BTRFS_I(oe->inode),
2837                                            oe->file_offset, &stack_fi,
2838                                            update_inode_bytes, oe->qgroup_rsv);
2839 }
2840
2841 /*
2842  * As ordered data IO finishes, this gets called so we can finish
2843  * an ordered extent if the range of bytes in the file it covers are
2844  * fully written.
2845  */
2846 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2847 {
2848         struct btrfs_inode *inode = BTRFS_I(ordered_extent->inode);
2849         struct btrfs_root *root = inode->root;
2850         struct btrfs_fs_info *fs_info = root->fs_info;
2851         struct btrfs_trans_handle *trans = NULL;
2852         struct extent_io_tree *io_tree = &inode->io_tree;
2853         struct extent_state *cached_state = NULL;
2854         u64 start, end;
2855         int compress_type = 0;
2856         int ret = 0;
2857         u64 logical_len = ordered_extent->num_bytes;
2858         bool freespace_inode;
2859         bool truncated = false;
2860         bool clear_reserved_extent = true;
2861         unsigned int clear_bits = EXTENT_DEFRAG;
2862
2863         start = ordered_extent->file_offset;
2864         end = start + ordered_extent->num_bytes - 1;
2865
2866         if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2867             !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2868             !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2869                 clear_bits |= EXTENT_DELALLOC_NEW;
2870
2871         freespace_inode = btrfs_is_free_space_inode(inode);
2872
2873         if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2874                 ret = -EIO;
2875                 goto out;
2876         }
2877
2878         if (ordered_extent->disk)
2879                 btrfs_rewrite_logical_zoned(ordered_extent);
2880
2881         btrfs_free_io_failure_record(inode, start, end);
2882
2883         if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2884                 truncated = true;
2885                 logical_len = ordered_extent->truncated_len;
2886                 /* Truncated the entire extent, don't bother adding */
2887                 if (!logical_len)
2888                         goto out;
2889         }
2890
2891         if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2892                 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2893
2894                 btrfs_inode_safe_disk_i_size_write(inode, 0);
2895                 if (freespace_inode)
2896                         trans = btrfs_join_transaction_spacecache(root);
2897                 else
2898                         trans = btrfs_join_transaction(root);
2899                 if (IS_ERR(trans)) {
2900                         ret = PTR_ERR(trans);
2901                         trans = NULL;
2902                         goto out;
2903                 }
2904                 trans->block_rsv = &inode->block_rsv;
2905                 ret = btrfs_update_inode_fallback(trans, root, inode);
2906                 if (ret) /* -ENOMEM or corruption */
2907                         btrfs_abort_transaction(trans, ret);
2908                 goto out;
2909         }
2910
2911         clear_bits |= EXTENT_LOCKED;
2912         lock_extent_bits(io_tree, start, end, &cached_state);
2913
2914         if (freespace_inode)
2915                 trans = btrfs_join_transaction_spacecache(root);
2916         else
2917                 trans = btrfs_join_transaction(root);
2918         if (IS_ERR(trans)) {
2919                 ret = PTR_ERR(trans);
2920                 trans = NULL;
2921                 goto out;
2922         }
2923
2924         trans->block_rsv = &inode->block_rsv;
2925
2926         if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2927                 compress_type = ordered_extent->compress_type;
2928         if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2929                 BUG_ON(compress_type);
2930                 ret = btrfs_mark_extent_written(trans, inode,
2931                                                 ordered_extent->file_offset,
2932                                                 ordered_extent->file_offset +
2933                                                 logical_len);
2934         } else {
2935                 BUG_ON(root == fs_info->tree_root);
2936                 ret = insert_ordered_extent_file_extent(trans, ordered_extent);
2937                 if (!ret) {
2938                         clear_reserved_extent = false;
2939                         btrfs_release_delalloc_bytes(fs_info,
2940                                                 ordered_extent->disk_bytenr,
2941                                                 ordered_extent->disk_num_bytes);
2942                 }
2943         }
2944         unpin_extent_cache(&inode->extent_tree, ordered_extent->file_offset,
2945                            ordered_extent->num_bytes, trans->transid);
2946         if (ret < 0) {
2947                 btrfs_abort_transaction(trans, ret);
2948                 goto out;
2949         }
2950
2951         ret = add_pending_csums(trans, &ordered_extent->list);
2952         if (ret) {
2953                 btrfs_abort_transaction(trans, ret);
2954                 goto out;
2955         }
2956
2957         /*
2958          * If this is a new delalloc range, clear its new delalloc flag to
2959          * update the inode's number of bytes. This needs to be done first
2960          * before updating the inode item.
2961          */
2962         if ((clear_bits & EXTENT_DELALLOC_NEW) &&
2963             !test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags))
2964                 clear_extent_bit(&inode->io_tree, start, end,
2965                                  EXTENT_DELALLOC_NEW | EXTENT_ADD_INODE_BYTES,
2966                                  0, 0, &cached_state);
2967
2968         btrfs_inode_safe_disk_i_size_write(inode, 0);
2969         ret = btrfs_update_inode_fallback(trans, root, inode);
2970         if (ret) { /* -ENOMEM or corruption */
2971                 btrfs_abort_transaction(trans, ret);
2972                 goto out;
2973         }
2974         ret = 0;
2975 out:
2976         clear_extent_bit(&inode->io_tree, start, end, clear_bits,
2977                          (clear_bits & EXTENT_LOCKED) ? 1 : 0, 0,
2978                          &cached_state);
2979
2980         if (trans)
2981                 btrfs_end_transaction(trans);
2982
2983         if (ret || truncated) {
2984                 u64 unwritten_start = start;
2985
2986                 if (truncated)
2987                         unwritten_start += logical_len;
2988                 clear_extent_uptodate(io_tree, unwritten_start, end, NULL);
2989
2990                 /* Drop the cache for the part of the extent we didn't write. */
2991                 btrfs_drop_extent_cache(inode, unwritten_start, end, 0);
2992
2993                 /*
2994                  * If the ordered extent had an IOERR or something else went
2995                  * wrong we need to return the space for this ordered extent
2996                  * back to the allocator.  We only free the extent in the
2997                  * truncated case if we didn't write out the extent at all.
2998                  *
2999                  * If we made it past insert_reserved_file_extent before we
3000                  * errored out then we don't need to do this as the accounting
3001                  * has already been done.
3002                  */
3003                 if ((ret || !logical_len) &&
3004                     clear_reserved_extent &&
3005                     !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3006                     !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3007                         /*
3008                          * Discard the range before returning it back to the
3009                          * free space pool
3010                          */
3011                         if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
3012                                 btrfs_discard_extent(fs_info,
3013                                                 ordered_extent->disk_bytenr,
3014                                                 ordered_extent->disk_num_bytes,
3015                                                 NULL);
3016                         btrfs_free_reserved_extent(fs_info,
3017                                         ordered_extent->disk_bytenr,
3018                                         ordered_extent->disk_num_bytes, 1);
3019                 }
3020         }
3021
3022         /*
3023          * This needs to be done to make sure anybody waiting knows we are done
3024          * updating everything for this ordered extent.
3025          */
3026         btrfs_remove_ordered_extent(inode, ordered_extent);
3027
3028         /* once for us */
3029         btrfs_put_ordered_extent(ordered_extent);
3030         /* once for the tree */
3031         btrfs_put_ordered_extent(ordered_extent);
3032
3033         return ret;
3034 }
3035
3036 static void finish_ordered_fn(struct btrfs_work *work)
3037 {
3038         struct btrfs_ordered_extent *ordered_extent;
3039         ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3040         btrfs_finish_ordered_io(ordered_extent);
3041 }
3042
3043 void btrfs_writepage_endio_finish_ordered(struct page *page, u64 start,
3044                                           u64 end, int uptodate)
3045 {
3046         struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
3047         struct btrfs_fs_info *fs_info = inode->root->fs_info;
3048         struct btrfs_ordered_extent *ordered_extent = NULL;
3049         struct btrfs_workqueue *wq;
3050
3051         trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3052
3053         ClearPagePrivate2(page);
3054         if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3055                                             end - start + 1, uptodate))
3056                 return;
3057
3058         if (btrfs_is_free_space_inode(inode))
3059                 wq = fs_info->endio_freespace_worker;
3060         else
3061                 wq = fs_info->endio_write_workers;
3062
3063         btrfs_init_work(&ordered_extent->work, finish_ordered_fn, NULL, NULL);
3064         btrfs_queue_work(wq, &ordered_extent->work);
3065 }
3066
3067 /*
3068  * check_data_csum - verify checksum of one sector of uncompressed data
3069  * @inode:      inode
3070  * @io_bio:     btrfs_io_bio which contains the csum
3071  * @bio_offset: offset to the beginning of the bio (in bytes)
3072  * @page:       page where is the data to be verified
3073  * @pgoff:      offset inside the page
3074  *
3075  * The length of such check is always one sector size.
3076  */
3077 static int check_data_csum(struct inode *inode, struct btrfs_io_bio *io_bio,
3078                            u32 bio_offset, struct page *page, u32 pgoff)
3079 {
3080         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3081         SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3082         char *kaddr;
3083         u32 len = fs_info->sectorsize;
3084         const u32 csum_size = fs_info->csum_size;
3085         unsigned int offset_sectors;
3086         u8 *csum_expected;
3087         u8 csum[BTRFS_CSUM_SIZE];
3088
3089         ASSERT(pgoff + len <= PAGE_SIZE);
3090
3091         offset_sectors = bio_offset >> fs_info->sectorsize_bits;
3092         csum_expected = ((u8 *)io_bio->csum) + offset_sectors * csum_size;
3093
3094         kaddr = kmap_atomic(page);
3095         shash->tfm = fs_info->csum_shash;
3096
3097         crypto_shash_digest(shash, kaddr + pgoff, len, csum);
3098
3099         if (memcmp(csum, csum_expected, csum_size))
3100                 goto zeroit;
3101
3102         kunmap_atomic(kaddr);
3103         return 0;
3104 zeroit:
3105         btrfs_print_data_csum_error(BTRFS_I(inode), page_offset(page) + pgoff,
3106                                     csum, csum_expected, io_bio->mirror_num);
3107         if (io_bio->device)
3108                 btrfs_dev_stat_inc_and_print(io_bio->device,
3109                                              BTRFS_DEV_STAT_CORRUPTION_ERRS);
3110         memset(kaddr + pgoff, 1, len);
3111         flush_dcache_page(page);
3112         kunmap_atomic(kaddr);
3113         return -EIO;
3114 }
3115
3116 /*
3117  * When reads are done, we need to check csums to verify the data is correct.
3118  * if there's a match, we allow the bio to finish.  If not, the code in
3119  * extent_io.c will try to find good copies for us.
3120  *
3121  * @bio_offset: offset to the beginning of the bio (in bytes)
3122  * @start:      file offset of the range start
3123  * @end:        file offset of the range end (inclusive)
3124  * @mirror:     mirror number
3125  */
3126 int btrfs_verify_data_csum(struct btrfs_io_bio *io_bio, u32 bio_offset,
3127                            struct page *page, u64 start, u64 end, int mirror)
3128 {
3129         struct inode *inode = page->mapping->host;
3130         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3131         struct btrfs_root *root = BTRFS_I(inode)->root;
3132         const u32 sectorsize = root->fs_info->sectorsize;
3133         u32 pg_off;
3134
3135         if (PageChecked(page)) {
3136                 ClearPageChecked(page);
3137                 return 0;
3138         }
3139
3140         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3141                 return 0;
3142
3143         if (!root->fs_info->csum_root)
3144                 return 0;
3145
3146         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3147             test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3148                 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3149                 return 0;
3150         }
3151
3152         ASSERT(page_offset(page) <= start &&
3153                end <= page_offset(page) + PAGE_SIZE - 1);
3154         for (pg_off = offset_in_page(start);
3155              pg_off < offset_in_page(end);
3156              pg_off += sectorsize, bio_offset += sectorsize) {
3157                 int ret;
3158
3159                 ret = check_data_csum(inode, io_bio, bio_offset, page, pg_off);
3160                 if (ret < 0)
3161                         return -EIO;
3162         }
3163         return 0;
3164 }
3165
3166 /*
3167  * btrfs_add_delayed_iput - perform a delayed iput on @inode
3168  *
3169  * @inode: The inode we want to perform iput on
3170  *
3171  * This function uses the generic vfs_inode::i_count to track whether we should
3172  * just decrement it (in case it's > 1) or if this is the last iput then link
3173  * the inode to the delayed iput machinery. Delayed iputs are processed at
3174  * transaction commit time/superblock commit/cleaner kthread.
3175  */
3176 void btrfs_add_delayed_iput(struct inode *inode)
3177 {
3178         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3179         struct btrfs_inode *binode = BTRFS_I(inode);
3180
3181         if (atomic_add_unless(&inode->i_count, -1, 1))
3182                 return;
3183
3184         atomic_inc(&fs_info->nr_delayed_iputs);
3185         spin_lock(&fs_info->delayed_iput_lock);
3186         ASSERT(list_empty(&binode->delayed_iput));
3187         list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3188         spin_unlock(&fs_info->delayed_iput_lock);
3189         if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3190                 wake_up_process(fs_info->cleaner_kthread);
3191 }
3192
3193 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
3194                                     struct btrfs_inode *inode)
3195 {
3196         list_del_init(&inode->delayed_iput);
3197         spin_unlock(&fs_info->delayed_iput_lock);
3198         iput(&inode->vfs_inode);
3199         if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3200                 wake_up(&fs_info->delayed_iputs_wait);
3201         spin_lock(&fs_info->delayed_iput_lock);
3202 }
3203
3204 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
3205                                    struct btrfs_inode *inode)
3206 {
3207         if (!list_empty(&inode->delayed_iput)) {
3208                 spin_lock(&fs_info->delayed_iput_lock);
3209                 if (!list_empty(&inode->delayed_iput))
3210                         run_delayed_iput_locked(fs_info, inode);
3211                 spin_unlock(&fs_info->delayed_iput_lock);
3212         }
3213 }
3214
3215 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3216 {
3217
3218         spin_lock(&fs_info->delayed_iput_lock);
3219         while (!list_empty(&fs_info->delayed_iputs)) {
3220                 struct btrfs_inode *inode;
3221
3222                 inode = list_first_entry(&fs_info->delayed_iputs,
3223                                 struct btrfs_inode, delayed_iput);
3224                 run_delayed_iput_locked(fs_info, inode);
3225         }
3226         spin_unlock(&fs_info->delayed_iput_lock);
3227 }
3228
3229 /**
3230  * Wait for flushing all delayed iputs
3231  *
3232  * @fs_info:  the filesystem
3233  *
3234  * This will wait on any delayed iputs that are currently running with KILLABLE
3235  * set.  Once they are all done running we will return, unless we are killed in
3236  * which case we return EINTR. This helps in user operations like fallocate etc
3237  * that might get blocked on the iputs.
3238  *
3239  * Return EINTR if we were killed, 0 if nothing's pending
3240  */
3241 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3242 {
3243         int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3244                         atomic_read(&fs_info->nr_delayed_iputs) == 0);
3245         if (ret)
3246                 return -EINTR;
3247         return 0;
3248 }
3249
3250 /*
3251  * This creates an orphan entry for the given inode in case something goes wrong
3252  * in the middle of an unlink.
3253  */
3254 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3255                      struct btrfs_inode *inode)
3256 {
3257         int ret;
3258
3259         ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3260         if (ret && ret != -EEXIST) {
3261                 btrfs_abort_transaction(trans, ret);
3262                 return ret;
3263         }
3264
3265         return 0;
3266 }
3267
3268 /*
3269  * We have done the delete so we can go ahead and remove the orphan item for
3270  * this particular inode.
3271  */
3272 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3273                             struct btrfs_inode *inode)
3274 {
3275         return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3276 }
3277
3278 /*
3279  * this cleans up any orphans that may be left on the list from the last use
3280  * of this root.
3281  */
3282 int btrfs_orphan_cleanup(struct btrfs_root *root)
3283 {
3284         struct btrfs_fs_info *fs_info = root->fs_info;
3285         struct btrfs_path *path;
3286         struct extent_buffer *leaf;
3287         struct btrfs_key key, found_key;
3288         struct btrfs_trans_handle *trans;
3289         struct inode *inode;
3290         u64 last_objectid = 0;
3291         int ret = 0, nr_unlink = 0;
3292
3293         if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3294                 return 0;
3295
3296         path = btrfs_alloc_path();
3297         if (!path) {
3298                 ret = -ENOMEM;
3299                 goto out;
3300         }
3301         path->reada = READA_BACK;
3302
3303         key.objectid = BTRFS_ORPHAN_OBJECTID;
3304         key.type = BTRFS_ORPHAN_ITEM_KEY;
3305         key.offset = (u64)-1;
3306
3307         while (1) {
3308                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3309                 if (ret < 0)
3310                         goto out;
3311
3312                 /*
3313                  * if ret == 0 means we found what we were searching for, which
3314                  * is weird, but possible, so only screw with path if we didn't
3315                  * find the key and see if we have stuff that matches
3316                  */
3317                 if (ret > 0) {
3318                         ret = 0;
3319                         if (path->slots[0] == 0)
3320                                 break;
3321                         path->slots[0]--;
3322                 }
3323
3324                 /* pull out the item */
3325                 leaf = path->nodes[0];
3326                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3327
3328                 /* make sure the item matches what we want */
3329                 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3330                         break;
3331                 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3332                         break;
3333
3334                 /* release the path since we're done with it */
3335                 btrfs_release_path(path);
3336
3337                 /*
3338                  * this is where we are basically btrfs_lookup, without the
3339                  * crossing root thing.  we store the inode number in the
3340                  * offset of the orphan item.
3341                  */
3342
3343                 if (found_key.offset == last_objectid) {
3344                         btrfs_err(fs_info,
3345                                   "Error removing orphan entry, stopping orphan cleanup");
3346                         ret = -EINVAL;
3347                         goto out;
3348                 }
3349
3350                 last_objectid = found_key.offset;
3351
3352                 found_key.objectid = found_key.offset;
3353                 found_key.type = BTRFS_INODE_ITEM_KEY;
3354                 found_key.offset = 0;
3355                 inode = btrfs_iget(fs_info->sb, last_objectid, root);
3356                 ret = PTR_ERR_OR_ZERO(inode);
3357                 if (ret && ret != -ENOENT)
3358                         goto out;
3359
3360                 if (ret == -ENOENT && root == fs_info->tree_root) {
3361                         struct btrfs_root *dead_root;
3362                         int is_dead_root = 0;
3363
3364                         /*
3365                          * this is an orphan in the tree root. Currently these
3366                          * could come from 2 sources:
3367                          *  a) a snapshot deletion in progress
3368                          *  b) a free space cache inode
3369                          * We need to distinguish those two, as the snapshot
3370                          * orphan must not get deleted.
3371                          * find_dead_roots already ran before us, so if this
3372                          * is a snapshot deletion, we should find the root
3373                          * in the fs_roots radix tree.
3374                          */
3375
3376                         spin_lock(&fs_info->fs_roots_radix_lock);
3377                         dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
3378                                                          (unsigned long)found_key.objectid);
3379                         if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
3380                                 is_dead_root = 1;
3381                         spin_unlock(&fs_info->fs_roots_radix_lock);
3382
3383                         if (is_dead_root) {
3384                                 /* prevent this orphan from being found again */
3385                                 key.offset = found_key.objectid - 1;
3386                                 continue;
3387                         }
3388
3389                 }
3390
3391                 /*
3392                  * If we have an inode with links, there are a couple of
3393                  * possibilities. Old kernels (before v3.12) used to create an
3394                  * orphan item for truncate indicating that there were possibly
3395                  * extent items past i_size that needed to be deleted. In v3.12,
3396                  * truncate was changed to update i_size in sync with the extent
3397                  * items, but the (useless) orphan item was still created. Since
3398                  * v4.18, we don't create the orphan item for truncate at all.
3399                  *
3400                  * So, this item could mean that we need to do a truncate, but
3401                  * only if this filesystem was last used on a pre-v3.12 kernel
3402                  * and was not cleanly unmounted. The odds of that are quite
3403                  * slim, and it's a pain to do the truncate now, so just delete
3404                  * the orphan item.
3405                  *
3406                  * It's also possible that this orphan item was supposed to be
3407                  * deleted but wasn't. The inode number may have been reused,
3408                  * but either way, we can delete the orphan item.
3409                  */
3410                 if (ret == -ENOENT || inode->i_nlink) {
3411                         if (!ret)
3412                                 iput(inode);
3413                         trans = btrfs_start_transaction(root, 1);
3414                         if (IS_ERR(trans)) {
3415                                 ret = PTR_ERR(trans);
3416                                 goto out;
3417                         }
3418                         btrfs_debug(fs_info, "auto deleting %Lu",
3419                                     found_key.objectid);
3420                         ret = btrfs_del_orphan_item(trans, root,
3421                                                     found_key.objectid);
3422                         btrfs_end_transaction(trans);
3423                         if (ret)
3424                                 goto out;
3425                         continue;
3426                 }
3427
3428                 nr_unlink++;
3429
3430                 /* this will do delete_inode and everything for us */
3431                 iput(inode);
3432         }
3433         /* release the path since we're done with it */
3434         btrfs_release_path(path);
3435
3436         root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3437
3438         if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3439                 trans = btrfs_join_transaction(root);
3440                 if (!IS_ERR(trans))
3441                         btrfs_end_transaction(trans);
3442         }
3443
3444         if (nr_unlink)
3445                 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3446
3447 out:
3448         if (ret)
3449                 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3450         btrfs_free_path(path);
3451         return ret;
3452 }
3453
3454 /*
3455  * very simple check to peek ahead in the leaf looking for xattrs.  If we
3456  * don't find any xattrs, we know there can't be any acls.
3457  *
3458  * slot is the slot the inode is in, objectid is the objectid of the inode
3459  */
3460 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3461                                           int slot, u64 objectid,
3462                                           int *first_xattr_slot)
3463 {
3464         u32 nritems = btrfs_header_nritems(leaf);
3465         struct btrfs_key found_key;
3466         static u64 xattr_access = 0;
3467         static u64 xattr_default = 0;
3468         int scanned = 0;
3469
3470         if (!xattr_access) {
3471                 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3472                                         strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3473                 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3474                                         strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3475         }
3476
3477         slot++;
3478         *first_xattr_slot = -1;
3479         while (slot < nritems) {
3480                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3481
3482                 /* we found a different objectid, there must not be acls */
3483                 if (found_key.objectid != objectid)
3484                         return 0;
3485
3486                 /* we found an xattr, assume we've got an acl */
3487                 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3488                         if (*first_xattr_slot == -1)
3489                                 *first_xattr_slot = slot;
3490                         if (found_key.offset == xattr_access ||
3491                             found_key.offset == xattr_default)
3492                                 return 1;
3493                 }
3494
3495                 /*
3496                  * we found a key greater than an xattr key, there can't
3497                  * be any acls later on
3498                  */
3499                 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3500                         return 0;
3501
3502                 slot++;
3503                 scanned++;
3504
3505                 /*
3506                  * it goes inode, inode backrefs, xattrs, extents,
3507                  * so if there are a ton of hard links to an inode there can
3508                  * be a lot of backrefs.  Don't waste time searching too hard,
3509                  * this is just an optimization
3510                  */
3511                 if (scanned >= 8)
3512                         break;
3513         }
3514         /* we hit the end of the leaf before we found an xattr or
3515          * something larger than an xattr.  We have to assume the inode
3516          * has acls
3517          */
3518         if (*first_xattr_slot == -1)
3519                 *first_xattr_slot = slot;
3520         return 1;
3521 }
3522
3523 /*
3524  * read an inode from the btree into the in-memory inode
3525  */
3526 static int btrfs_read_locked_inode(struct inode *inode,
3527                                    struct btrfs_path *in_path)
3528 {
3529         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3530         struct btrfs_path *path = in_path;
3531         struct extent_buffer *leaf;
3532         struct btrfs_inode_item *inode_item;
3533         struct btrfs_root *root = BTRFS_I(inode)->root;
3534         struct btrfs_key location;
3535         unsigned long ptr;
3536         int maybe_acls;
3537         u32 rdev;
3538         int ret;
3539         bool filled = false;
3540         int first_xattr_slot;
3541
3542         ret = btrfs_fill_inode(inode, &rdev);
3543         if (!ret)
3544                 filled = true;
3545
3546         if (!path) {
3547                 path = btrfs_alloc_path();
3548                 if (!path)
3549                         return -ENOMEM;
3550         }
3551
3552         memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3553
3554         ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3555         if (ret) {
3556                 if (path != in_path)
3557                         btrfs_free_path(path);
3558                 return ret;
3559         }
3560
3561         leaf = path->nodes[0];
3562
3563         if (filled)
3564                 goto cache_index;
3565
3566         inode_item = btrfs_item_ptr(leaf, path->slots[0],
3567                                     struct btrfs_inode_item);
3568         inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3569         set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3570         i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3571         i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3572         btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3573         btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
3574                         round_up(i_size_read(inode), fs_info->sectorsize));
3575
3576         inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3577         inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3578
3579         inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3580         inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3581
3582         inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3583         inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3584
3585         BTRFS_I(inode)->i_otime.tv_sec =
3586                 btrfs_timespec_sec(leaf, &inode_item->otime);
3587         BTRFS_I(inode)->i_otime.tv_nsec =
3588                 btrfs_timespec_nsec(leaf, &inode_item->otime);
3589
3590         inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3591         BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3592         BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3593
3594         inode_set_iversion_queried(inode,
3595                                    btrfs_inode_sequence(leaf, inode_item));
3596         inode->i_generation = BTRFS_I(inode)->generation;
3597         inode->i_rdev = 0;
3598         rdev = btrfs_inode_rdev(leaf, inode_item);
3599
3600         BTRFS_I(inode)->index_cnt = (u64)-1;
3601         BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3602
3603 cache_index:
3604         /*
3605          * If we were modified in the current generation and evicted from memory
3606          * and then re-read we need to do a full sync since we don't have any
3607          * idea about which extents were modified before we were evicted from
3608          * cache.
3609          *
3610          * This is required for both inode re-read from disk and delayed inode
3611          * in delayed_nodes_tree.
3612          */
3613         if (BTRFS_I(inode)->last_trans == fs_info->generation)
3614                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3615                         &BTRFS_I(inode)->runtime_flags);
3616
3617         /*
3618          * We don't persist the id of the transaction where an unlink operation
3619          * against the inode was last made. So here we assume the inode might
3620          * have been evicted, and therefore the exact value of last_unlink_trans
3621          * lost, and set it to last_trans to avoid metadata inconsistencies
3622          * between the inode and its parent if the inode is fsync'ed and the log
3623          * replayed. For example, in the scenario:
3624          *
3625          * touch mydir/foo
3626          * ln mydir/foo mydir/bar
3627          * sync
3628          * unlink mydir/bar
3629          * echo 2 > /proc/sys/vm/drop_caches   # evicts inode
3630          * xfs_io -c fsync mydir/foo
3631          * <power failure>
3632          * mount fs, triggers fsync log replay
3633          *
3634          * We must make sure that when we fsync our inode foo we also log its
3635          * parent inode, otherwise after log replay the parent still has the
3636          * dentry with the "bar" name but our inode foo has a link count of 1
3637          * and doesn't have an inode ref with the name "bar" anymore.
3638          *
3639          * Setting last_unlink_trans to last_trans is a pessimistic approach,
3640          * but it guarantees correctness at the expense of occasional full
3641          * transaction commits on fsync if our inode is a directory, or if our
3642          * inode is not a directory, logging its parent unnecessarily.
3643          */
3644         BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3645
3646         /*
3647          * Same logic as for last_unlink_trans. We don't persist the generation
3648          * of the last transaction where this inode was used for a reflink
3649          * operation, so after eviction and reloading the inode we must be
3650          * pessimistic and assume the last transaction that modified the inode.
3651          */
3652         BTRFS_I(inode)->last_reflink_trans = BTRFS_I(inode)->last_trans;
3653
3654         path->slots[0]++;
3655         if (inode->i_nlink != 1 ||
3656             path->slots[0] >= btrfs_header_nritems(leaf))
3657                 goto cache_acl;
3658
3659         btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3660         if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3661                 goto cache_acl;
3662
3663         ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3664         if (location.type == BTRFS_INODE_REF_KEY) {
3665                 struct btrfs_inode_ref *ref;
3666
3667                 ref = (struct btrfs_inode_ref *)ptr;
3668                 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3669         } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3670                 struct btrfs_inode_extref *extref;
3671
3672                 extref = (struct btrfs_inode_extref *)ptr;
3673                 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3674                                                                      extref);
3675         }
3676 cache_acl:
3677         /*
3678          * try to precache a NULL acl entry for files that don't have
3679          * any xattrs or acls
3680          */
3681         maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3682                         btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3683         if (first_xattr_slot != -1) {
3684                 path->slots[0] = first_xattr_slot;
3685                 ret = btrfs_load_inode_props(inode, path);
3686                 if (ret)
3687                         btrfs_err(fs_info,
3688                                   "error loading props for ino %llu (root %llu): %d",
3689                                   btrfs_ino(BTRFS_I(inode)),
3690                                   root->root_key.objectid, ret);
3691         }
3692         if (path != in_path)
3693                 btrfs_free_path(path);
3694
3695         if (!maybe_acls)
3696                 cache_no_acl(inode);
3697
3698         switch (inode->i_mode & S_IFMT) {
3699         case S_IFREG:
3700                 inode->i_mapping->a_ops = &btrfs_aops;
3701                 inode->i_fop = &btrfs_file_operations;
3702                 inode->i_op = &btrfs_file_inode_operations;
3703                 break;
3704         case S_IFDIR:
3705                 inode->i_fop = &btrfs_dir_file_operations;
3706                 inode->i_op = &btrfs_dir_inode_operations;
3707                 break;
3708         case S_IFLNK:
3709                 inode->i_op = &btrfs_symlink_inode_operations;
3710                 inode_nohighmem(inode);
3711                 inode->i_mapping->a_ops = &btrfs_aops;
3712                 break;
3713         default:
3714                 inode->i_op = &btrfs_special_inode_operations;
3715                 init_special_inode(inode, inode->i_mode, rdev);
3716                 break;
3717         }
3718
3719         btrfs_sync_inode_flags_to_i_flags(inode);
3720         return 0;
3721 }
3722
3723 /*
3724  * given a leaf and an inode, copy the inode fields into the leaf
3725  */
3726 static void fill_inode_item(struct btrfs_trans_handle *trans,
3727                             struct extent_buffer *leaf,
3728                             struct btrfs_inode_item *item,
3729                             struct inode *inode)
3730 {
3731         struct btrfs_map_token token;
3732
3733         btrfs_init_map_token(&token, leaf);
3734
3735         btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
3736         btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
3737         btrfs_set_token_inode_size(&token, item, BTRFS_I(inode)->disk_i_size);
3738         btrfs_set_token_inode_mode(&token, item, inode->i_mode);
3739         btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
3740
3741         btrfs_set_token_timespec_sec(&token, &item->atime,
3742                                      inode->i_atime.tv_sec);
3743         btrfs_set_token_timespec_nsec(&token, &item->atime,
3744                                       inode->i_atime.tv_nsec);
3745
3746         btrfs_set_token_timespec_sec(&token, &item->mtime,
3747                                      inode->i_mtime.tv_sec);
3748         btrfs_set_token_timespec_nsec(&token, &item->mtime,
3749                                       inode->i_mtime.tv_nsec);
3750
3751         btrfs_set_token_timespec_sec(&token, &item->ctime,
3752                                      inode->i_ctime.tv_sec);
3753         btrfs_set_token_timespec_nsec(&token, &item->ctime,
3754                                       inode->i_ctime.tv_nsec);
3755
3756         btrfs_set_token_timespec_sec(&token, &item->otime,
3757                                      BTRFS_I(inode)->i_otime.tv_sec);
3758         btrfs_set_token_timespec_nsec(&token, &item->otime,
3759                                       BTRFS_I(inode)->i_otime.tv_nsec);
3760
3761         btrfs_set_token_inode_nbytes(&token, item, inode_get_bytes(inode));
3762         btrfs_set_token_inode_generation(&token, item,
3763                                          BTRFS_I(inode)->generation);
3764         btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
3765         btrfs_set_token_inode_transid(&token, item, trans->transid);
3766         btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
3767         btrfs_set_token_inode_flags(&token, item, BTRFS_I(inode)->flags);
3768         btrfs_set_token_inode_block_group(&token, item, 0);
3769 }
3770
3771 /*
3772  * copy everything in the in-memory inode into the btree.
3773  */
3774 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3775                                 struct btrfs_root *root,
3776                                 struct btrfs_inode *inode)
3777 {
3778         struct btrfs_inode_item *inode_item;
3779         struct btrfs_path *path;
3780         struct extent_buffer *leaf;
3781         int ret;
3782
3783         path = btrfs_alloc_path();
3784         if (!path)
3785                 return -ENOMEM;
3786
3787         ret = btrfs_lookup_inode(trans, root, path, &inode->location, 1);
3788         if (ret) {
3789                 if (ret > 0)
3790                         ret = -ENOENT;
3791                 goto failed;
3792         }
3793
3794         leaf = path->nodes[0];
3795         inode_item = btrfs_item_ptr(leaf, path->slots[0],
3796                                     struct btrfs_inode_item);
3797
3798         fill_inode_item(trans, leaf, inode_item, &inode->vfs_inode);
3799         btrfs_mark_buffer_dirty(leaf);
3800         btrfs_set_inode_last_trans(trans, inode);
3801         ret = 0;
3802 failed:
3803         btrfs_free_path(path);
3804         return ret;
3805 }
3806
3807 /*
3808  * copy everything in the in-memory inode into the btree.
3809  */
3810 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3811                                 struct btrfs_root *root,
3812                                 struct btrfs_inode *inode)
3813 {
3814         struct btrfs_fs_info *fs_info = root->fs_info;
3815         int ret;
3816
3817         /*
3818          * If the inode is a free space inode, we can deadlock during commit
3819          * if we put it into the delayed code.
3820          *
3821          * The data relocation inode should also be directly updated
3822          * without delay
3823          */
3824         if (!btrfs_is_free_space_inode(inode)
3825             && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3826             && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3827                 btrfs_update_root_times(trans, root);
3828
3829                 ret = btrfs_delayed_update_inode(trans, root, inode);
3830                 if (!ret)
3831                         btrfs_set_inode_last_trans(trans, inode);
3832                 return ret;
3833         }
3834
3835         return btrfs_update_inode_item(trans, root, inode);
3836 }
3837
3838 int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3839                                 struct btrfs_root *root, struct btrfs_inode *inode)
3840 {
3841         int ret;
3842
3843         ret = btrfs_update_inode(trans, root, inode);
3844         if (ret == -ENOSPC)
3845                 return btrfs_update_inode_item(trans, root, inode);
3846         return ret;
3847 }
3848
3849 /*
3850  * unlink helper that gets used here in inode.c and in the tree logging
3851  * recovery code.  It remove a link in a directory with a given name, and
3852  * also drops the back refs in the inode to the directory
3853  */
3854 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3855                                 struct btrfs_root *root,
3856                                 struct btrfs_inode *dir,
3857                                 struct btrfs_inode *inode,
3858                                 const char *name, int name_len)
3859 {
3860         struct btrfs_fs_info *fs_info = root->fs_info;
3861         struct btrfs_path *path;
3862         int ret = 0;
3863         struct btrfs_dir_item *di;
3864         u64 index;
3865         u64 ino = btrfs_ino(inode);
3866         u64 dir_ino = btrfs_ino(dir);
3867
3868         path = btrfs_alloc_path();
3869         if (!path) {
3870                 ret = -ENOMEM;
3871                 goto out;
3872         }
3873
3874         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3875                                     name, name_len, -1);
3876         if (IS_ERR_OR_NULL(di)) {
3877                 ret = di ? PTR_ERR(di) : -ENOENT;
3878                 goto err;
3879         }
3880         ret = btrfs_delete_one_dir_name(trans, root, path, di);
3881         if (ret)
3882                 goto err;
3883         btrfs_release_path(path);
3884
3885         /*
3886          * If we don't have dir index, we have to get it by looking up
3887          * the inode ref, since we get the inode ref, remove it directly,
3888          * it is unnecessary to do delayed deletion.
3889          *
3890          * But if we have dir index, needn't search inode ref to get it.
3891          * Since the inode ref is close to the inode item, it is better
3892          * that we delay to delete it, and just do this deletion when
3893          * we update the inode item.
3894          */
3895         if (inode->dir_index) {
3896                 ret = btrfs_delayed_delete_inode_ref(inode);
3897                 if (!ret) {
3898                         index = inode->dir_index;
3899                         goto skip_backref;
3900                 }
3901         }
3902
3903         ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3904                                   dir_ino, &index);
3905         if (ret) {
3906                 btrfs_info(fs_info,
3907                         "failed to delete reference to %.*s, inode %llu parent %llu",
3908                         name_len, name, ino, dir_ino);
3909                 btrfs_abort_transaction(trans, ret);
3910                 goto err;
3911         }
3912 skip_backref:
3913         ret = btrfs_delete_delayed_dir_index(trans, dir, index);
3914         if (ret) {
3915                 btrfs_abort_transaction(trans, ret);
3916                 goto err;
3917         }
3918
3919         ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
3920                         dir_ino);
3921         if (ret != 0 && ret != -ENOENT) {
3922                 btrfs_abort_transaction(trans, ret);
3923                 goto err;
3924         }
3925
3926         ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
3927                         index);
3928         if (ret == -ENOENT)
3929                 ret = 0;
3930         else if (ret)
3931                 btrfs_abort_transaction(trans, ret);
3932
3933         /*
3934          * If we have a pending delayed iput we could end up with the final iput
3935          * being run in btrfs-cleaner context.  If we have enough of these built
3936          * up we can end up burning a lot of time in btrfs-cleaner without any
3937          * way to throttle the unlinks.  Since we're currently holding a ref on
3938          * the inode we can run the delayed iput here without any issues as the
3939          * final iput won't be done until after we drop the ref we're currently
3940          * holding.
3941          */
3942         btrfs_run_delayed_iput(fs_info, inode);
3943 err:
3944         btrfs_free_path(path);
3945         if (ret)
3946                 goto out;
3947
3948         btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
3949         inode_inc_iversion(&inode->vfs_inode);
3950         inode_inc_iversion(&dir->vfs_inode);
3951         inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
3952                 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
3953         ret = btrfs_update_inode(trans, root, dir);
3954 out:
3955         return ret;
3956 }
3957
3958 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3959                        struct btrfs_root *root,
3960                        struct btrfs_inode *dir, struct btrfs_inode *inode,
3961                        const char *name, int name_len)
3962 {
3963         int ret;
3964         ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3965         if (!ret) {
3966                 drop_nlink(&inode->vfs_inode);
3967                 ret = btrfs_update_inode(trans, root, inode);
3968         }
3969         return ret;
3970 }
3971
3972 /*
3973  * helper to start transaction for unlink and rmdir.
3974  *
3975  * unlink and rmdir are special in btrfs, they do not always free space, so
3976  * if we cannot make our reservations the normal way try and see if there is
3977  * plenty of slack room in the global reserve to migrate, otherwise we cannot
3978  * allow the unlink to occur.
3979  */
3980 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3981 {
3982         struct btrfs_root *root = BTRFS_I(dir)->root;
3983
3984         /*
3985          * 1 for the possible orphan item
3986          * 1 for the dir item
3987          * 1 for the dir index
3988          * 1 for the inode ref
3989          * 1 for the inode
3990          */
3991         return btrfs_start_transaction_fallback_global_rsv(root, 5);
3992 }
3993
3994 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3995 {
3996         struct btrfs_root *root = BTRFS_I(dir)->root;
3997         struct btrfs_trans_handle *trans;
3998         struct inode *inode = d_inode(dentry);
3999         int ret;
4000
4001         trans = __unlink_start_trans(dir);
4002         if (IS_ERR(trans))
4003                 return PTR_ERR(trans);
4004
4005         btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4006                         0);
4007
4008         ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4009                         BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4010                         dentry->d_name.len);
4011         if (ret)
4012                 goto out;
4013
4014         if (inode->i_nlink == 0) {
4015                 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4016                 if (ret)
4017                         goto out;
4018         }
4019
4020 out:
4021         btrfs_end_transaction(trans);
4022         btrfs_btree_balance_dirty(root->fs_info);
4023         return ret;
4024 }
4025
4026 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4027                                struct inode *dir, struct dentry *dentry)
4028 {
4029         struct btrfs_root *root = BTRFS_I(dir)->root;
4030         struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
4031         struct btrfs_path *path;
4032         struct extent_buffer *leaf;
4033         struct btrfs_dir_item *di;
4034         struct btrfs_key key;
4035         const char *name = dentry->d_name.name;
4036         int name_len = dentry->d_name.len;
4037         u64 index;
4038         int ret;
4039         u64 objectid;
4040         u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4041
4042         if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
4043                 objectid = inode->root->root_key.objectid;
4044         } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4045                 objectid = inode->location.objectid;
4046         } else {
4047                 WARN_ON(1);
4048                 return -EINVAL;
4049         }
4050
4051         path = btrfs_alloc_path();
4052         if (!path)
4053                 return -ENOMEM;
4054
4055         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4056                                    name, name_len, -1);
4057         if (IS_ERR_OR_NULL(di)) {
4058                 ret = di ? PTR_ERR(di) : -ENOENT;
4059                 goto out;
4060         }
4061
4062         leaf = path->nodes[0];
4063         btrfs_dir_item_key_to_cpu(leaf, di, &key);
4064         WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4065         ret = btrfs_delete_one_dir_name(trans, root, path, di);
4066         if (ret) {
4067                 btrfs_abort_transaction(trans, ret);
4068                 goto out;
4069         }
4070         btrfs_release_path(path);
4071
4072         /*
4073          * This is a placeholder inode for a subvolume we didn't have a
4074          * reference to at the time of the snapshot creation.  In the meantime
4075          * we could have renamed the real subvol link into our snapshot, so
4076          * depending on btrfs_del_root_ref to return -ENOENT here is incorret.
4077          * Instead simply lookup the dir_index_item for this entry so we can
4078          * remove it.  Otherwise we know we have a ref to the root and we can
4079          * call btrfs_del_root_ref, and it _shouldn't_ fail.
4080          */
4081         if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4082                 di = btrfs_search_dir_index_item(root, path, dir_ino,
4083                                                  name, name_len);
4084                 if (IS_ERR_OR_NULL(di)) {
4085                         if (!di)
4086                                 ret = -ENOENT;
4087                         else
4088                                 ret = PTR_ERR(di);
4089                         btrfs_abort_transaction(trans, ret);
4090                         goto out;
4091                 }
4092
4093                 leaf = path->nodes[0];
4094                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4095                 index = key.offset;
4096                 btrfs_release_path(path);
4097         } else {
4098                 ret = btrfs_del_root_ref(trans, objectid,
4099                                          root->root_key.objectid, dir_ino,
4100                                          &index, name, name_len);
4101                 if (ret) {
4102                         btrfs_abort_transaction(trans, ret);
4103                         goto out;
4104                 }
4105         }
4106
4107         ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
4108         if (ret) {
4109                 btrfs_abort_transaction(trans, ret);
4110                 goto out;
4111         }
4112
4113         btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4114         inode_inc_iversion(dir);
4115         dir->i_mtime = dir->i_ctime = current_time(dir);
4116         ret = btrfs_update_inode_fallback(trans, root, BTRFS_I(dir));
4117         if (ret)
4118                 btrfs_abort_transaction(trans, ret);
4119 out:
4120         btrfs_free_path(path);
4121         return ret;
4122 }
4123
4124 /*
4125  * Helper to check if the subvolume references other subvolumes or if it's
4126  * default.
4127  */
4128 static noinline int may_destroy_subvol(struct btrfs_root *root)
4129 {
4130         struct btrfs_fs_info *fs_info = root->fs_info;
4131         struct btrfs_path *path;
4132         struct btrfs_dir_item *di;
4133         struct btrfs_key key;
4134         u64 dir_id;
4135         int ret;
4136
4137         path = btrfs_alloc_path();
4138         if (!path)
4139                 return -ENOMEM;
4140
4141         /* Make sure this root isn't set as the default subvol */
4142         dir_id = btrfs_super_root_dir(fs_info->super_copy);
4143         di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4144                                    dir_id, "default", 7, 0);
4145         if (di && !IS_ERR(di)) {
4146                 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4147                 if (key.objectid == root->root_key.objectid) {
4148                         ret = -EPERM;
4149                         btrfs_err(fs_info,
4150                                   "deleting default subvolume %llu is not allowed",
4151                                   key.objectid);
4152                         goto out;
4153                 }
4154                 btrfs_release_path(path);
4155         }
4156
4157         key.objectid = root->root_key.objectid;
4158         key.type = BTRFS_ROOT_REF_KEY;
4159         key.offset = (u64)-1;
4160
4161         ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4162         if (ret < 0)
4163                 goto out;
4164         BUG_ON(ret == 0);
4165
4166         ret = 0;
4167         if (path->slots[0] > 0) {
4168                 path->slots[0]--;
4169                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4170                 if (key.objectid == root->root_key.objectid &&
4171                     key.type == BTRFS_ROOT_REF_KEY)
4172                         ret = -ENOTEMPTY;
4173         }
4174 out:
4175         btrfs_free_path(path);
4176         return ret;
4177 }
4178
4179 /* Delete all dentries for inodes belonging to the root */
4180 static void btrfs_prune_dentries(struct btrfs_root *root)
4181 {
4182         struct btrfs_fs_info *fs_info = root->fs_info;
4183         struct rb_node *node;
4184         struct rb_node *prev;
4185         struct btrfs_inode *entry;
4186         struct inode *inode;
4187         u64 objectid = 0;
4188
4189         if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
4190                 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4191
4192         spin_lock(&root->inode_lock);
4193 again:
4194         node = root->inode_tree.rb_node;
4195         prev = NULL;
4196         while (node) {
4197                 prev = node;
4198                 entry = rb_entry(node, struct btrfs_inode, rb_node);
4199
4200                 if (objectid < btrfs_ino(entry))
4201                         node = node->rb_left;
4202                 else if (objectid > btrfs_ino(entry))
4203                         node = node->rb_right;
4204                 else
4205                         break;
4206         }
4207         if (!node) {
4208                 while (prev) {
4209                         entry = rb_entry(prev, struct btrfs_inode, rb_node);
4210                         if (objectid <= btrfs_ino(entry)) {
4211                                 node = prev;
4212                                 break;
4213                         }
4214                         prev = rb_next(prev);
4215                 }
4216         }
4217         while (node) {
4218                 entry = rb_entry(node, struct btrfs_inode, rb_node);
4219                 objectid = btrfs_ino(entry) + 1;
4220                 inode = igrab(&entry->vfs_inode);
4221                 if (inode) {
4222                         spin_unlock(&root->inode_lock);
4223                         if (atomic_read(&inode->i_count) > 1)
4224                                 d_prune_aliases(inode);
4225                         /*
4226                          * btrfs_drop_inode will have it removed from the inode
4227                          * cache when its usage count hits zero.
4228                          */
4229                         iput(inode);
4230                         cond_resched();
4231                         spin_lock(&root->inode_lock);
4232                         goto again;
4233                 }
4234
4235                 if (cond_resched_lock(&root->inode_lock))
4236                         goto again;
4237
4238                 node = rb_next(node);
4239         }
4240         spin_unlock(&root->inode_lock);
4241 }
4242
4243 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4244 {
4245         struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4246         struct btrfs_root *root = BTRFS_I(dir)->root;
4247         struct inode *inode = d_inode(dentry);
4248         struct btrfs_root *dest = BTRFS_I(inode)->root;
4249         struct btrfs_trans_handle *trans;
4250         struct btrfs_block_rsv block_rsv;
4251         u64 root_flags;
4252         int ret;
4253
4254         /*
4255          * Don't allow to delete a subvolume with send in progress. This is
4256          * inside the inode lock so the error handling that has to drop the bit
4257          * again is not run concurrently.
4258          */
4259         spin_lock(&dest->root_item_lock);
4260         if (dest->send_in_progress) {
4261                 spin_unlock(&dest->root_item_lock);
4262                 btrfs_warn(fs_info,
4263                            "attempt to delete subvolume %llu during send",
4264                            dest->root_key.objectid);
4265                 return -EPERM;
4266         }
4267         root_flags = btrfs_root_flags(&dest->root_item);
4268         btrfs_set_root_flags(&dest->root_item,
4269                              root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4270         spin_unlock(&dest->root_item_lock);
4271
4272         down_write(&fs_info->subvol_sem);
4273
4274         ret = may_destroy_subvol(dest);
4275         if (ret)
4276                 goto out_up_write;
4277
4278         btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4279         /*
4280          * One for dir inode,
4281          * two for dir entries,
4282          * two for root ref/backref.
4283          */
4284         ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4285         if (ret)
4286                 goto out_up_write;
4287
4288         trans = btrfs_start_transaction(root, 0);
4289         if (IS_ERR(trans)) {
4290                 ret = PTR_ERR(trans);
4291                 goto out_release;
4292         }
4293         trans->block_rsv = &block_rsv;
4294         trans->bytes_reserved = block_rsv.size;
4295
4296         btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4297
4298         ret = btrfs_unlink_subvol(trans, dir, dentry);
4299         if (ret) {
4300                 btrfs_abort_transaction(trans, ret);
4301                 goto out_end_trans;
4302         }
4303
4304         btrfs_record_root_in_trans(trans, dest);
4305
4306         memset(&dest->root_item.drop_progress, 0,
4307                 sizeof(dest->root_item.drop_progress));
4308         btrfs_set_root_drop_level(&dest->root_item, 0);
4309         btrfs_set_root_refs(&dest->root_item, 0);
4310
4311         if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4312                 ret = btrfs_insert_orphan_item(trans,
4313                                         fs_info->tree_root,
4314                                         dest->root_key.objectid);
4315                 if (ret) {
4316                         btrfs_abort_transaction(trans, ret);
4317                         goto out_end_trans;
4318                 }
4319         }
4320
4321         ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4322                                   BTRFS_UUID_KEY_SUBVOL,
4323                                   dest->root_key.objectid);
4324         if (ret && ret != -ENOENT) {
4325                 btrfs_abort_transaction(trans, ret);
4326                 goto out_end_trans;
4327         }
4328         if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4329                 ret = btrfs_uuid_tree_remove(trans,
4330                                           dest->root_item.received_uuid,
4331                                           BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4332                                           dest->root_key.objectid);
4333                 if (ret && ret != -ENOENT) {
4334                         btrfs_abort_transaction(trans, ret);
4335                         goto out_end_trans;
4336                 }
4337         }
4338
4339         free_anon_bdev(dest->anon_dev);
4340         dest->anon_dev = 0;
4341 out_end_trans:
4342         trans->block_rsv = NULL;
4343         trans->bytes_reserved = 0;
4344         ret = btrfs_end_transaction(trans);
4345         inode->i_flags |= S_DEAD;
4346 out_release:
4347         btrfs_subvolume_release_metadata(root, &block_rsv);
4348 out_up_write:
4349         up_write(&fs_info->subvol_sem);
4350         if (ret) {
4351                 spin_lock(&dest->root_item_lock);
4352                 root_flags = btrfs_root_flags(&dest->root_item);
4353                 btrfs_set_root_flags(&dest->root_item,
4354                                 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4355                 spin_unlock(&dest->root_item_lock);
4356         } else {
4357                 d_invalidate(dentry);
4358                 btrfs_prune_dentries(dest);
4359                 ASSERT(dest->send_in_progress == 0);
4360         }
4361
4362         return ret;
4363 }
4364
4365 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4366 {
4367         struct inode *inode = d_inode(dentry);
4368         int err = 0;
4369         struct btrfs_root *root = BTRFS_I(dir)->root;
4370         struct btrfs_trans_handle *trans;
4371         u64 last_unlink_trans;
4372
4373         if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4374                 return -ENOTEMPTY;
4375         if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4376                 return btrfs_delete_subvolume(dir, dentry);
4377
4378         trans = __unlink_start_trans(dir);
4379         if (IS_ERR(trans))
4380                 return PTR_ERR(trans);
4381
4382         if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4383                 err = btrfs_unlink_subvol(trans, dir, dentry);
4384                 goto out;
4385         }
4386
4387         err = btrfs_orphan_add(trans, BTRFS_I(inode));
4388         if (err)
4389                 goto out;
4390
4391         last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4392
4393         /* now the directory is empty */
4394         err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4395                         BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4396                         dentry->d_name.len);
4397         if (!err) {
4398                 btrfs_i_size_write(BTRFS_I(inode), 0);
4399                 /*
4400                  * Propagate the last_unlink_trans value of the deleted dir to
4401                  * its parent directory. This is to prevent an unrecoverable
4402                  * log tree in the case we do something like this:
4403                  * 1) create dir foo
4404                  * 2) create snapshot under dir foo
4405                  * 3) delete the snapshot
4406                  * 4) rmdir foo
4407                  * 5) mkdir foo
4408                  * 6) fsync foo or some file inside foo
4409                  */
4410                 if (last_unlink_trans >= trans->transid)
4411                         BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4412         }
4413 out:
4414         btrfs_end_transaction(trans);
4415         btrfs_btree_balance_dirty(root->fs_info);
4416
4417         return err;
4418 }
4419
4420 /*
4421  * Return this if we need to call truncate_block for the last bit of the
4422  * truncate.
4423  */
4424 #define NEED_TRUNCATE_BLOCK 1
4425
4426 /*
4427  * this can truncate away extent items, csum items and directory items.
4428  * It starts at a high offset and removes keys until it can't find
4429  * any higher than new_size
4430  *
4431  * csum items that cross the new i_size are truncated to the new size
4432  * as well.
4433  *
4434  * min_type is the minimum key type to truncate down to.  If set to 0, this
4435  * will kill all the items on this inode, including the INODE_ITEM_KEY.
4436  */
4437 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4438                                struct btrfs_root *root,
4439                                struct btrfs_inode *inode,
4440                                u64 new_size, u32 min_type)
4441 {
4442         struct btrfs_fs_info *fs_info = root->fs_info;
4443         struct btrfs_path *path;
4444         struct extent_buffer *leaf;
4445         struct btrfs_file_extent_item *fi;
4446         struct btrfs_key key;
4447         struct btrfs_key found_key;
4448         u64 extent_start = 0;
4449         u64 extent_num_bytes = 0;
4450         u64 extent_offset = 0;
4451         u64 item_end = 0;
4452         u64 last_size = new_size;
4453         u32 found_type = (u8)-1;
4454         int found_extent;
4455         int del_item;
4456         int pending_del_nr = 0;
4457         int pending_del_slot = 0;
4458         int extent_type = -1;
4459         int ret;
4460         u64 ino = btrfs_ino(inode);
4461         u64 bytes_deleted = 0;
4462         bool be_nice = false;
4463         bool should_throttle = false;
4464         const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
4465         struct extent_state *cached_state = NULL;
4466
4467         BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4468
4469         /*
4470          * For non-free space inodes and non-shareable roots, we want to back
4471          * off from time to time.  This means all inodes in subvolume roots,
4472          * reloc roots, and data reloc roots.
4473          */
4474         if (!btrfs_is_free_space_inode(inode) &&
4475             test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4476                 be_nice = true;
4477
4478         path = btrfs_alloc_path();
4479         if (!path)
4480                 return -ENOMEM;
4481         path->reada = READA_BACK;
4482
4483         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4484                 lock_extent_bits(&inode->io_tree, lock_start, (u64)-1,
4485                                  &cached_state);
4486
4487                 /*
4488                  * We want to drop from the next block forward in case this
4489                  * new size is not block aligned since we will be keeping the
4490                  * last block of the extent just the way it is.
4491                  */
4492                 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4493                                         fs_info->sectorsize),
4494                                         (u64)-1, 0);
4495         }
4496
4497         /*
4498          * This function is also used to drop the items in the log tree before
4499          * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4500          * it is used to drop the logged items. So we shouldn't kill the delayed
4501          * items.
4502          */
4503         if (min_type == 0 && root == inode->root)
4504                 btrfs_kill_delayed_inode_items(inode);
4505
4506         key.objectid = ino;
4507         key.offset = (u64)-1;
4508         key.type = (u8)-1;
4509
4510 search_again:
4511         /*
4512          * with a 16K leaf size and 128MB extents, you can actually queue
4513          * up a huge file in a single leaf.  Most of the time that
4514          * bytes_deleted is > 0, it will be huge by the time we get here
4515          */
4516         if (be_nice && bytes_deleted > SZ_32M &&
4517             btrfs_should_end_transaction(trans)) {
4518                 ret = -EAGAIN;
4519                 goto out;
4520         }
4521
4522         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4523         if (ret < 0)
4524                 goto out;
4525
4526         if (ret > 0) {
4527                 ret = 0;
4528                 /* there are no items in the tree for us to truncate, we're
4529                  * done
4530                  */
4531                 if (path->slots[0] == 0)
4532                         goto out;
4533                 path->slots[0]--;
4534         }
4535
4536         while (1) {
4537                 u64 clear_start = 0, clear_len = 0;
4538
4539                 fi = NULL;
4540                 leaf = path->nodes[0];
4541                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4542                 found_type = found_key.type;
4543
4544                 if (found_key.objectid != ino)
4545                         break;
4546
4547                 if (found_type < min_type)
4548                         break;
4549
4550                 item_end = found_key.offset;
4551                 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4552                         fi = btrfs_item_ptr(leaf, path->slots[0],
4553                                             struct btrfs_file_extent_item);
4554                         extent_type = btrfs_file_extent_type(leaf, fi);
4555                         if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4556                                 item_end +=
4557                                     btrfs_file_extent_num_bytes(leaf, fi);
4558
4559                                 trace_btrfs_truncate_show_fi_regular(
4560                                         inode, leaf, fi, found_key.offset);
4561                         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4562                                 item_end += btrfs_file_extent_ram_bytes(leaf,
4563                                                                         fi);
4564
4565                                 trace_btrfs_truncate_show_fi_inline(
4566                                         inode, leaf, fi, path->slots[0],
4567                                         found_key.offset);
4568                         }
4569                         item_end--;
4570                 }
4571                 if (found_type > min_type) {
4572                         del_item = 1;
4573                 } else {
4574                         if (item_end < new_size)
4575                                 break;
4576                         if (found_key.offset >= new_size)
4577                                 del_item = 1;
4578                         else
4579                                 del_item = 0;
4580                 }
4581                 found_extent = 0;
4582                 /* FIXME, shrink the extent if the ref count is only 1 */
4583                 if (found_type != BTRFS_EXTENT_DATA_KEY)
4584                         goto delete;
4585
4586                 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4587                         u64 num_dec;
4588
4589                         clear_start = found_key.offset;
4590                         extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4591                         if (!del_item) {
4592                                 u64 orig_num_bytes =
4593                                         btrfs_file_extent_num_bytes(leaf, fi);
4594                                 extent_num_bytes = ALIGN(new_size -
4595                                                 found_key.offset,
4596                                                 fs_info->sectorsize);
4597                                 clear_start = ALIGN(new_size, fs_info->sectorsize);
4598                                 btrfs_set_file_extent_num_bytes(leaf, fi,
4599                                                          extent_num_bytes);
4600                                 num_dec = (orig_num_bytes -
4601                                            extent_num_bytes);
4602                                 if (test_bit(BTRFS_ROOT_SHAREABLE,
4603                                              &root->state) &&
4604                                     extent_start != 0)
4605                                         inode_sub_bytes(&inode->vfs_inode,
4606                                                         num_dec);
4607                                 btrfs_mark_buffer_dirty(leaf);
4608                         } else {
4609                                 extent_num_bytes =
4610                                         btrfs_file_extent_disk_num_bytes(leaf,
4611                                                                          fi);
4612                                 extent_offset = found_key.offset -
4613                                         btrfs_file_extent_offset(leaf, fi);
4614
4615                                 /* FIXME blocksize != 4096 */
4616                                 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4617                                 if (extent_start != 0) {
4618                                         found_extent = 1;
4619                                         if (test_bit(BTRFS_ROOT_SHAREABLE,
4620                                                      &root->state))
4621                                                 inode_sub_bytes(&inode->vfs_inode,
4622                                                                 num_dec);
4623                                 }
4624                         }
4625                         clear_len = num_dec;
4626                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4627                         /*
4628                          * we can't truncate inline items that have had
4629                          * special encodings
4630                          */
4631                         if (!del_item &&
4632                             btrfs_file_extent_encryption(leaf, fi) == 0 &&
4633                             btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4634                             btrfs_file_extent_compression(leaf, fi) == 0) {
4635                                 u32 size = (u32)(new_size - found_key.offset);
4636
4637                                 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4638                                 size = btrfs_file_extent_calc_inline_size(size);
4639                                 btrfs_truncate_item(path, size, 1);
4640                         } else if (!del_item) {
4641                                 /*
4642                                  * We have to bail so the last_size is set to
4643                                  * just before this extent.
4644                                  */
4645                                 ret = NEED_TRUNCATE_BLOCK;
4646                                 break;
4647                         } else {
4648                                 /*
4649                                  * Inline extents are special, we just treat
4650                                  * them as a full sector worth in the file
4651                                  * extent tree just for simplicity sake.
4652                                  */
4653                                 clear_len = fs_info->sectorsize;
4654                         }
4655
4656                         if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4657                                 inode_sub_bytes(&inode->vfs_inode,
4658                                                 item_end + 1 - new_size);
4659                 }
4660 delete:
4661                 /*
4662                  * We use btrfs_truncate_inode_items() to clean up log trees for
4663                  * multiple fsyncs, and in this case we don't want to clear the
4664                  * file extent range because it's just the log.
4665                  */
4666                 if (root == inode->root) {
4667                         ret = btrfs_inode_clear_file_extent_range(inode,
4668                                                   clear_start, clear_len);
4669                         if (ret) {
4670                                 btrfs_abort_transaction(trans, ret);
4671                                 break;
4672                         }
4673                 }
4674
4675                 if (del_item)
4676                         last_size = found_key.offset;
4677                 else
4678                         last_size = new_size;
4679                 if (del_item) {
4680                         if (!pending_del_nr) {
4681                                 /* no pending yet, add ourselves */
4682                                 pending_del_slot = path->slots[0];
4683                                 pending_del_nr = 1;
4684                         } else if (pending_del_nr &&
4685                                    path->slots[0] + 1 == pending_del_slot) {
4686                                 /* hop on the pending chunk */
4687                                 pending_del_nr++;
4688                                 pending_del_slot = path->slots[0];
4689                         } else {
4690                                 BUG();
4691                         }
4692                 } else {
4693                         break;
4694                 }
4695                 should_throttle = false;
4696
4697                 if (found_extent &&
4698                     root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4699                         struct btrfs_ref ref = { 0 };
4700
4701                         bytes_deleted += extent_num_bytes;
4702
4703                         btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4704                                         extent_start, extent_num_bytes, 0);
4705                         ref.real_root = root->root_key.objectid;
4706                         btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4707                                         ino, extent_offset);
4708                         ret = btrfs_free_extent(trans, &ref);
4709                         if (ret) {
4710                                 btrfs_abort_transaction(trans, ret);
4711                                 break;
4712                         }
4713                         if (be_nice) {
4714                                 if (btrfs_should_throttle_delayed_refs(trans))
4715                                         should_throttle = true;
4716                         }
4717                 }
4718
4719                 if (found_type == BTRFS_INODE_ITEM_KEY)
4720                         break;
4721
4722                 if (path->slots[0] == 0 ||
4723                     path->slots[0] != pending_del_slot ||
4724                     should_throttle) {
4725                         if (pending_del_nr) {
4726                                 ret = btrfs_del_items(trans, root, path,
4727                                                 pending_del_slot,
4728                                                 pending_del_nr);
4729                                 if (ret) {
4730                                         btrfs_abort_transaction(trans, ret);
4731                                         break;
4732                                 }
4733                                 pending_del_nr = 0;
4734                         }
4735                         btrfs_release_path(path);
4736
4737                         /*
4738                          * We can generate a lot of delayed refs, so we need to
4739                          * throttle every once and a while and make sure we're
4740                          * adding enough space to keep up with the work we are
4741                          * generating.  Since we hold a transaction here we
4742                          * can't flush, and we don't want to FLUSH_LIMIT because
4743                          * we could have generated too many delayed refs to
4744                          * actually allocate, so just bail if we're short and
4745                          * let the normal reservation dance happen higher up.
4746                          */
4747                         if (should_throttle) {
4748                                 ret = btrfs_delayed_refs_rsv_refill(fs_info,
4749                                                         BTRFS_RESERVE_NO_FLUSH);
4750                                 if (ret) {
4751                                         ret = -EAGAIN;
4752                                         break;
4753                                 }
4754                         }
4755                         goto search_again;
4756                 } else {
4757                         path->slots[0]--;
4758                 }
4759         }
4760 out:
4761         if (ret >= 0 && pending_del_nr) {
4762                 int err;
4763
4764                 err = btrfs_del_items(trans, root, path, pending_del_slot,
4765                                       pending_del_nr);
4766                 if (err) {
4767                         btrfs_abort_transaction(trans, err);
4768                         ret = err;
4769                 }
4770         }
4771         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4772                 ASSERT(last_size >= new_size);
4773                 if (!ret && last_size > new_size)
4774                         last_size = new_size;
4775                 btrfs_inode_safe_disk_i_size_write(inode, last_size);
4776                 unlock_extent_cached(&inode->io_tree, lock_start, (u64)-1,
4777                                      &cached_state);
4778         }
4779
4780         btrfs_free_path(path);
4781         return ret;
4782 }
4783
4784 /*
4785  * btrfs_truncate_block - read, zero a chunk and write a block
4786  * @inode - inode that we're zeroing
4787  * @from - the offset to start zeroing
4788  * @len - the length to zero, 0 to zero the entire range respective to the
4789  *      offset
4790  * @front - zero up to the offset instead of from the offset on
4791  *
4792  * This will find the block for the "from" offset and cow the block and zero the
4793  * part we want to zero.  This is used with truncate and hole punching.
4794  */
4795 int btrfs_truncate_block(struct btrfs_inode *inode, loff_t from, loff_t len,
4796                          int front)
4797 {
4798         struct btrfs_fs_info *fs_info = inode->root->fs_info;
4799         struct address_space *mapping = inode->vfs_inode.i_mapping;
4800         struct extent_io_tree *io_tree = &inode->io_tree;
4801         struct btrfs_ordered_extent *ordered;
4802         struct extent_state *cached_state = NULL;
4803         struct extent_changeset *data_reserved = NULL;
4804         char *kaddr;
4805         bool only_release_metadata = false;
4806         u32 blocksize = fs_info->sectorsize;
4807         pgoff_t index = from >> PAGE_SHIFT;
4808         unsigned offset = from & (blocksize - 1);
4809         struct page *page;
4810         gfp_t mask = btrfs_alloc_write_mask(mapping);
4811         size_t write_bytes = blocksize;
4812         int ret = 0;
4813         u64 block_start;
4814         u64 block_end;
4815
4816         if (IS_ALIGNED(offset, blocksize) &&
4817             (!len || IS_ALIGNED(len, blocksize)))
4818                 goto out;
4819
4820         block_start = round_down(from, blocksize);
4821         block_end = block_start + blocksize - 1;
4822
4823         ret = btrfs_check_data_free_space(inode, &data_reserved, block_start,
4824                                           blocksize);
4825         if (ret < 0) {
4826                 if (btrfs_check_nocow_lock(inode, block_start, &write_bytes) > 0) {
4827                         /* For nocow case, no need to reserve data space */
4828                         only_release_metadata = true;
4829                 } else {
4830                         goto out;
4831                 }
4832         }
4833         ret = btrfs_delalloc_reserve_metadata(inode, blocksize);
4834         if (ret < 0) {
4835                 if (!only_release_metadata)
4836                         btrfs_free_reserved_data_space(inode, data_reserved,
4837                                                        block_start, blocksize);
4838                 goto out;
4839         }
4840 again:
4841         page = find_or_create_page(mapping, index, mask);
4842         if (!page) {
4843                 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4844                                              blocksize, true);
4845                 btrfs_delalloc_release_extents(inode, blocksize);
4846                 ret = -ENOMEM;
4847                 goto out;
4848         }
4849         ret = set_page_extent_mapped(page);
4850         if (ret < 0)
4851                 goto out_unlock;
4852
4853         if (!PageUptodate(page)) {
4854                 ret = btrfs_readpage(NULL, page);
4855                 lock_page(page);
4856                 if (page->mapping != mapping) {
4857                         unlock_page(page);
4858                         put_page(page);
4859                         goto again;
4860                 }
4861                 if (!PageUptodate(page)) {
4862                         ret = -EIO;
4863                         goto out_unlock;
4864                 }
4865         }
4866         wait_on_page_writeback(page);
4867
4868         lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4869
4870         ordered = btrfs_lookup_ordered_extent(inode, block_start);
4871         if (ordered) {
4872                 unlock_extent_cached(io_tree, block_start, block_end,
4873                                      &cached_state);
4874                 unlock_page(page);
4875                 put_page(page);
4876                 btrfs_start_ordered_extent(ordered, 1);
4877                 btrfs_put_ordered_extent(ordered);
4878                 goto again;
4879         }
4880
4881         clear_extent_bit(&inode->io_tree, block_start, block_end,
4882                          EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4883                          0, 0, &cached_state);
4884
4885         ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4886                                         &cached_state);
4887         if (ret) {
4888                 unlock_extent_cached(io_tree, block_start, block_end,
4889                                      &cached_state);
4890                 goto out_unlock;
4891         }
4892
4893         if (offset != blocksize) {
4894                 if (!len)
4895                         len = blocksize - offset;
4896                 kaddr = kmap(page);
4897                 if (front)
4898                         memset(kaddr + (block_start - page_offset(page)),
4899                                 0, offset);
4900                 else
4901                         memset(kaddr + (block_start - page_offset(page)) +  offset,
4902                                 0, len);
4903                 flush_dcache_page(page);
4904                 kunmap(page);
4905         }
4906         ClearPageChecked(page);
4907         set_page_dirty(page);
4908         unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4909
4910         if (only_release_metadata)
4911                 set_extent_bit(&inode->io_tree, block_start, block_end,
4912                                EXTENT_NORESERVE, 0, NULL, NULL, GFP_NOFS, NULL);
4913
4914 out_unlock:
4915         if (ret) {
4916                 if (only_release_metadata)
4917                         btrfs_delalloc_release_metadata(inode, blocksize, true);
4918                 else
4919                         btrfs_delalloc_release_space(inode, data_reserved,
4920                                         block_start, blocksize, true);
4921         }
4922         btrfs_delalloc_release_extents(inode, blocksize);
4923         unlock_page(page);
4924         put_page(page);
4925 out:
4926         if (only_release_metadata)
4927                 btrfs_check_nocow_unlock(inode);
4928         extent_changeset_free(data_reserved);
4929         return ret;
4930 }
4931
4932 static int maybe_insert_hole(struct btrfs_root *root, struct btrfs_inode *inode,
4933                              u64 offset, u64 len)
4934 {
4935         struct btrfs_fs_info *fs_info = root->fs_info;
4936         struct btrfs_trans_handle *trans;
4937         struct btrfs_drop_extents_args drop_args = { 0 };
4938         int ret;
4939
4940         /*
4941          * Still need to make sure the inode looks like it's been updated so
4942          * that any holes get logged if we fsync.
4943          */
4944         if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4945                 inode->last_trans = fs_info->generation;
4946                 inode->last_sub_trans = root->log_transid;
4947                 inode->last_log_commit = root->last_log_commit;
4948                 return 0;
4949         }
4950
4951         /*
4952          * 1 - for the one we're dropping
4953          * 1 - for the one we're adding
4954          * 1 - for updating the inode.
4955          */
4956         trans = btrfs_start_transaction(root, 3);
4957         if (IS_ERR(trans))
4958                 return PTR_ERR(trans);
4959
4960         drop_args.start = offset;
4961         drop_args.end = offset + len;
4962         drop_args.drop_cache = true;
4963
4964         ret = btrfs_drop_extents(trans, root, inode, &drop_args);
4965         if (ret) {
4966                 btrfs_abort_transaction(trans, ret);
4967                 btrfs_end_transaction(trans);
4968                 return ret;
4969         }
4970
4971         ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode),
4972                         offset, 0, 0, len, 0, len, 0, 0, 0);
4973         if (ret) {
4974                 btrfs_abort_transaction(trans, ret);
4975         } else {
4976                 btrfs_update_inode_bytes(inode, 0, drop_args.bytes_found);
4977                 btrfs_update_inode(trans, root, inode);
4978         }
4979         btrfs_end_transaction(trans);
4980         return ret;
4981 }
4982
4983 /*
4984  * This function puts in dummy file extents for the area we're creating a hole
4985  * for.  So if we are truncating this file to a larger size we need to insert
4986  * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4987  * the range between oldsize and size
4988  */
4989 int btrfs_cont_expand(struct btrfs_inode *inode, loff_t oldsize, loff_t size)
4990 {
4991         struct btrfs_root *root = inode->root;
4992         struct btrfs_fs_info *fs_info = root->fs_info;
4993         struct extent_io_tree *io_tree = &inode->io_tree;
4994         struct extent_map *em = NULL;
4995         struct extent_state *cached_state = NULL;
4996         struct extent_map_tree *em_tree = &inode->extent_tree;
4997         u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4998         u64 block_end = ALIGN(size, fs_info->sectorsize);
4999         u64 last_byte;
5000         u64 cur_offset;
5001         u64 hole_size;
5002         int err = 0;
5003
5004         /*
5005          * If our size started in the middle of a block we need to zero out the
5006          * rest of the block before we expand the i_size, otherwise we could
5007          * expose stale data.
5008          */
5009         err = btrfs_truncate_block(inode, oldsize, 0, 0);
5010         if (err)
5011                 return err;
5012
5013         if (size <= hole_start)
5014                 return 0;
5015
5016         btrfs_lock_and_flush_ordered_range(inode, hole_start, block_end - 1,
5017                                            &cached_state);
5018         cur_offset = hole_start;
5019         while (1) {
5020                 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
5021                                       block_end - cur_offset);
5022                 if (IS_ERR(em)) {
5023                         err = PTR_ERR(em);
5024                         em = NULL;
5025                         break;
5026                 }
5027                 last_byte = min(extent_map_end(em), block_end);
5028                 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5029                 hole_size = last_byte - cur_offset;
5030
5031                 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5032                         struct extent_map *hole_em;
5033
5034                         err = maybe_insert_hole(root, inode, cur_offset,
5035                                                 hole_size);
5036                         if (err)
5037                                 break;
5038
5039                         err = btrfs_inode_set_file_extent_range(inode,
5040                                                         cur_offset, hole_size);
5041                         if (err)
5042                                 break;
5043
5044                         btrfs_drop_extent_cache(inode, cur_offset,
5045                                                 cur_offset + hole_size - 1, 0);
5046                         hole_em = alloc_extent_map();
5047                         if (!hole_em) {
5048                                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5049                                         &inode->runtime_flags);
5050                                 goto next;
5051                         }
5052                         hole_em->start = cur_offset;
5053                         hole_em->len = hole_size;
5054                         hole_em->orig_start = cur_offset;
5055
5056                         hole_em->block_start = EXTENT_MAP_HOLE;
5057                         hole_em->block_len = 0;
5058                         hole_em->orig_block_len = 0;
5059                         hole_em->ram_bytes = hole_size;
5060                         hole_em->compress_type = BTRFS_COMPRESS_NONE;
5061                         hole_em->generation = fs_info->generation;
5062
5063                         while (1) {
5064                                 write_lock(&em_tree->lock);
5065                                 err = add_extent_mapping(em_tree, hole_em, 1);
5066                                 write_unlock(&em_tree->lock);
5067                                 if (err != -EEXIST)
5068                                         break;
5069                                 btrfs_drop_extent_cache(inode, cur_offset,
5070                                                         cur_offset +
5071                                                         hole_size - 1, 0);
5072                         }
5073                         free_extent_map(hole_em);
5074                 } else {
5075                         err = btrfs_inode_set_file_extent_range(inode,
5076                                                         cur_offset, hole_size);
5077                         if (err)
5078                                 break;
5079                 }
5080 next:
5081                 free_extent_map(em);
5082                 em = NULL;
5083                 cur_offset = last_byte;
5084                 if (cur_offset >= block_end)
5085                         break;
5086         }
5087         free_extent_map(em);
5088         unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5089         return err;
5090 }
5091
5092 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5093 {
5094         struct btrfs_root *root = BTRFS_I(inode)->root;
5095         struct btrfs_trans_handle *trans;
5096         loff_t oldsize = i_size_read(inode);
5097         loff_t newsize = attr->ia_size;
5098         int mask = attr->ia_valid;
5099         int ret;
5100
5101         /*
5102          * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5103          * special case where we need to update the times despite not having
5104          * these flags set.  For all other operations the VFS set these flags
5105          * explicitly if it wants a timestamp update.
5106          */
5107         if (newsize != oldsize) {
5108                 inode_inc_iversion(inode);
5109                 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5110                         inode->i_ctime = inode->i_mtime =
5111                                 current_time(inode);
5112         }
5113
5114         if (newsize > oldsize) {
5115                 /*
5116                  * Don't do an expanding truncate while snapshotting is ongoing.
5117                  * This is to ensure the snapshot captures a fully consistent
5118                  * state of this file - if the snapshot captures this expanding
5119                  * truncation, it must capture all writes that happened before
5120                  * this truncation.
5121                  */
5122                 btrfs_drew_write_lock(&root->snapshot_lock);
5123                 ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, newsize);
5124                 if (ret) {
5125                         btrfs_drew_write_unlock(&root->snapshot_lock);
5126                         return ret;
5127                 }
5128
5129                 trans = btrfs_start_transaction(root, 1);
5130                 if (IS_ERR(trans)) {
5131                         btrfs_drew_write_unlock(&root->snapshot_lock);
5132                         return PTR_ERR(trans);
5133                 }
5134
5135                 i_size_write(inode, newsize);
5136                 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
5137                 pagecache_isize_extended(inode, oldsize, newsize);
5138                 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
5139                 btrfs_drew_write_unlock(&root->snapshot_lock);
5140                 btrfs_end_transaction(trans);
5141         } else {
5142
5143                 /*
5144                  * We're truncating a file that used to have good data down to
5145                  * zero. Make sure any new writes to the file get on disk
5146                  * on close.
5147                  */
5148                 if (newsize == 0)
5149                         set_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
5150                                 &BTRFS_I(inode)->runtime_flags);
5151
5152                 truncate_setsize(inode, newsize);
5153
5154                 inode_dio_wait(inode);
5155
5156                 ret = btrfs_truncate(inode, newsize == oldsize);
5157                 if (ret && inode->i_nlink) {
5158                         int err;
5159
5160                         /*
5161                          * Truncate failed, so fix up the in-memory size. We
5162                          * adjusted disk_i_size down as we removed extents, so
5163                          * wait for disk_i_size to be stable and then update the
5164                          * in-memory size to match.
5165                          */
5166                         err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5167                         if (err)
5168                                 return err;
5169                         i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5170                 }
5171         }
5172
5173         return ret;
5174 }
5175
5176 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5177 {
5178         struct inode *inode = d_inode(dentry);
5179         struct btrfs_root *root = BTRFS_I(inode)->root;
5180         int err;
5181
5182         if (btrfs_root_readonly(root))
5183                 return -EROFS;
5184
5185         err = setattr_prepare(dentry, attr);
5186         if (err)
5187                 return err;
5188
5189         if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5190                 err = btrfs_setsize(inode, attr);
5191                 if (err)
5192                         return err;
5193         }
5194
5195         if (attr->ia_valid) {
5196                 setattr_copy(inode, attr);
5197                 inode_inc_iversion(inode);
5198                 err = btrfs_dirty_inode(inode);
5199
5200                 if (!err && attr->ia_valid & ATTR_MODE)
5201                         err = posix_acl_chmod(inode, inode->i_mode);
5202         }
5203
5204         return err;
5205 }
5206
5207 /*
5208  * While truncating the inode pages during eviction, we get the VFS calling
5209  * btrfs_invalidatepage() against each page of the inode. This is slow because
5210  * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5211  * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5212  * extent_state structures over and over, wasting lots of time.
5213  *
5214  * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5215  * those expensive operations on a per page basis and do only the ordered io
5216  * finishing, while we release here the extent_map and extent_state structures,
5217  * without the excessive merging and splitting.
5218  */
5219 static void evict_inode_truncate_pages(struct inode *inode)
5220 {
5221         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5222         struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5223         struct rb_node *node;
5224
5225         ASSERT(inode->i_state & I_FREEING);
5226         truncate_inode_pages_final(&inode->i_data);
5227
5228         write_lock(&map_tree->lock);
5229         while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
5230                 struct extent_map *em;
5231
5232                 node = rb_first_cached(&map_tree->map);
5233                 em = rb_entry(node, struct extent_map, rb_node);
5234                 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5235                 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5236                 remove_extent_mapping(map_tree, em);
5237                 free_extent_map(em);
5238                 if (need_resched()) {
5239                         write_unlock(&map_tree->lock);
5240                         cond_resched();
5241                         write_lock(&map_tree->lock);
5242                 }
5243         }
5244         write_unlock(&map_tree->lock);
5245
5246         /*
5247          * Keep looping until we have no more ranges in the io tree.
5248          * We can have ongoing bios started by readahead that have
5249          * their endio callback (extent_io.c:end_bio_extent_readpage)
5250          * still in progress (unlocked the pages in the bio but did not yet
5251          * unlocked the ranges in the io tree). Therefore this means some
5252          * ranges can still be locked and eviction started because before
5253          * submitting those bios, which are executed by a separate task (work
5254          * queue kthread), inode references (inode->i_count) were not taken
5255          * (which would be dropped in the end io callback of each bio).
5256          * Therefore here we effectively end up waiting for those bios and
5257          * anyone else holding locked ranges without having bumped the inode's
5258          * reference count - if we don't do it, when they access the inode's
5259          * io_tree to unlock a range it may be too late, leading to an
5260          * use-after-free issue.
5261          */
5262         spin_lock(&io_tree->lock);
5263         while (!RB_EMPTY_ROOT(&io_tree->state)) {
5264                 struct extent_state *state;
5265                 struct extent_state *cached_state = NULL;
5266                 u64 start;
5267                 u64 end;
5268                 unsigned state_flags;
5269
5270                 node = rb_first(&io_tree->state);
5271                 state = rb_entry(node, struct extent_state, rb_node);
5272                 start = state->start;
5273                 end = state->end;
5274                 state_flags = state->state;
5275                 spin_unlock(&io_tree->lock);
5276
5277                 lock_extent_bits(io_tree, start, end, &cached_state);
5278
5279                 /*
5280                  * If still has DELALLOC flag, the extent didn't reach disk,
5281                  * and its reserved space won't be freed by delayed_ref.
5282                  * So we need to free its reserved space here.
5283                  * (Refer to comment in btrfs_invalidatepage, case 2)
5284                  *
5285                  * Note, end is the bytenr of last byte, so we need + 1 here.
5286                  */
5287                 if (state_flags & EXTENT_DELALLOC)
5288                         btrfs_qgroup_free_data(BTRFS_I(inode), NULL, start,
5289                                                end - start + 1);
5290
5291                 clear_extent_bit(io_tree, start, end,
5292                                  EXTENT_LOCKED | EXTENT_DELALLOC |
5293                                  EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
5294                                  &cached_state);
5295
5296                 cond_resched();
5297                 spin_lock(&io_tree->lock);
5298         }
5299         spin_unlock(&io_tree->lock);
5300 }
5301
5302 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5303                                                         struct btrfs_block_rsv *rsv)
5304 {
5305         struct btrfs_fs_info *fs_info = root->fs_info;
5306         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5307         struct btrfs_trans_handle *trans;
5308         u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
5309         int ret;
5310
5311         /*
5312          * Eviction should be taking place at some place safe because of our
5313          * delayed iputs.  However the normal flushing code will run delayed
5314          * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5315          *
5316          * We reserve the delayed_refs_extra here again because we can't use
5317          * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5318          * above.  We reserve our extra bit here because we generate a ton of
5319          * delayed refs activity by truncating.
5320          *
5321          * If we cannot make our reservation we'll attempt to steal from the
5322          * global reserve, because we really want to be able to free up space.
5323          */
5324         ret = btrfs_block_rsv_refill(root, rsv, rsv->size + delayed_refs_extra,
5325                                      BTRFS_RESERVE_FLUSH_EVICT);
5326         if (ret) {
5327                 /*
5328                  * Try to steal from the global reserve if there is space for
5329                  * it.
5330                  */
5331                 if (btrfs_check_space_for_delayed_refs(fs_info) ||
5332                     btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0)) {
5333                         btrfs_warn(fs_info,
5334                                    "could not allocate space for delete; will truncate on mount");
5335                         return ERR_PTR(-ENOSPC);
5336                 }
5337                 delayed_refs_extra = 0;
5338         }
5339
5340         trans = btrfs_join_transaction(root);
5341         if (IS_ERR(trans))
5342                 return trans;
5343
5344         if (delayed_refs_extra) {
5345                 trans->block_rsv = &fs_info->trans_block_rsv;
5346                 trans->bytes_reserved = delayed_refs_extra;
5347                 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5348                                         delayed_refs_extra, 1);
5349         }
5350         return trans;
5351 }
5352
5353 void btrfs_evict_inode(struct inode *inode)
5354 {
5355         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5356         struct btrfs_trans_handle *trans;
5357         struct btrfs_root *root = BTRFS_I(inode)->root;
5358         struct btrfs_block_rsv *rsv;
5359         int ret;
5360
5361         trace_btrfs_inode_evict(inode);
5362
5363         if (!root) {
5364                 clear_inode(inode);
5365                 return;
5366         }
5367
5368         evict_inode_truncate_pages(inode);
5369
5370         if (inode->i_nlink &&
5371             ((btrfs_root_refs(&root->root_item) != 0 &&
5372               root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5373              btrfs_is_free_space_inode(BTRFS_I(inode))))
5374                 goto no_delete;
5375
5376         if (is_bad_inode(inode))
5377                 goto no_delete;
5378
5379         btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5380
5381         if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5382                 goto no_delete;
5383
5384         if (inode->i_nlink > 0) {
5385                 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5386                        root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5387                 goto no_delete;
5388         }
5389
5390         ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5391         if (ret)
5392                 goto no_delete;
5393
5394         rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5395         if (!rsv)
5396                 goto no_delete;
5397         rsv->size = btrfs_calc_metadata_size(fs_info, 1);
5398         rsv->failfast = 1;
5399
5400         btrfs_i_size_write(BTRFS_I(inode), 0);
5401
5402         while (1) {
5403                 trans = evict_refill_and_join(root, rsv);
5404                 if (IS_ERR(trans))
5405                         goto free_rsv;
5406
5407                 trans->block_rsv = rsv;
5408
5409                 ret = btrfs_truncate_inode_items(trans, root, BTRFS_I(inode),
5410                                                  0, 0);
5411                 trans->block_rsv = &fs_info->trans_block_rsv;
5412                 btrfs_end_transaction(trans);
5413                 btrfs_btree_balance_dirty(fs_info);
5414                 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5415                         goto free_rsv;
5416                 else if (!ret)
5417                         break;
5418         }
5419
5420         /*
5421          * Errors here aren't a big deal, it just means we leave orphan items in
5422          * the tree. They will be cleaned up on the next mount. If the inode
5423          * number gets reused, cleanup deletes the orphan item without doing
5424          * anything, and unlink reuses the existing orphan item.
5425          *
5426          * If it turns out that we are dropping too many of these, we might want
5427          * to add a mechanism for retrying these after a commit.
5428          */
5429         trans = evict_refill_and_join(root, rsv);
5430         if (!IS_ERR(trans)) {
5431                 trans->block_rsv = rsv;
5432                 btrfs_orphan_del(trans, BTRFS_I(inode));
5433                 trans->block_rsv = &fs_info->trans_block_rsv;
5434                 btrfs_end_transaction(trans);
5435         }
5436
5437 free_rsv:
5438         btrfs_free_block_rsv(fs_info, rsv);
5439 no_delete:
5440         /*
5441          * If we didn't successfully delete, the orphan item will still be in
5442          * the tree and we'll retry on the next mount. Again, we might also want
5443          * to retry these periodically in the future.
5444          */
5445         btrfs_remove_delayed_node(BTRFS_I(inode));
5446         clear_inode(inode);
5447 }
5448
5449 /*
5450  * Return the key found in the dir entry in the location pointer, fill @type
5451  * with BTRFS_FT_*, and return 0.
5452  *
5453  * If no dir entries were found, returns -ENOENT.
5454  * If found a corrupted location in dir entry, returns -EUCLEAN.
5455  */
5456 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5457                                struct btrfs_key *location, u8 *type)
5458 {
5459         const char *name = dentry->d_name.name;
5460         int namelen = dentry->d_name.len;
5461         struct btrfs_dir_item *di;
5462         struct btrfs_path *path;
5463         struct btrfs_root *root = BTRFS_I(dir)->root;
5464         int ret = 0;
5465
5466         path = btrfs_alloc_path();
5467         if (!path)
5468                 return -ENOMEM;
5469
5470         di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5471                         name, namelen, 0);
5472         if (IS_ERR_OR_NULL(di)) {
5473                 ret = di ? PTR_ERR(di) : -ENOENT;
5474                 goto out;
5475         }
5476
5477         btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5478         if (location->type != BTRFS_INODE_ITEM_KEY &&
5479             location->type != BTRFS_ROOT_ITEM_KEY) {
5480                 ret = -EUCLEAN;
5481                 btrfs_warn(root->fs_info,
5482 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5483                            __func__, name, btrfs_ino(BTRFS_I(dir)),
5484                            location->objectid, location->type, location->offset);
5485         }
5486         if (!ret)
5487                 *type = btrfs_dir_type(path->nodes[0], di);
5488 out:
5489         btrfs_free_path(path);
5490         return ret;
5491 }
5492
5493 /*
5494  * when we hit a tree root in a directory, the btrfs part of the inode
5495  * needs to be changed to reflect the root directory of the tree root.  This
5496  * is kind of like crossing a mount point.
5497  */
5498 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5499                                     struct inode *dir,
5500                                     struct dentry *dentry,
5501                                     struct btrfs_key *location,
5502                                     struct btrfs_root **sub_root)
5503 {
5504         struct btrfs_path *path;
5505         struct btrfs_root *new_root;
5506         struct btrfs_root_ref *ref;
5507         struct extent_buffer *leaf;
5508         struct btrfs_key key;
5509         int ret;
5510         int err = 0;
5511
5512         path = btrfs_alloc_path();
5513         if (!path) {
5514                 err = -ENOMEM;
5515                 goto out;
5516         }
5517
5518         err = -ENOENT;
5519         key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5520         key.type = BTRFS_ROOT_REF_KEY;
5521         key.offset = location->objectid;
5522
5523         ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5524         if (ret) {
5525                 if (ret < 0)
5526                         err = ret;
5527                 goto out;
5528         }
5529
5530         leaf = path->nodes[0];
5531         ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5532         if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5533             btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5534                 goto out;
5535
5536         ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5537                                    (unsigned long)(ref + 1),
5538                                    dentry->d_name.len);
5539         if (ret)
5540                 goto out;
5541
5542         btrfs_release_path(path);
5543
5544         new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5545         if (IS_ERR(new_root)) {
5546                 err = PTR_ERR(new_root);
5547                 goto out;
5548         }
5549
5550         *sub_root = new_root;
5551         location->objectid = btrfs_root_dirid(&new_root->root_item);
5552         location->type = BTRFS_INODE_ITEM_KEY;
5553         location->offset = 0;
5554         err = 0;
5555 out:
5556         btrfs_free_path(path);
5557         return err;
5558 }
5559
5560 static void inode_tree_add(struct inode *inode)
5561 {
5562         struct btrfs_root *root = BTRFS_I(inode)->root;
5563         struct btrfs_inode *entry;
5564         struct rb_node **p;
5565         struct rb_node *parent;
5566         struct rb_node *new = &BTRFS_I(inode)->rb_node;
5567         u64 ino = btrfs_ino(BTRFS_I(inode));
5568
5569         if (inode_unhashed(inode))
5570                 return;
5571         parent = NULL;
5572         spin_lock(&root->inode_lock);
5573         p = &root->inode_tree.rb_node;
5574         while (*p) {
5575                 parent = *p;
5576                 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5577
5578                 if (ino < btrfs_ino(entry))
5579                         p = &parent->rb_left;
5580                 else if (ino > btrfs_ino(entry))
5581                         p = &parent->rb_right;
5582                 else {
5583                         WARN_ON(!(entry->vfs_inode.i_state &
5584                                   (I_WILL_FREE | I_FREEING)));
5585                         rb_replace_node(parent, new, &root->inode_tree);
5586                         RB_CLEAR_NODE(parent);
5587                         spin_unlock(&root->inode_lock);
5588                         return;
5589                 }
5590         }
5591         rb_link_node(new, parent, p);
5592         rb_insert_color(new, &root->inode_tree);
5593         spin_unlock(&root->inode_lock);
5594 }
5595
5596 static void inode_tree_del(struct btrfs_inode *inode)
5597 {
5598         struct btrfs_root *root = inode->root;
5599         int empty = 0;
5600
5601         spin_lock(&root->inode_lock);
5602         if (!RB_EMPTY_NODE(&inode->rb_node)) {
5603                 rb_erase(&inode->rb_node, &root->inode_tree);
5604                 RB_CLEAR_NODE(&inode->rb_node);
5605                 empty = RB_EMPTY_ROOT(&root->inode_tree);
5606         }
5607         spin_unlock(&root->inode_lock);
5608
5609         if (empty && btrfs_root_refs(&root->root_item) == 0) {
5610                 spin_lock(&root->inode_lock);
5611                 empty = RB_EMPTY_ROOT(&root->inode_tree);
5612                 spin_unlock(&root->inode_lock);
5613                 if (empty)
5614                         btrfs_add_dead_root(root);
5615         }
5616 }
5617
5618
5619 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5620 {
5621         struct btrfs_iget_args *args = p;
5622
5623         inode->i_ino = args->ino;
5624         BTRFS_I(inode)->location.objectid = args->ino;
5625         BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
5626         BTRFS_I(inode)->location.offset = 0;
5627         BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5628         BUG_ON(args->root && !BTRFS_I(inode)->root);
5629         return 0;
5630 }
5631
5632 static int btrfs_find_actor(struct inode *inode, void *opaque)
5633 {
5634         struct btrfs_iget_args *args = opaque;
5635
5636         return args->ino == BTRFS_I(inode)->location.objectid &&
5637                 args->root == BTRFS_I(inode)->root;
5638 }
5639
5640 static struct inode *btrfs_iget_locked(struct super_block *s, u64 ino,
5641                                        struct btrfs_root *root)
5642 {
5643         struct inode *inode;
5644         struct btrfs_iget_args args;
5645         unsigned long hashval = btrfs_inode_hash(ino, root);
5646
5647         args.ino = ino;
5648         args.root = root;
5649
5650         inode = iget5_locked(s, hashval, btrfs_find_actor,
5651                              btrfs_init_locked_inode,
5652                              (void *)&args);
5653         return inode;
5654 }
5655
5656 /*
5657  * Get an inode object given its inode number and corresponding root.
5658  * Path can be preallocated to prevent recursing back to iget through
5659  * allocator. NULL is also valid but may require an additional allocation
5660  * later.
5661  */
5662 struct inode *btrfs_iget_path(struct super_block *s, u64 ino,
5663                               struct btrfs_root *root, struct btrfs_path *path)
5664 {
5665         struct inode *inode;
5666
5667         inode = btrfs_iget_locked(s, ino, root);
5668         if (!inode)
5669                 return ERR_PTR(-ENOMEM);
5670
5671         if (inode->i_state & I_NEW) {
5672                 int ret;
5673
5674                 ret = btrfs_read_locked_inode(inode, path);
5675                 if (!ret) {
5676                         inode_tree_add(inode);
5677                         unlock_new_inode(inode);
5678                 } else {
5679                         iget_failed(inode);
5680                         /*
5681                          * ret > 0 can come from btrfs_search_slot called by
5682                          * btrfs_read_locked_inode, this means the inode item
5683                          * was not found.
5684                          */
5685                         if (ret > 0)
5686                                 ret = -ENOENT;
5687                         inode = ERR_PTR(ret);
5688                 }
5689         }
5690
5691         return inode;
5692 }
5693
5694 struct inode *btrfs_iget(struct super_block *s, u64 ino, struct btrfs_root *root)
5695 {
5696         return btrfs_iget_path(s, ino, root, NULL);
5697 }
5698
5699 static struct inode *new_simple_dir(struct super_block *s,
5700                                     struct btrfs_key *key,
5701                                     struct btrfs_root *root)
5702 {
5703         struct inode *inode = new_inode(s);
5704
5705         if (!inode)
5706                 return ERR_PTR(-ENOMEM);
5707
5708         BTRFS_I(inode)->root = btrfs_grab_root(root);
5709         memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5710         set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5711
5712         inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5713         /*
5714          * We only need lookup, the rest is read-only and there's no inode
5715          * associated with the dentry
5716          */
5717         inode->i_op = &simple_dir_inode_operations;
5718         inode->i_opflags &= ~IOP_XATTR;
5719         inode->i_fop = &simple_dir_operations;
5720         inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5721         inode->i_mtime = current_time(inode);
5722         inode->i_atime = inode->i_mtime;
5723         inode->i_ctime = inode->i_mtime;
5724         BTRFS_I(inode)->i_otime = inode->i_mtime;
5725
5726         return inode;
5727 }
5728
5729 static inline u8 btrfs_inode_type(struct inode *inode)
5730 {
5731         /*
5732          * Compile-time asserts that generic FT_* types still match
5733          * BTRFS_FT_* types
5734          */
5735         BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
5736         BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
5737         BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
5738         BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
5739         BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
5740         BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
5741         BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
5742         BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
5743
5744         return fs_umode_to_ftype(inode->i_mode);
5745 }
5746
5747 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5748 {
5749         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5750         struct inode *inode;
5751         struct btrfs_root *root = BTRFS_I(dir)->root;
5752         struct btrfs_root *sub_root = root;
5753         struct btrfs_key location;
5754         u8 di_type = 0;
5755         int ret = 0;
5756
5757         if (dentry->d_name.len > BTRFS_NAME_LEN)
5758                 return ERR_PTR(-ENAMETOOLONG);
5759
5760         ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5761         if (ret < 0)
5762                 return ERR_PTR(ret);
5763
5764         if (location.type == BTRFS_INODE_ITEM_KEY) {
5765                 inode = btrfs_iget(dir->i_sb, location.objectid, root);
5766                 if (IS_ERR(inode))
5767                         return inode;
5768
5769                 /* Do extra check against inode mode with di_type */
5770                 if (btrfs_inode_type(inode) != di_type) {
5771                         btrfs_crit(fs_info,
5772 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5773                                   inode->i_mode, btrfs_inode_type(inode),
5774                                   di_type);
5775                         iput(inode);
5776                         return ERR_PTR(-EUCLEAN);
5777                 }
5778                 return inode;
5779         }
5780
5781         ret = fixup_tree_root_location(fs_info, dir, dentry,
5782                                        &location, &sub_root);
5783         if (ret < 0) {
5784                 if (ret != -ENOENT)
5785                         inode = ERR_PTR(ret);
5786                 else
5787                         inode = new_simple_dir(dir->i_sb, &location, sub_root);
5788         } else {
5789                 inode = btrfs_iget(dir->i_sb, location.objectid, sub_root);
5790         }
5791         if (root != sub_root)
5792                 btrfs_put_root(sub_root);
5793
5794         if (!IS_ERR(inode) && root != sub_root) {
5795                 down_read(&fs_info->cleanup_work_sem);
5796                 if (!sb_rdonly(inode->i_sb))
5797                         ret = btrfs_orphan_cleanup(sub_root);
5798                 up_read(&fs_info->cleanup_work_sem);
5799                 if (ret) {
5800                         iput(inode);
5801                         inode = ERR_PTR(ret);
5802                 }
5803         }
5804
5805         return inode;
5806 }
5807
5808 static int btrfs_dentry_delete(const struct dentry *dentry)
5809 {
5810         struct btrfs_root *root;
5811         struct inode *inode = d_inode(dentry);
5812
5813         if (!inode && !IS_ROOT(dentry))
5814                 inode = d_inode(dentry->d_parent);
5815
5816         if (inode) {
5817                 root = BTRFS_I(inode)->root;
5818                 if (btrfs_root_refs(&root->root_item) == 0)
5819                         return 1;
5820
5821                 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5822                         return 1;
5823         }
5824         return 0;
5825 }
5826
5827 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5828                                    unsigned int flags)
5829 {
5830         struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5831
5832         if (inode == ERR_PTR(-ENOENT))
5833                 inode = NULL;
5834         return d_splice_alias(inode, dentry);
5835 }
5836
5837 /*
5838  * All this infrastructure exists because dir_emit can fault, and we are holding
5839  * the tree lock when doing readdir.  For now just allocate a buffer and copy
5840  * our information into that, and then dir_emit from the buffer.  This is
5841  * similar to what NFS does, only we don't keep the buffer around in pagecache
5842  * because I'm afraid I'll mess that up.  Long term we need to make filldir do
5843  * copy_to_user_inatomic so we don't have to worry about page faulting under the
5844  * tree lock.
5845  */
5846 static int btrfs_opendir(struct inode *inode, struct file *file)
5847 {
5848         struct btrfs_file_private *private;
5849
5850         private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5851         if (!private)
5852                 return -ENOMEM;
5853         private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5854         if (!private->filldir_buf) {
5855                 kfree(private);
5856                 return -ENOMEM;
5857         }
5858         file->private_data = private;
5859         return 0;
5860 }
5861
5862 struct dir_entry {
5863         u64 ino;
5864         u64 offset;
5865         unsigned type;
5866         int name_len;
5867 };
5868
5869 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5870 {
5871         while (entries--) {
5872                 struct dir_entry *entry = addr;
5873                 char *name = (char *)(entry + 1);
5874
5875                 ctx->pos = get_unaligned(&entry->offset);
5876                 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5877                                          get_unaligned(&entry->ino),
5878                                          get_unaligned(&entry->type)))
5879                         return 1;
5880                 addr += sizeof(struct dir_entry) +
5881                         get_unaligned(&entry->name_len);
5882                 ctx->pos++;
5883         }
5884         return 0;
5885 }
5886
5887 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5888 {
5889         struct inode *inode = file_inode(file);
5890         struct btrfs_root *root = BTRFS_I(inode)->root;
5891         struct btrfs_file_private *private = file->private_data;
5892         struct btrfs_dir_item *di;
5893         struct btrfs_key key;
5894         struct btrfs_key found_key;
5895         struct btrfs_path *path;
5896         void *addr;
5897         struct list_head ins_list;
5898         struct list_head del_list;
5899         int ret;
5900         struct extent_buffer *leaf;
5901         int slot;
5902         char *name_ptr;
5903         int name_len;
5904         int entries = 0;
5905         int total_len = 0;
5906         bool put = false;
5907         struct btrfs_key location;
5908
5909         if (!dir_emit_dots(file, ctx))
5910                 return 0;
5911
5912         path = btrfs_alloc_path();
5913         if (!path)
5914                 return -ENOMEM;
5915
5916         addr = private->filldir_buf;
5917         path->reada = READA_FORWARD;
5918
5919         INIT_LIST_HEAD(&ins_list);
5920         INIT_LIST_HEAD(&del_list);
5921         put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5922
5923 again:
5924         key.type = BTRFS_DIR_INDEX_KEY;
5925         key.offset = ctx->pos;
5926         key.objectid = btrfs_ino(BTRFS_I(inode));
5927
5928         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5929         if (ret < 0)
5930                 goto err;
5931
5932         while (1) {
5933                 struct dir_entry *entry;
5934
5935                 leaf = path->nodes[0];
5936                 slot = path->slots[0];
5937                 if (slot >= btrfs_header_nritems(leaf)) {
5938                         ret = btrfs_next_leaf(root, path);
5939                         if (ret < 0)
5940                                 goto err;
5941                         else if (ret > 0)
5942                                 break;
5943                         continue;
5944                 }
5945
5946                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5947
5948                 if (found_key.objectid != key.objectid)
5949                         break;
5950                 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5951                         break;
5952                 if (found_key.offset < ctx->pos)
5953                         goto next;
5954                 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5955                         goto next;
5956                 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5957                 name_len = btrfs_dir_name_len(leaf, di);
5958                 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5959                     PAGE_SIZE) {
5960                         btrfs_release_path(path);
5961                         ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5962                         if (ret)
5963                                 goto nopos;
5964                         addr = private->filldir_buf;
5965                         entries = 0;
5966                         total_len = 0;
5967                         goto again;
5968                 }
5969
5970                 entry = addr;
5971                 put_unaligned(name_len, &entry->name_len);
5972                 name_ptr = (char *)(entry + 1);
5973                 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5974                                    name_len);
5975                 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
5976                                 &entry->type);
5977                 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5978                 put_unaligned(location.objectid, &entry->ino);
5979                 put_unaligned(found_key.offset, &entry->offset);
5980                 entries++;
5981                 addr += sizeof(struct dir_entry) + name_len;
5982                 total_len += sizeof(struct dir_entry) + name_len;
5983 next:
5984                 path->slots[0]++;
5985         }
5986         btrfs_release_path(path);
5987
5988         ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5989         if (ret)
5990                 goto nopos;
5991
5992         ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5993         if (ret)
5994                 goto nopos;
5995
5996         /*
5997          * Stop new entries from being returned after we return the last
5998          * entry.
5999          *
6000          * New directory entries are assigned a strictly increasing
6001          * offset.  This means that new entries created during readdir
6002          * are *guaranteed* to be seen in the future by that readdir.
6003          * This has broken buggy programs which operate on names as
6004          * they're returned by readdir.  Until we re-use freed offsets
6005          * we have this hack to stop new entries from being returned
6006          * under the assumption that they'll never reach this huge
6007          * offset.
6008          *
6009          * This is being careful not to overflow 32bit loff_t unless the
6010          * last entry requires it because doing so has broken 32bit apps
6011          * in the past.
6012          */
6013         if (ctx->pos >= INT_MAX)
6014                 ctx->pos = LLONG_MAX;
6015         else
6016                 ctx->pos = INT_MAX;
6017 nopos:
6018         ret = 0;
6019 err:
6020         if (put)
6021                 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6022         btrfs_free_path(path);
6023         return ret;
6024 }
6025
6026 /*
6027  * This is somewhat expensive, updating the tree every time the
6028  * inode changes.  But, it is most likely to find the inode in cache.
6029  * FIXME, needs more benchmarking...there are no reasons other than performance
6030  * to keep or drop this code.
6031  */
6032 static int btrfs_dirty_inode(struct inode *inode)
6033 {
6034         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6035         struct btrfs_root *root = BTRFS_I(inode)->root;
6036         struct btrfs_trans_handle *trans;
6037         int ret;
6038
6039         if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6040                 return 0;
6041
6042         trans = btrfs_join_transaction(root);
6043         if (IS_ERR(trans))
6044                 return PTR_ERR(trans);
6045
6046         ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
6047         if (ret && ret == -ENOSPC) {
6048                 /* whoops, lets try again with the full transaction */
6049                 btrfs_end_transaction(trans);
6050                 trans = btrfs_start_transaction(root, 1);
6051                 if (IS_ERR(trans))
6052                         return PTR_ERR(trans);
6053
6054                 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
6055         }
6056         btrfs_end_transaction(trans);
6057         if (BTRFS_I(inode)->delayed_node)
6058                 btrfs_balance_delayed_items(fs_info);
6059
6060         return ret;
6061 }
6062
6063 /*
6064  * This is a copy of file_update_time.  We need this so we can return error on
6065  * ENOSPC for updating the inode in the case of file write and mmap writes.
6066  */
6067 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
6068                              int flags)
6069 {
6070         struct btrfs_root *root = BTRFS_I(inode)->root;
6071         bool dirty = flags & ~S_VERSION;
6072
6073         if (btrfs_root_readonly(root))
6074                 return -EROFS;
6075
6076         if (flags & S_VERSION)
6077                 dirty |= inode_maybe_inc_iversion(inode, dirty);
6078         if (flags & S_CTIME)
6079                 inode->i_ctime = *now;
6080         if (flags & S_MTIME)
6081                 inode->i_mtime = *now;
6082         if (flags & S_ATIME)
6083                 inode->i_atime = *now;
6084         return dirty ? btrfs_dirty_inode(inode) : 0;
6085 }
6086
6087 /*
6088  * find the highest existing sequence number in a directory
6089  * and then set the in-memory index_cnt variable to reflect
6090  * free sequence numbers
6091  */
6092 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6093 {
6094         struct btrfs_root *root = inode->root;
6095         struct btrfs_key key, found_key;
6096         struct btrfs_path *path;
6097         struct extent_buffer *leaf;
6098         int ret;
6099
6100         key.objectid = btrfs_ino(inode);
6101         key.type = BTRFS_DIR_INDEX_KEY;
6102         key.offset = (u64)-1;
6103
6104         path = btrfs_alloc_path();
6105         if (!path)
6106                 return -ENOMEM;
6107
6108         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6109         if (ret < 0)
6110                 goto out;
6111         /* FIXME: we should be able to handle this */
6112         if (ret == 0)
6113                 goto out;
6114         ret = 0;
6115
6116         /*
6117          * MAGIC NUMBER EXPLANATION:
6118          * since we search a directory based on f_pos we have to start at 2
6119          * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6120          * else has to start at 2
6121          */
6122         if (path->slots[0] == 0) {
6123                 inode->index_cnt = 2;
6124                 goto out;
6125         }
6126
6127         path->slots[0]--;
6128
6129         leaf = path->nodes[0];
6130         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6131
6132         if (found_key.objectid != btrfs_ino(inode) ||
6133             found_key.type != BTRFS_DIR_INDEX_KEY) {
6134                 inode->index_cnt = 2;
6135                 goto out;
6136         }
6137
6138         inode->index_cnt = found_key.offset + 1;
6139 out:
6140         btrfs_free_path(path);
6141         return ret;
6142 }
6143
6144 /*
6145  * helper to find a free sequence number in a given directory.  This current
6146  * code is very simple, later versions will do smarter things in the btree
6147  */
6148 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6149 {
6150         int ret = 0;
6151
6152         if (dir->index_cnt == (u64)-1) {
6153                 ret = btrfs_inode_delayed_dir_index_count(dir);
6154                 if (ret) {
6155                         ret = btrfs_set_inode_index_count(dir);
6156                         if (ret)
6157                                 return ret;
6158                 }
6159         }
6160
6161         *index = dir->index_cnt;
6162         dir->index_cnt++;
6163
6164         return ret;
6165 }
6166
6167 static int btrfs_insert_inode_locked(struct inode *inode)
6168 {
6169         struct btrfs_iget_args args;
6170
6171         args.ino = BTRFS_I(inode)->location.objectid;
6172         args.root = BTRFS_I(inode)->root;
6173
6174         return insert_inode_locked4(inode,
6175                    btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6176                    btrfs_find_actor, &args);
6177 }
6178
6179 /*
6180  * Inherit flags from the parent inode.
6181  *
6182  * Currently only the compression flags and the cow flags are inherited.
6183  */
6184 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6185 {
6186         unsigned int flags;
6187
6188         if (!dir)
6189                 return;
6190
6191         flags = BTRFS_I(dir)->flags;
6192
6193         if (flags & BTRFS_INODE_NOCOMPRESS) {
6194                 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6195                 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6196         } else if (flags & BTRFS_INODE_COMPRESS) {
6197                 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6198                 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6199         }
6200
6201         if (flags & BTRFS_INODE_NODATACOW) {
6202                 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6203                 if (S_ISREG(inode->i_mode))
6204                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6205         }
6206
6207         btrfs_sync_inode_flags_to_i_flags(inode);
6208 }
6209
6210 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6211                                      struct btrfs_root *root,
6212                                      struct inode *dir,
6213                                      const char *name, int name_len,
6214                                      u64 ref_objectid, u64 objectid,
6215                                      umode_t mode, u64 *index)
6216 {
6217         struct btrfs_fs_info *fs_info = root->fs_info;
6218         struct inode *inode;
6219         struct btrfs_inode_item *inode_item;
6220         struct btrfs_key *location;
6221         struct btrfs_path *path;
6222         struct btrfs_inode_ref *ref;
6223         struct btrfs_key key[2];
6224         u32 sizes[2];
6225         int nitems = name ? 2 : 1;
6226         unsigned long ptr;
6227         unsigned int nofs_flag;
6228         int ret;
6229
6230         path = btrfs_alloc_path();
6231         if (!path)
6232                 return ERR_PTR(-ENOMEM);
6233
6234         nofs_flag = memalloc_nofs_save();
6235         inode = new_inode(fs_info->sb);
6236         memalloc_nofs_restore(nofs_flag);
6237         if (!inode) {
6238                 btrfs_free_path(path);
6239                 return ERR_PTR(-ENOMEM);
6240         }
6241
6242         /*
6243          * O_TMPFILE, set link count to 0, so that after this point,
6244          * we fill in an inode item with the correct link count.
6245          */
6246         if (!name)
6247                 set_nlink(inode, 0);
6248
6249         /*
6250          * we have to initialize this early, so we can reclaim the inode
6251          * number if we fail afterwards in this function.
6252          */
6253         inode->i_ino = objectid;
6254
6255         if (dir && name) {
6256                 trace_btrfs_inode_request(dir);
6257
6258                 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6259                 if (ret) {
6260                         btrfs_free_path(path);
6261                         iput(inode);
6262                         return ERR_PTR(ret);
6263                 }
6264         } else if (dir) {
6265                 *index = 0;
6266         }
6267         /*
6268          * index_cnt is ignored for everything but a dir,
6269          * btrfs_set_inode_index_count has an explanation for the magic
6270          * number
6271          */
6272         BTRFS_I(inode)->index_cnt = 2;
6273         BTRFS_I(inode)->dir_index = *index;
6274         BTRFS_I(inode)->root = btrfs_grab_root(root);
6275         BTRFS_I(inode)->generation = trans->transid;
6276         inode->i_generation = BTRFS_I(inode)->generation;
6277
6278         /*
6279          * We could have gotten an inode number from somebody who was fsynced
6280          * and then removed in this same transaction, so let's just set full
6281          * sync since it will be a full sync anyway and this will blow away the
6282          * old info in the log.
6283          */
6284         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6285
6286         key[0].objectid = objectid;
6287         key[0].type = BTRFS_INODE_ITEM_KEY;
6288         key[0].offset = 0;
6289
6290         sizes[0] = sizeof(struct btrfs_inode_item);
6291
6292         if (name) {
6293                 /*
6294                  * Start new inodes with an inode_ref. This is slightly more
6295                  * efficient for small numbers of hard links since they will
6296                  * be packed into one item. Extended refs will kick in if we
6297                  * add more hard links than can fit in the ref item.
6298                  */
6299                 key[1].objectid = objectid;
6300                 key[1].type = BTRFS_INODE_REF_KEY;
6301                 key[1].offset = ref_objectid;
6302
6303                 sizes[1] = name_len + sizeof(*ref);
6304         }
6305
6306         location = &BTRFS_I(inode)->location;
6307         location->objectid = objectid;
6308         location->offset = 0;
6309         location->type = BTRFS_INODE_ITEM_KEY;
6310
6311         ret = btrfs_insert_inode_locked(inode);
6312         if (ret < 0) {
6313                 iput(inode);
6314                 goto fail;
6315         }
6316
6317         ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6318         if (ret != 0)
6319                 goto fail_unlock;
6320
6321         inode_init_owner(inode, dir, mode);
6322         inode_set_bytes(inode, 0);
6323
6324         inode->i_mtime = current_time(inode);
6325         inode->i_atime = inode->i_mtime;
6326         inode->i_ctime = inode->i_mtime;
6327         BTRFS_I(inode)->i_otime = inode->i_mtime;
6328
6329         inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6330                                   struct btrfs_inode_item);
6331         memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6332                              sizeof(*inode_item));
6333         fill_inode_item(trans, path->nodes[0], inode_item, inode);
6334
6335         if (name) {
6336                 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6337                                      struct btrfs_inode_ref);
6338                 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6339                 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6340                 ptr = (unsigned long)(ref + 1);
6341                 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6342         }
6343
6344         btrfs_mark_buffer_dirty(path->nodes[0]);
6345         btrfs_free_path(path);
6346
6347         btrfs_inherit_iflags(inode, dir);
6348
6349         if (S_ISREG(mode)) {
6350                 if (btrfs_test_opt(fs_info, NODATASUM))
6351                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6352                 if (btrfs_test_opt(fs_info, NODATACOW))
6353                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6354                                 BTRFS_INODE_NODATASUM;
6355         }
6356
6357         inode_tree_add(inode);
6358
6359         trace_btrfs_inode_new(inode);
6360         btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
6361
6362         btrfs_update_root_times(trans, root);
6363
6364         ret = btrfs_inode_inherit_props(trans, inode, dir);
6365         if (ret)
6366                 btrfs_err(fs_info,
6367                           "error inheriting props for ino %llu (root %llu): %d",
6368                         btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6369
6370         return inode;
6371
6372 fail_unlock:
6373         discard_new_inode(inode);
6374 fail:
6375         if (dir && name)
6376                 BTRFS_I(dir)->index_cnt--;
6377         btrfs_free_path(path);
6378         return ERR_PTR(ret);
6379 }
6380
6381 /*
6382  * utility function to add 'inode' into 'parent_inode' with
6383  * a give name and a given sequence number.
6384  * if 'add_backref' is true, also insert a backref from the
6385  * inode to the parent directory.
6386  */
6387 int btrfs_add_link(struct btrfs_trans_handle *trans,
6388                    struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6389                    const char *name, int name_len, int add_backref, u64 index)
6390 {
6391         int ret = 0;
6392         struct btrfs_key key;
6393         struct btrfs_root *root = parent_inode->root;
6394         u64 ino = btrfs_ino(inode);
6395         u64 parent_ino = btrfs_ino(parent_inode);
6396
6397         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6398                 memcpy(&key, &inode->root->root_key, sizeof(key));
6399         } else {
6400                 key.objectid = ino;
6401                 key.type = BTRFS_INODE_ITEM_KEY;
6402                 key.offset = 0;
6403         }
6404
6405         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6406                 ret = btrfs_add_root_ref(trans, key.objectid,
6407                                          root->root_key.objectid, parent_ino,
6408                                          index, name, name_len);
6409         } else if (add_backref) {
6410                 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6411                                              parent_ino, index);
6412         }
6413
6414         /* Nothing to clean up yet */
6415         if (ret)
6416                 return ret;
6417
6418         ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6419                                     btrfs_inode_type(&inode->vfs_inode), index);
6420         if (ret == -EEXIST || ret == -EOVERFLOW)
6421                 goto fail_dir_item;
6422         else if (ret) {
6423                 btrfs_abort_transaction(trans, ret);
6424                 return ret;
6425         }
6426
6427         btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6428                            name_len * 2);
6429         inode_inc_iversion(&parent_inode->vfs_inode);
6430         /*
6431          * If we are replaying a log tree, we do not want to update the mtime
6432          * and ctime of the parent directory with the current time, since the
6433          * log replay procedure is responsible for setting them to their correct
6434          * values (the ones it had when the fsync was done).
6435          */
6436         if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6437                 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6438
6439                 parent_inode->vfs_inode.i_mtime = now;
6440                 parent_inode->vfs_inode.i_ctime = now;
6441         }
6442         ret = btrfs_update_inode(trans, root, parent_inode);
6443         if (ret)
6444                 btrfs_abort_transaction(trans, ret);
6445         return ret;
6446
6447 fail_dir_item:
6448         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6449                 u64 local_index;
6450                 int err;
6451                 err = btrfs_del_root_ref(trans, key.objectid,
6452                                          root->root_key.objectid, parent_ino,
6453                                          &local_index, name, name_len);
6454                 if (err)
6455                         btrfs_abort_transaction(trans, err);
6456         } else if (add_backref) {
6457                 u64 local_index;
6458                 int err;
6459
6460                 err = btrfs_del_inode_ref(trans, root, name, name_len,
6461                                           ino, parent_ino, &local_index);
6462                 if (err)
6463                         btrfs_abort_transaction(trans, err);
6464         }
6465
6466         /* Return the original error code */
6467         return ret;
6468 }
6469
6470 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6471                             struct btrfs_inode *dir, struct dentry *dentry,
6472                             struct btrfs_inode *inode, int backref, u64 index)
6473 {
6474         int err = btrfs_add_link(trans, dir, inode,
6475                                  dentry->d_name.name, dentry->d_name.len,
6476                                  backref, index);
6477         if (err > 0)
6478                 err = -EEXIST;
6479         return err;
6480 }
6481
6482 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6483                         umode_t mode, dev_t rdev)
6484 {
6485         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6486         struct btrfs_trans_handle *trans;
6487         struct btrfs_root *root = BTRFS_I(dir)->root;
6488         struct inode *inode = NULL;
6489         int err;
6490         u64 objectid;
6491         u64 index = 0;
6492
6493         /*
6494          * 2 for inode item and ref
6495          * 2 for dir items
6496          * 1 for xattr if selinux is on
6497          */
6498         trans = btrfs_start_transaction(root, 5);
6499         if (IS_ERR(trans))
6500                 return PTR_ERR(trans);
6501
6502         err = btrfs_get_free_objectid(root, &objectid);
6503         if (err)
6504                 goto out_unlock;
6505
6506         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6507                         dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6508                         mode, &index);
6509         if (IS_ERR(inode)) {
6510                 err = PTR_ERR(inode);
6511                 inode = NULL;
6512                 goto out_unlock;
6513         }
6514
6515         /*
6516         * If the active LSM wants to access the inode during
6517         * d_instantiate it needs these. Smack checks to see
6518         * if the filesystem supports xattrs by looking at the
6519         * ops vector.
6520         */
6521         inode->i_op = &btrfs_special_inode_operations;
6522         init_special_inode(inode, inode->i_mode, rdev);
6523
6524         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6525         if (err)
6526                 goto out_unlock;
6527
6528         err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6529                         0, index);
6530         if (err)
6531                 goto out_unlock;
6532
6533         btrfs_update_inode(trans, root, BTRFS_I(inode));
6534         d_instantiate_new(dentry, inode);
6535
6536 out_unlock:
6537         btrfs_end_transaction(trans);
6538         btrfs_btree_balance_dirty(fs_info);
6539         if (err && inode) {
6540                 inode_dec_link_count(inode);
6541                 discard_new_inode(inode);
6542         }
6543         return err;
6544 }
6545
6546 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6547                         umode_t mode, bool excl)
6548 {
6549         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6550         struct btrfs_trans_handle *trans;
6551         struct btrfs_root *root = BTRFS_I(dir)->root;
6552         struct inode *inode = NULL;
6553         int err;
6554         u64 objectid;
6555         u64 index = 0;
6556
6557         /*
6558          * 2 for inode item and ref
6559          * 2 for dir items
6560          * 1 for xattr if selinux is on
6561          */
6562         trans = btrfs_start_transaction(root, 5);
6563         if (IS_ERR(trans))
6564                 return PTR_ERR(trans);
6565
6566         err = btrfs_get_free_objectid(root, &objectid);
6567         if (err)
6568                 goto out_unlock;
6569
6570         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6571                         dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6572                         mode, &index);
6573         if (IS_ERR(inode)) {
6574                 err = PTR_ERR(inode);
6575                 inode = NULL;
6576                 goto out_unlock;
6577         }
6578         /*
6579         * If the active LSM wants to access the inode during
6580         * d_instantiate it needs these. Smack checks to see
6581         * if the filesystem supports xattrs by looking at the
6582         * ops vector.
6583         */
6584         inode->i_fop = &btrfs_file_operations;
6585         inode->i_op = &btrfs_file_inode_operations;
6586         inode->i_mapping->a_ops = &btrfs_aops;
6587
6588         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6589         if (err)
6590                 goto out_unlock;
6591
6592         err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6593         if (err)
6594                 goto out_unlock;
6595
6596         err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6597                         0, index);
6598         if (err)
6599                 goto out_unlock;
6600
6601         d_instantiate_new(dentry, inode);
6602
6603 out_unlock:
6604         btrfs_end_transaction(trans);
6605         if (err && inode) {
6606                 inode_dec_link_count(inode);
6607                 discard_new_inode(inode);
6608         }
6609         btrfs_btree_balance_dirty(fs_info);
6610         return err;
6611 }
6612
6613 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6614                       struct dentry *dentry)
6615 {
6616         struct btrfs_trans_handle *trans = NULL;
6617         struct btrfs_root *root = BTRFS_I(dir)->root;
6618         struct inode *inode = d_inode(old_dentry);
6619         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6620         u64 index;
6621         int err;
6622         int drop_inode = 0;
6623
6624         /* do not allow sys_link's with other subvols of the same device */
6625         if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6626                 return -EXDEV;
6627
6628         if (inode->i_nlink >= BTRFS_LINK_MAX)
6629                 return -EMLINK;
6630
6631         err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6632         if (err)
6633                 goto fail;
6634
6635         /*
6636          * 2 items for inode and inode ref
6637          * 2 items for dir items
6638          * 1 item for parent inode
6639          * 1 item for orphan item deletion if O_TMPFILE
6640          */
6641         trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6642         if (IS_ERR(trans)) {
6643                 err = PTR_ERR(trans);
6644                 trans = NULL;
6645                 goto fail;
6646         }
6647
6648         /* There are several dir indexes for this inode, clear the cache. */
6649         BTRFS_I(inode)->dir_index = 0ULL;
6650         inc_nlink(inode);
6651         inode_inc_iversion(inode);
6652         inode->i_ctime = current_time(inode);
6653         ihold(inode);
6654         set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6655
6656         err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6657                         1, index);
6658
6659         if (err) {
6660                 drop_inode = 1;
6661         } else {
6662                 struct dentry *parent = dentry->d_parent;
6663
6664                 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6665                 if (err)
6666                         goto fail;
6667                 if (inode->i_nlink == 1) {
6668                         /*
6669                          * If new hard link count is 1, it's a file created
6670                          * with open(2) O_TMPFILE flag.
6671                          */
6672                         err = btrfs_orphan_del(trans, BTRFS_I(inode));
6673                         if (err)
6674                                 goto fail;
6675                 }
6676                 d_instantiate(dentry, inode);
6677                 btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent);
6678         }
6679
6680 fail:
6681         if (trans)
6682                 btrfs_end_transaction(trans);
6683         if (drop_inode) {
6684                 inode_dec_link_count(inode);
6685                 iput(inode);
6686         }
6687         btrfs_btree_balance_dirty(fs_info);
6688         return err;
6689 }
6690
6691 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6692 {
6693         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6694         struct inode *inode = NULL;
6695         struct btrfs_trans_handle *trans;
6696         struct btrfs_root *root = BTRFS_I(dir)->root;
6697         int err = 0;
6698         u64 objectid = 0;
6699         u64 index = 0;
6700
6701         /*
6702          * 2 items for inode and ref
6703          * 2 items for dir items
6704          * 1 for xattr if selinux is on
6705          */
6706         trans = btrfs_start_transaction(root, 5);
6707         if (IS_ERR(trans))
6708                 return PTR_ERR(trans);
6709
6710         err = btrfs_get_free_objectid(root, &objectid);
6711         if (err)
6712                 goto out_fail;
6713
6714         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6715                         dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6716                         S_IFDIR | mode, &index);
6717         if (IS_ERR(inode)) {
6718                 err = PTR_ERR(inode);
6719                 inode = NULL;
6720                 goto out_fail;
6721         }
6722
6723         /* these must be set before we unlock the inode */
6724         inode->i_op = &btrfs_dir_inode_operations;
6725         inode->i_fop = &btrfs_dir_file_operations;
6726
6727         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6728         if (err)
6729                 goto out_fail;
6730
6731         btrfs_i_size_write(BTRFS_I(inode), 0);
6732         err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6733         if (err)
6734                 goto out_fail;
6735
6736         err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6737                         dentry->d_name.name,
6738                         dentry->d_name.len, 0, index);
6739         if (err)
6740                 goto out_fail;
6741
6742         d_instantiate_new(dentry, inode);
6743
6744 out_fail:
6745         btrfs_end_transaction(trans);
6746         if (err && inode) {
6747                 inode_dec_link_count(inode);
6748                 discard_new_inode(inode);
6749         }
6750         btrfs_btree_balance_dirty(fs_info);
6751         return err;
6752 }
6753
6754 static noinline int uncompress_inline(struct btrfs_path *path,
6755                                       struct page *page,
6756                                       size_t pg_offset, u64 extent_offset,
6757                                       struct btrfs_file_extent_item *item)
6758 {
6759         int ret;
6760         struct extent_buffer *leaf = path->nodes[0];
6761         char *tmp;
6762         size_t max_size;
6763         unsigned long inline_size;
6764         unsigned long ptr;
6765         int compress_type;
6766
6767         WARN_ON(pg_offset != 0);
6768         compress_type = btrfs_file_extent_compression(leaf, item);
6769         max_size = btrfs_file_extent_ram_bytes(leaf, item);
6770         inline_size = btrfs_file_extent_inline_item_len(leaf,
6771                                         btrfs_item_nr(path->slots[0]));
6772         tmp = kmalloc(inline_size, GFP_NOFS);
6773         if (!tmp)
6774                 return -ENOMEM;
6775         ptr = btrfs_file_extent_inline_start(item);
6776
6777         read_extent_buffer(leaf, tmp, ptr, inline_size);
6778
6779         max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6780         ret = btrfs_decompress(compress_type, tmp, page,
6781                                extent_offset, inline_size, max_size);
6782
6783         /*
6784          * decompression code contains a memset to fill in any space between the end
6785          * of the uncompressed data and the end of max_size in case the decompressed
6786          * data ends up shorter than ram_bytes.  That doesn't cover the hole between
6787          * the end of an inline extent and the beginning of the next block, so we
6788          * cover that region here.
6789          */
6790
6791         if (max_size + pg_offset < PAGE_SIZE) {
6792                 char *map = kmap(page);
6793                 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6794                 kunmap(page);
6795         }
6796         kfree(tmp);
6797         return ret;
6798 }
6799
6800 /**
6801  * btrfs_get_extent - Lookup the first extent overlapping a range in a file.
6802  * @inode:      file to search in
6803  * @page:       page to read extent data into if the extent is inline
6804  * @pg_offset:  offset into @page to copy to
6805  * @start:      file offset
6806  * @len:        length of range starting at @start
6807  *
6808  * This returns the first &struct extent_map which overlaps with the given
6809  * range, reading it from the B-tree and caching it if necessary. Note that
6810  * there may be more extents which overlap the given range after the returned
6811  * extent_map.
6812  *
6813  * If @page is not NULL and the extent is inline, this also reads the extent
6814  * data directly into the page and marks the extent up to date in the io_tree.
6815  *
6816  * Return: ERR_PTR on error, non-NULL extent_map on success.
6817  */
6818 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6819                                     struct page *page, size_t pg_offset,
6820                                     u64 start, u64 len)
6821 {
6822         struct btrfs_fs_info *fs_info = inode->root->fs_info;
6823         int ret = 0;
6824         u64 extent_start = 0;
6825         u64 extent_end = 0;
6826         u64 objectid = btrfs_ino(inode);
6827         int extent_type = -1;
6828         struct btrfs_path *path = NULL;
6829         struct btrfs_root *root = inode->root;
6830         struct btrfs_file_extent_item *item;
6831         struct extent_buffer *leaf;
6832         struct btrfs_key found_key;
6833         struct extent_map *em = NULL;
6834         struct extent_map_tree *em_tree = &inode->extent_tree;
6835         struct extent_io_tree *io_tree = &inode->io_tree;
6836
6837         read_lock(&em_tree->lock);
6838         em = lookup_extent_mapping(em_tree, start, len);
6839         read_unlock(&em_tree->lock);
6840
6841         if (em) {
6842                 if (em->start > start || em->start + em->len <= start)
6843                         free_extent_map(em);
6844                 else if (em->block_start == EXTENT_MAP_INLINE && page)
6845                         free_extent_map(em);
6846                 else
6847                         goto out;
6848         }
6849         em = alloc_extent_map();
6850         if (!em) {
6851                 ret = -ENOMEM;
6852                 goto out;
6853         }
6854         em->start = EXTENT_MAP_HOLE;
6855         em->orig_start = EXTENT_MAP_HOLE;
6856         em->len = (u64)-1;
6857         em->block_len = (u64)-1;
6858
6859         path = btrfs_alloc_path();
6860         if (!path) {
6861                 ret = -ENOMEM;
6862                 goto out;
6863         }
6864
6865         /* Chances are we'll be called again, so go ahead and do readahead */
6866         path->reada = READA_FORWARD;
6867
6868         /*
6869          * The same explanation in load_free_space_cache applies here as well,
6870          * we only read when we're loading the free space cache, and at that
6871          * point the commit_root has everything we need.
6872          */
6873         if (btrfs_is_free_space_inode(inode)) {
6874                 path->search_commit_root = 1;
6875                 path->skip_locking = 1;
6876         }
6877
6878         ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6879         if (ret < 0) {
6880                 goto out;
6881         } else if (ret > 0) {
6882                 if (path->slots[0] == 0)
6883                         goto not_found;
6884                 path->slots[0]--;
6885                 ret = 0;
6886         }
6887
6888         leaf = path->nodes[0];
6889         item = btrfs_item_ptr(leaf, path->slots[0],
6890                               struct btrfs_file_extent_item);
6891         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6892         if (found_key.objectid != objectid ||
6893             found_key.type != BTRFS_EXTENT_DATA_KEY) {
6894                 /*
6895                  * If we backup past the first extent we want to move forward
6896                  * and see if there is an extent in front of us, otherwise we'll
6897                  * say there is a hole for our whole search range which can
6898                  * cause problems.
6899                  */
6900                 extent_end = start;
6901                 goto next;
6902         }
6903
6904         extent_type = btrfs_file_extent_type(leaf, item);
6905         extent_start = found_key.offset;
6906         extent_end = btrfs_file_extent_end(path);
6907         if (extent_type == BTRFS_FILE_EXTENT_REG ||
6908             extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6909                 /* Only regular file could have regular/prealloc extent */
6910                 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6911                         ret = -EUCLEAN;
6912                         btrfs_crit(fs_info,
6913                 "regular/prealloc extent found for non-regular inode %llu",
6914                                    btrfs_ino(inode));
6915                         goto out;
6916                 }
6917                 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6918                                                        extent_start);
6919         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6920                 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6921                                                       path->slots[0],
6922                                                       extent_start);
6923         }
6924 next:
6925         if (start >= extent_end) {
6926                 path->slots[0]++;
6927                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6928                         ret = btrfs_next_leaf(root, path);
6929                         if (ret < 0)
6930                                 goto out;
6931                         else if (ret > 0)
6932                                 goto not_found;
6933
6934                         leaf = path->nodes[0];
6935                 }
6936                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6937                 if (found_key.objectid != objectid ||
6938                     found_key.type != BTRFS_EXTENT_DATA_KEY)
6939                         goto not_found;
6940                 if (start + len <= found_key.offset)
6941                         goto not_found;
6942                 if (start > found_key.offset)
6943                         goto next;
6944
6945                 /* New extent overlaps with existing one */
6946                 em->start = start;
6947                 em->orig_start = start;
6948                 em->len = found_key.offset - start;
6949                 em->block_start = EXTENT_MAP_HOLE;
6950                 goto insert;
6951         }
6952
6953         btrfs_extent_item_to_extent_map(inode, path, item, !page, em);
6954
6955         if (extent_type == BTRFS_FILE_EXTENT_REG ||
6956             extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6957                 goto insert;
6958         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6959                 unsigned long ptr;
6960                 char *map;
6961                 size_t size;
6962                 size_t extent_offset;
6963                 size_t copy_size;
6964
6965                 if (!page)
6966                         goto out;
6967
6968                 size = btrfs_file_extent_ram_bytes(leaf, item);
6969                 extent_offset = page_offset(page) + pg_offset - extent_start;
6970                 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6971                                   size - extent_offset);
6972                 em->start = extent_start + extent_offset;
6973                 em->len = ALIGN(copy_size, fs_info->sectorsize);
6974                 em->orig_block_len = em->len;
6975                 em->orig_start = em->start;
6976                 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6977
6978                 if (!PageUptodate(page)) {
6979                         if (btrfs_file_extent_compression(leaf, item) !=
6980                             BTRFS_COMPRESS_NONE) {
6981                                 ret = uncompress_inline(path, page, pg_offset,
6982                                                         extent_offset, item);
6983                                 if (ret)
6984                                         goto out;
6985                         } else {
6986                                 map = kmap(page);
6987                                 read_extent_buffer(leaf, map + pg_offset, ptr,
6988                                                    copy_size);
6989                                 if (pg_offset + copy_size < PAGE_SIZE) {
6990                                         memset(map + pg_offset + copy_size, 0,
6991                                                PAGE_SIZE - pg_offset -
6992                                                copy_size);
6993                                 }
6994                                 kunmap(page);
6995                         }
6996                         flush_dcache_page(page);
6997                 }
6998                 set_extent_uptodate(io_tree, em->start,
6999                                     extent_map_end(em) - 1, NULL, GFP_NOFS);
7000                 goto insert;
7001         }
7002 not_found:
7003         em->start = start;
7004         em->orig_start = start;
7005         em->len = len;
7006         em->block_start = EXTENT_MAP_HOLE;
7007 insert:
7008         ret = 0;
7009         btrfs_release_path(path);
7010         if (em->start > start || extent_map_end(em) <= start) {
7011                 btrfs_err(fs_info,
7012                           "bad extent! em: [%llu %llu] passed [%llu %llu]",
7013                           em->start, em->len, start, len);
7014                 ret = -EIO;
7015                 goto out;
7016         }
7017
7018         write_lock(&em_tree->lock);
7019         ret = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
7020         write_unlock(&em_tree->lock);
7021 out:
7022         btrfs_free_path(path);
7023
7024         trace_btrfs_get_extent(root, inode, em);
7025
7026         if (ret) {
7027                 free_extent_map(em);
7028                 return ERR_PTR(ret);
7029         }
7030         return em;
7031 }
7032
7033 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7034                                            u64 start, u64 len)
7035 {
7036         struct extent_map *em;
7037         struct extent_map *hole_em = NULL;
7038         u64 delalloc_start = start;
7039         u64 end;
7040         u64 delalloc_len;
7041         u64 delalloc_end;
7042         int err = 0;
7043
7044         em = btrfs_get_extent(inode, NULL, 0, start, len);
7045         if (IS_ERR(em))
7046                 return em;
7047         /*
7048          * If our em maps to:
7049          * - a hole or
7050          * - a pre-alloc extent,
7051          * there might actually be delalloc bytes behind it.
7052          */
7053         if (em->block_start != EXTENT_MAP_HOLE &&
7054             !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7055                 return em;
7056         else
7057                 hole_em = em;
7058
7059         /* check to see if we've wrapped (len == -1 or similar) */
7060         end = start + len;
7061         if (end < start)
7062                 end = (u64)-1;
7063         else
7064                 end -= 1;
7065
7066         em = NULL;
7067
7068         /* ok, we didn't find anything, lets look for delalloc */
7069         delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
7070                                  end, len, EXTENT_DELALLOC, 1);
7071         delalloc_end = delalloc_start + delalloc_len;
7072         if (delalloc_end < delalloc_start)
7073                 delalloc_end = (u64)-1;
7074
7075         /*
7076          * We didn't find anything useful, return the original results from
7077          * get_extent()
7078          */
7079         if (delalloc_start > end || delalloc_end <= start) {
7080                 em = hole_em;
7081                 hole_em = NULL;
7082                 goto out;
7083         }
7084
7085         /*
7086          * Adjust the delalloc_start to make sure it doesn't go backwards from
7087          * the start they passed in
7088          */
7089         delalloc_start = max(start, delalloc_start);
7090         delalloc_len = delalloc_end - delalloc_start;
7091
7092         if (delalloc_len > 0) {
7093                 u64 hole_start;
7094                 u64 hole_len;
7095                 const u64 hole_end = extent_map_end(hole_em);
7096
7097                 em = alloc_extent_map();
7098                 if (!em) {
7099                         err = -ENOMEM;
7100                         goto out;
7101                 }
7102
7103                 ASSERT(hole_em);
7104                 /*
7105                  * When btrfs_get_extent can't find anything it returns one
7106                  * huge hole
7107                  *
7108                  * Make sure what it found really fits our range, and adjust to
7109                  * make sure it is based on the start from the caller
7110                  */
7111                 if (hole_end <= start || hole_em->start > end) {
7112                        free_extent_map(hole_em);
7113                        hole_em = NULL;
7114                 } else {
7115                        hole_start = max(hole_em->start, start);
7116                        hole_len = hole_end - hole_start;
7117                 }
7118
7119                 if (hole_em && delalloc_start > hole_start) {
7120                         /*
7121                          * Our hole starts before our delalloc, so we have to
7122                          * return just the parts of the hole that go until the
7123                          * delalloc starts
7124                          */
7125                         em->len = min(hole_len, delalloc_start - hole_start);
7126                         em->start = hole_start;
7127                         em->orig_start = hole_start;
7128                         /*
7129                          * Don't adjust block start at all, it is fixed at
7130                          * EXTENT_MAP_HOLE
7131                          */
7132                         em->block_start = hole_em->block_start;
7133                         em->block_len = hole_len;
7134                         if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7135                                 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7136                 } else {
7137                         /*
7138                          * Hole is out of passed range or it starts after
7139                          * delalloc range
7140                          */
7141                         em->start = delalloc_start;
7142                         em->len = delalloc_len;
7143                         em->orig_start = delalloc_start;
7144                         em->block_start = EXTENT_MAP_DELALLOC;
7145                         em->block_len = delalloc_len;
7146                 }
7147         } else {
7148                 return hole_em;
7149         }
7150 out:
7151
7152         free_extent_map(hole_em);
7153         if (err) {
7154                 free_extent_map(em);
7155                 return ERR_PTR(err);
7156         }
7157         return em;
7158 }
7159
7160 static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,
7161                                                   const u64 start,
7162                                                   const u64 len,
7163                                                   const u64 orig_start,
7164                                                   const u64 block_start,
7165                                                   const u64 block_len,
7166                                                   const u64 orig_block_len,
7167                                                   const u64 ram_bytes,
7168                                                   const int type)
7169 {
7170         struct extent_map *em = NULL;
7171         int ret;
7172
7173         if (type != BTRFS_ORDERED_NOCOW) {
7174                 em = create_io_em(inode, start, len, orig_start, block_start,
7175                                   block_len, orig_block_len, ram_bytes,
7176                                   BTRFS_COMPRESS_NONE, /* compress_type */
7177                                   type);
7178                 if (IS_ERR(em))
7179                         goto out;
7180         }
7181         ret = btrfs_add_ordered_extent_dio(inode, start, block_start, len,
7182                                            block_len, type);
7183         if (ret) {
7184                 if (em) {
7185                         free_extent_map(em);
7186                         btrfs_drop_extent_cache(inode, start, start + len - 1, 0);
7187                 }
7188                 em = ERR_PTR(ret);
7189         }
7190  out:
7191
7192         return em;
7193 }
7194
7195 static struct extent_map *btrfs_new_extent_direct(struct btrfs_inode *inode,
7196                                                   u64 start, u64 len)
7197 {
7198         struct btrfs_root *root = inode->root;
7199         struct btrfs_fs_info *fs_info = root->fs_info;
7200         struct extent_map *em;
7201         struct btrfs_key ins;
7202         u64 alloc_hint;
7203         int ret;
7204
7205         alloc_hint = get_extent_allocation_hint(inode, start, len);
7206         ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7207                                    0, alloc_hint, &ins, 1, 1);
7208         if (ret)
7209                 return ERR_PTR(ret);
7210
7211         em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7212                                      ins.objectid, ins.offset, ins.offset,
7213                                      ins.offset, BTRFS_ORDERED_REGULAR);
7214         btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7215         if (IS_ERR(em))
7216                 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset,
7217                                            1);
7218
7219         return em;
7220 }
7221
7222 /*
7223  * Check if we can do nocow write into the range [@offset, @offset + @len)
7224  *
7225  * @offset:     File offset
7226  * @len:        The length to write, will be updated to the nocow writeable
7227  *              range
7228  * @orig_start: (optional) Return the original file offset of the file extent
7229  * @orig_len:   (optional) Return the original on-disk length of the file extent
7230  * @ram_bytes:  (optional) Return the ram_bytes of the file extent
7231  * @strict:     if true, omit optimizations that might force us into unnecessary
7232  *              cow. e.g., don't trust generation number.
7233  *
7234  * Return:
7235  * >0   and update @len if we can do nocow write
7236  *  0   if we can't do nocow write
7237  * <0   if error happened
7238  *
7239  * NOTE: This only checks the file extents, caller is responsible to wait for
7240  *       any ordered extents.
7241  */
7242 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7243                               u64 *orig_start, u64 *orig_block_len,
7244                               u64 *ram_bytes, bool strict)
7245 {
7246         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7247         struct btrfs_path *path;
7248         int ret;
7249         struct extent_buffer *leaf;
7250         struct btrfs_root *root = BTRFS_I(inode)->root;
7251         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7252         struct btrfs_file_extent_item *fi;
7253         struct btrfs_key key;
7254         u64 disk_bytenr;
7255         u64 backref_offset;
7256         u64 extent_end;
7257         u64 num_bytes;
7258         int slot;
7259         int found_type;
7260         bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7261
7262         path = btrfs_alloc_path();
7263         if (!path)
7264                 return -ENOMEM;
7265
7266         ret = btrfs_lookup_file_extent(NULL, root, path,
7267                         btrfs_ino(BTRFS_I(inode)), offset, 0);
7268         if (ret < 0)
7269                 goto out;
7270
7271         slot = path->slots[0];
7272         if (ret == 1) {
7273                 if (slot == 0) {
7274                         /* can't find the item, must cow */
7275                         ret = 0;
7276                         goto out;
7277                 }
7278                 slot--;
7279         }
7280         ret = 0;
7281         leaf = path->nodes[0];
7282         btrfs_item_key_to_cpu(leaf, &key, slot);
7283         if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7284             key.type != BTRFS_EXTENT_DATA_KEY) {
7285                 /* not our file or wrong item type, must cow */
7286                 goto out;
7287         }
7288
7289         if (key.offset > offset) {
7290                 /* Wrong offset, must cow */
7291                 goto out;
7292         }
7293
7294         fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7295         found_type = btrfs_file_extent_type(leaf, fi);
7296         if (found_type != BTRFS_FILE_EXTENT_REG &&
7297             found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7298                 /* not a regular extent, must cow */
7299                 goto out;
7300         }
7301
7302         if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7303                 goto out;
7304
7305         extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7306         if (extent_end <= offset)
7307                 goto out;
7308
7309         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7310         if (disk_bytenr == 0)
7311                 goto out;
7312
7313         if (btrfs_file_extent_compression(leaf, fi) ||
7314             btrfs_file_extent_encryption(leaf, fi) ||
7315             btrfs_file_extent_other_encoding(leaf, fi))
7316                 goto out;
7317
7318         /*
7319          * Do the same check as in btrfs_cross_ref_exist but without the
7320          * unnecessary search.
7321          */
7322         if (!strict &&
7323             (btrfs_file_extent_generation(leaf, fi) <=
7324              btrfs_root_last_snapshot(&root->root_item)))
7325                 goto out;
7326
7327         backref_offset = btrfs_file_extent_offset(leaf, fi);
7328
7329         if (orig_start) {
7330                 *orig_start = key.offset - backref_offset;
7331                 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7332                 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7333         }
7334
7335         if (btrfs_extent_readonly(fs_info, disk_bytenr))
7336                 goto out;
7337
7338         num_bytes = min(offset + *len, extent_end) - offset;
7339         if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7340                 u64 range_end;
7341
7342                 range_end = round_up(offset + num_bytes,
7343                                      root->fs_info->sectorsize) - 1;
7344                 ret = test_range_bit(io_tree, offset, range_end,
7345                                      EXTENT_DELALLOC, 0, NULL);
7346                 if (ret) {
7347                         ret = -EAGAIN;
7348                         goto out;
7349                 }
7350         }
7351
7352         btrfs_release_path(path);
7353
7354         /*
7355          * look for other files referencing this extent, if we
7356          * find any we must cow
7357          */
7358
7359         ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7360                                     key.offset - backref_offset, disk_bytenr,
7361                                     strict);
7362         if (ret) {
7363                 ret = 0;
7364                 goto out;
7365         }
7366
7367         /*
7368          * adjust disk_bytenr and num_bytes to cover just the bytes
7369          * in this extent we are about to write.  If there
7370          * are any csums in that range we have to cow in order
7371          * to keep the csums correct
7372          */
7373         disk_bytenr += backref_offset;
7374         disk_bytenr += offset - key.offset;
7375         if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7376                 goto out;
7377         /*
7378          * all of the above have passed, it is safe to overwrite this extent
7379          * without cow
7380          */
7381         *len = num_bytes;
7382         ret = 1;
7383 out:
7384         btrfs_free_path(path);
7385         return ret;
7386 }
7387
7388 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7389                               struct extent_state **cached_state, bool writing)
7390 {
7391         struct btrfs_ordered_extent *ordered;
7392         int ret = 0;
7393
7394         while (1) {
7395                 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7396                                  cached_state);
7397                 /*
7398                  * We're concerned with the entire range that we're going to be
7399                  * doing DIO to, so we need to make sure there's no ordered
7400                  * extents in this range.
7401                  */
7402                 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7403                                                      lockend - lockstart + 1);
7404
7405                 /*
7406                  * We need to make sure there are no buffered pages in this
7407                  * range either, we could have raced between the invalidate in
7408                  * generic_file_direct_write and locking the extent.  The
7409                  * invalidate needs to happen so that reads after a write do not
7410                  * get stale data.
7411                  */
7412                 if (!ordered &&
7413                     (!writing || !filemap_range_has_page(inode->i_mapping,
7414                                                          lockstart, lockend)))
7415                         break;
7416
7417                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7418                                      cached_state);
7419
7420                 if (ordered) {
7421                         /*
7422                          * If we are doing a DIO read and the ordered extent we
7423                          * found is for a buffered write, we can not wait for it
7424                          * to complete and retry, because if we do so we can
7425                          * deadlock with concurrent buffered writes on page
7426                          * locks. This happens only if our DIO read covers more
7427                          * than one extent map, if at this point has already
7428                          * created an ordered extent for a previous extent map
7429                          * and locked its range in the inode's io tree, and a
7430                          * concurrent write against that previous extent map's
7431                          * range and this range started (we unlock the ranges
7432                          * in the io tree only when the bios complete and
7433                          * buffered writes always lock pages before attempting
7434                          * to lock range in the io tree).
7435                          */
7436                         if (writing ||
7437                             test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7438                                 btrfs_start_ordered_extent(ordered, 1);
7439                         else
7440                                 ret = -ENOTBLK;
7441                         btrfs_put_ordered_extent(ordered);
7442                 } else {
7443                         /*
7444                          * We could trigger writeback for this range (and wait
7445                          * for it to complete) and then invalidate the pages for
7446                          * this range (through invalidate_inode_pages2_range()),
7447                          * but that can lead us to a deadlock with a concurrent
7448                          * call to readahead (a buffered read or a defrag call
7449                          * triggered a readahead) on a page lock due to an
7450                          * ordered dio extent we created before but did not have
7451                          * yet a corresponding bio submitted (whence it can not
7452                          * complete), which makes readahead wait for that
7453                          * ordered extent to complete while holding a lock on
7454                          * that page.
7455                          */
7456                         ret = -ENOTBLK;
7457                 }
7458
7459                 if (ret)
7460                         break;
7461
7462                 cond_resched();
7463         }
7464
7465         return ret;
7466 }
7467
7468 /* The callers of this must take lock_extent() */
7469 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
7470                                        u64 len, u64 orig_start, u64 block_start,
7471                                        u64 block_len, u64 orig_block_len,
7472                                        u64 ram_bytes, int compress_type,
7473                                        int type)
7474 {
7475         struct extent_map_tree *em_tree;
7476         struct extent_map *em;
7477         int ret;
7478
7479         ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7480                type == BTRFS_ORDERED_COMPRESSED ||
7481                type == BTRFS_ORDERED_NOCOW ||
7482                type == BTRFS_ORDERED_REGULAR);
7483
7484         em_tree = &inode->extent_tree;
7485         em = alloc_extent_map();
7486         if (!em)
7487                 return ERR_PTR(-ENOMEM);
7488
7489         em->start = start;
7490         em->orig_start = orig_start;
7491         em->len = len;
7492         em->block_len = block_len;
7493         em->block_start = block_start;
7494         em->orig_block_len = orig_block_len;
7495         em->ram_bytes = ram_bytes;
7496         em->generation = -1;
7497         set_bit(EXTENT_FLAG_PINNED, &em->flags);
7498         if (type == BTRFS_ORDERED_PREALLOC) {
7499                 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7500         } else if (type == BTRFS_ORDERED_COMPRESSED) {
7501                 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7502                 em->compress_type = compress_type;
7503         }
7504
7505         do {
7506                 btrfs_drop_extent_cache(inode, em->start,
7507                                         em->start + em->len - 1, 0);
7508                 write_lock(&em_tree->lock);
7509                 ret = add_extent_mapping(em_tree, em, 1);
7510                 write_unlock(&em_tree->lock);
7511                 /*
7512                  * The caller has taken lock_extent(), who could race with us
7513                  * to add em?
7514                  */
7515         } while (ret == -EEXIST);
7516
7517         if (ret) {
7518                 free_extent_map(em);
7519                 return ERR_PTR(ret);
7520         }
7521
7522         /* em got 2 refs now, callers needs to do free_extent_map once. */
7523         return em;
7524 }
7525
7526
7527 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7528                                          struct inode *inode,
7529                                          struct btrfs_dio_data *dio_data,
7530                                          u64 start, u64 len)
7531 {
7532         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7533         struct extent_map *em = *map;
7534         int ret = 0;
7535
7536         /*
7537          * We don't allocate a new extent in the following cases
7538          *
7539          * 1) The inode is marked as NODATACOW. In this case we'll just use the
7540          * existing extent.
7541          * 2) The extent is marked as PREALLOC. We're good to go here and can
7542          * just use the extent.
7543          *
7544          */
7545         if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7546             ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7547              em->block_start != EXTENT_MAP_HOLE)) {
7548                 int type;
7549                 u64 block_start, orig_start, orig_block_len, ram_bytes;
7550
7551                 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7552                         type = BTRFS_ORDERED_PREALLOC;
7553                 else
7554                         type = BTRFS_ORDERED_NOCOW;
7555                 len = min(len, em->len - (start - em->start));
7556                 block_start = em->block_start + (start - em->start);
7557
7558                 if (can_nocow_extent(inode, start, &len, &orig_start,
7559                                      &orig_block_len, &ram_bytes, false) == 1 &&
7560                     btrfs_inc_nocow_writers(fs_info, block_start)) {
7561                         struct extent_map *em2;
7562
7563                         em2 = btrfs_create_dio_extent(BTRFS_I(inode), start, len,
7564                                                       orig_start, block_start,
7565                                                       len, orig_block_len,
7566                                                       ram_bytes, type);
7567                         btrfs_dec_nocow_writers(fs_info, block_start);
7568                         if (type == BTRFS_ORDERED_PREALLOC) {
7569                                 free_extent_map(em);
7570                                 *map = em = em2;
7571                         }
7572
7573                         if (em2 && IS_ERR(em2)) {
7574                                 ret = PTR_ERR(em2);
7575                                 goto out;
7576                         }
7577                         /*
7578                          * For inode marked NODATACOW or extent marked PREALLOC,
7579                          * use the existing or preallocated extent, so does not
7580                          * need to adjust btrfs_space_info's bytes_may_use.
7581                          */
7582                         btrfs_free_reserved_data_space_noquota(fs_info, len);
7583                         goto skip_cow;
7584                 }
7585         }
7586
7587         /* this will cow the extent */
7588         free_extent_map(em);
7589         *map = em = btrfs_new_extent_direct(BTRFS_I(inode), start, len);
7590         if (IS_ERR(em)) {
7591                 ret = PTR_ERR(em);
7592                 goto out;
7593         }
7594
7595         len = min(len, em->len - (start - em->start));
7596
7597 skip_cow:
7598         /*
7599          * Need to update the i_size under the extent lock so buffered
7600          * readers will get the updated i_size when we unlock.
7601          */
7602         if (start + len > i_size_read(inode))
7603                 i_size_write(inode, start + len);
7604
7605         dio_data->reserve -= len;
7606 out:
7607         return ret;
7608 }
7609
7610 static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start,
7611                 loff_t length, unsigned int flags, struct iomap *iomap,
7612                 struct iomap *srcmap)
7613 {
7614         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7615         struct extent_map *em;
7616         struct extent_state *cached_state = NULL;
7617         struct btrfs_dio_data *dio_data = NULL;
7618         u64 lockstart, lockend;
7619         const bool write = !!(flags & IOMAP_WRITE);
7620         int ret = 0;
7621         u64 len = length;
7622         bool unlock_extents = false;
7623
7624         if (!write)
7625                 len = min_t(u64, len, fs_info->sectorsize);
7626
7627         lockstart = start;
7628         lockend = start + len - 1;
7629
7630         /*
7631          * The generic stuff only does filemap_write_and_wait_range, which
7632          * isn't enough if we've written compressed pages to this area, so we
7633          * need to flush the dirty pages again to make absolutely sure that any
7634          * outstanding dirty pages are on disk.
7635          */
7636         if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7637                      &BTRFS_I(inode)->runtime_flags)) {
7638                 ret = filemap_fdatawrite_range(inode->i_mapping, start,
7639                                                start + length - 1);
7640                 if (ret)
7641                         return ret;
7642         }
7643
7644         dio_data = kzalloc(sizeof(*dio_data), GFP_NOFS);
7645         if (!dio_data)
7646                 return -ENOMEM;
7647
7648         dio_data->length = length;
7649         if (write) {
7650                 dio_data->reserve = round_up(length, fs_info->sectorsize);
7651                 ret = btrfs_delalloc_reserve_space(BTRFS_I(inode),
7652                                 &dio_data->data_reserved,
7653                                 start, dio_data->reserve);
7654                 if (ret) {
7655                         extent_changeset_free(dio_data->data_reserved);
7656                         kfree(dio_data);
7657                         return ret;
7658                 }
7659         }
7660         iomap->private = dio_data;
7661
7662
7663         /*
7664          * If this errors out it's because we couldn't invalidate pagecache for
7665          * this range and we need to fallback to buffered.
7666          */
7667         if (lock_extent_direct(inode, lockstart, lockend, &cached_state, write)) {
7668                 ret = -ENOTBLK;
7669                 goto err;
7670         }
7671
7672         em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
7673         if (IS_ERR(em)) {
7674                 ret = PTR_ERR(em);
7675                 goto unlock_err;
7676         }
7677
7678         /*
7679          * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7680          * io.  INLINE is special, and we could probably kludge it in here, but
7681          * it's still buffered so for safety lets just fall back to the generic
7682          * buffered path.
7683          *
7684          * For COMPRESSED we _have_ to read the entire extent in so we can
7685          * decompress it, so there will be buffering required no matter what we
7686          * do, so go ahead and fallback to buffered.
7687          *
7688          * We return -ENOTBLK because that's what makes DIO go ahead and go back
7689          * to buffered IO.  Don't blame me, this is the price we pay for using
7690          * the generic code.
7691          */
7692         if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7693             em->block_start == EXTENT_MAP_INLINE) {
7694                 free_extent_map(em);
7695                 ret = -ENOTBLK;
7696                 goto unlock_err;
7697         }
7698
7699         len = min(len, em->len - (start - em->start));
7700         if (write) {
7701                 ret = btrfs_get_blocks_direct_write(&em, inode, dio_data,
7702                                                     start, len);
7703                 if (ret < 0)
7704                         goto unlock_err;
7705                 unlock_extents = true;
7706                 /* Recalc len in case the new em is smaller than requested */
7707                 len = min(len, em->len - (start - em->start));
7708         } else {
7709                 /*
7710                  * We need to unlock only the end area that we aren't using.
7711                  * The rest is going to be unlocked by the endio routine.
7712                  */
7713                 lockstart = start + len;
7714                 if (lockstart < lockend)
7715                         unlock_extents = true;
7716         }
7717
7718         if (unlock_extents)
7719                 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
7720                                      lockstart, lockend, &cached_state);
7721         else
7722                 free_extent_state(cached_state);
7723
7724         /*
7725          * Translate extent map information to iomap.
7726          * We trim the extents (and move the addr) even though iomap code does
7727          * that, since we have locked only the parts we are performing I/O in.
7728          */
7729         if ((em->block_start == EXTENT_MAP_HOLE) ||
7730             (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) && !write)) {
7731                 iomap->addr = IOMAP_NULL_ADDR;
7732                 iomap->type = IOMAP_HOLE;
7733         } else {
7734                 iomap->addr = em->block_start + (start - em->start);
7735                 iomap->type = IOMAP_MAPPED;
7736         }
7737         iomap->offset = start;
7738         iomap->bdev = fs_info->fs_devices->latest_bdev;
7739         iomap->length = len;
7740
7741         free_extent_map(em);
7742
7743         return 0;
7744
7745 unlock_err:
7746         unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7747                              &cached_state);
7748 err:
7749         if (dio_data) {
7750                 btrfs_delalloc_release_space(BTRFS_I(inode),
7751                                 dio_data->data_reserved, start,
7752                                 dio_data->reserve, true);
7753                 btrfs_delalloc_release_extents(BTRFS_I(inode), dio_data->reserve);
7754                 extent_changeset_free(dio_data->data_reserved);
7755                 kfree(dio_data);
7756         }
7757         return ret;
7758 }
7759
7760 static int btrfs_dio_iomap_end(struct inode *inode, loff_t pos, loff_t length,
7761                 ssize_t written, unsigned int flags, struct iomap *iomap)
7762 {
7763         int ret = 0;
7764         struct btrfs_dio_data *dio_data = iomap->private;
7765         size_t submitted = dio_data->submitted;
7766         const bool write = !!(flags & IOMAP_WRITE);
7767
7768         if (!write && (iomap->type == IOMAP_HOLE)) {
7769                 /* If reading from a hole, unlock and return */
7770                 unlock_extent(&BTRFS_I(inode)->io_tree, pos, pos + length - 1);
7771                 goto out;
7772         }
7773
7774         if (submitted < length) {
7775                 pos += submitted;
7776                 length -= submitted;
7777                 if (write)
7778                         __endio_write_update_ordered(BTRFS_I(inode), pos,
7779                                         length, false);
7780                 else
7781                         unlock_extent(&BTRFS_I(inode)->io_tree, pos,
7782                                       pos + length - 1);
7783                 ret = -ENOTBLK;
7784         }
7785
7786         if (write) {
7787                 if (dio_data->reserve)
7788                         btrfs_delalloc_release_space(BTRFS_I(inode),
7789                                         dio_data->data_reserved, pos,
7790                                         dio_data->reserve, true);
7791                 btrfs_delalloc_release_extents(BTRFS_I(inode), dio_data->length);
7792                 extent_changeset_free(dio_data->data_reserved);
7793         }
7794 out:
7795         kfree(dio_data);
7796         iomap->private = NULL;
7797
7798         return ret;
7799 }
7800
7801 static void btrfs_dio_private_put(struct btrfs_dio_private *dip)
7802 {
7803         /*
7804          * This implies a barrier so that stores to dio_bio->bi_status before
7805          * this and loads of dio_bio->bi_status after this are fully ordered.
7806          */
7807         if (!refcount_dec_and_test(&dip->refs))
7808                 return;
7809
7810         if (btrfs_op(dip->dio_bio) == BTRFS_MAP_WRITE) {
7811                 __endio_write_update_ordered(BTRFS_I(dip->inode),
7812                                              dip->logical_offset,
7813                                              dip->bytes,
7814                                              !dip->dio_bio->bi_status);
7815         } else {
7816                 unlock_extent(&BTRFS_I(dip->inode)->io_tree,
7817                               dip->logical_offset,
7818                               dip->logical_offset + dip->bytes - 1);
7819         }
7820
7821         bio_endio(dip->dio_bio);
7822         kfree(dip);
7823 }
7824
7825 static blk_status_t submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7826                                           int mirror_num,
7827                                           unsigned long bio_flags)
7828 {
7829         struct btrfs_dio_private *dip = bio->bi_private;
7830         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7831         blk_status_t ret;
7832
7833         BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7834
7835         ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
7836         if (ret)
7837                 return ret;
7838
7839         refcount_inc(&dip->refs);
7840         ret = btrfs_map_bio(fs_info, bio, mirror_num);
7841         if (ret)
7842                 refcount_dec(&dip->refs);
7843         return ret;
7844 }
7845
7846 static blk_status_t btrfs_check_read_dio_bio(struct inode *inode,
7847                                              struct btrfs_io_bio *io_bio,
7848                                              const bool uptodate)
7849 {
7850         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
7851         const u32 sectorsize = fs_info->sectorsize;
7852         struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7853         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7854         const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7855         struct bio_vec bvec;
7856         struct bvec_iter iter;
7857         u64 start = io_bio->logical;
7858         u32 bio_offset = 0;
7859         blk_status_t err = BLK_STS_OK;
7860
7861         __bio_for_each_segment(bvec, &io_bio->bio, iter, io_bio->iter) {
7862                 unsigned int i, nr_sectors, pgoff;
7863
7864                 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7865                 pgoff = bvec.bv_offset;
7866                 for (i = 0; i < nr_sectors; i++) {
7867                         ASSERT(pgoff < PAGE_SIZE);
7868                         if (uptodate &&
7869                             (!csum || !check_data_csum(inode, io_bio,
7870                                         bio_offset, bvec.bv_page, pgoff))) {
7871                                 clean_io_failure(fs_info, failure_tree, io_tree,
7872                                                  start, bvec.bv_page,
7873                                                  btrfs_ino(BTRFS_I(inode)),
7874                                                  pgoff);
7875                         } else {
7876                                 blk_status_t status;
7877
7878                                 ASSERT((start - io_bio->logical) < UINT_MAX);
7879                                 status = btrfs_submit_read_repair(inode,
7880                                                         &io_bio->bio,
7881                                                         start - io_bio->logical,
7882                                                         bvec.bv_page, pgoff,
7883                                                         start,
7884                                                         start + sectorsize - 1,
7885                                                         io_bio->mirror_num,
7886                                                         submit_dio_repair_bio);
7887                                 if (status)
7888                                         err = status;
7889                         }
7890                         start += sectorsize;
7891                         ASSERT(bio_offset + sectorsize > bio_offset);
7892                         bio_offset += sectorsize;
7893                         pgoff += sectorsize;
7894                 }
7895         }
7896         return err;
7897 }
7898
7899 static void __endio_write_update_ordered(struct btrfs_inode *inode,
7900                                          const u64 offset, const u64 bytes,
7901                                          const bool uptodate)
7902 {
7903         struct btrfs_fs_info *fs_info = inode->root->fs_info;
7904         struct btrfs_ordered_extent *ordered = NULL;
7905         struct btrfs_workqueue *wq;
7906         u64 ordered_offset = offset;
7907         u64 ordered_bytes = bytes;
7908         u64 last_offset;
7909
7910         if (btrfs_is_free_space_inode(inode))
7911                 wq = fs_info->endio_freespace_worker;
7912         else
7913                 wq = fs_info->endio_write_workers;
7914
7915         while (ordered_offset < offset + bytes) {
7916                 last_offset = ordered_offset;
7917                 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
7918                                                          &ordered_offset,
7919                                                          ordered_bytes,
7920                                                          uptodate)) {
7921                         btrfs_init_work(&ordered->work, finish_ordered_fn, NULL,
7922                                         NULL);
7923                         btrfs_queue_work(wq, &ordered->work);
7924                 }
7925
7926                 /* No ordered extent found in the range, exit */
7927                 if (ordered_offset == last_offset)
7928                         return;
7929                 /*
7930                  * Our bio might span multiple ordered extents. In this case
7931                  * we keep going until we have accounted the whole dio.
7932                  */
7933                 if (ordered_offset < offset + bytes) {
7934                         ordered_bytes = offset + bytes - ordered_offset;
7935                         ordered = NULL;
7936                 }
7937         }
7938 }
7939
7940 static blk_status_t btrfs_submit_bio_start_direct_io(struct inode *inode,
7941                                                      struct bio *bio,
7942                                                      u64 dio_file_offset)
7943 {
7944         return btrfs_csum_one_bio(BTRFS_I(inode), bio, dio_file_offset, 1);
7945 }
7946
7947 static void btrfs_end_dio_bio(struct bio *bio)
7948 {
7949         struct btrfs_dio_private *dip = bio->bi_private;
7950         blk_status_t err = bio->bi_status;
7951
7952         if (err)
7953                 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
7954                            "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
7955                            btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
7956                            bio->bi_opf, bio->bi_iter.bi_sector,
7957                            bio->bi_iter.bi_size, err);
7958
7959         if (bio_op(bio) == REQ_OP_READ) {
7960                 err = btrfs_check_read_dio_bio(dip->inode, btrfs_io_bio(bio),
7961                                                !err);
7962         }
7963
7964         if (err)
7965                 dip->dio_bio->bi_status = err;
7966
7967         bio_put(bio);
7968         btrfs_dio_private_put(dip);
7969 }
7970
7971 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
7972                 struct inode *inode, u64 file_offset, int async_submit)
7973 {
7974         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7975         struct btrfs_dio_private *dip = bio->bi_private;
7976         bool write = btrfs_op(bio) == BTRFS_MAP_WRITE;
7977         blk_status_t ret;
7978
7979         /* Check btrfs_submit_bio_hook() for rules about async submit. */
7980         if (async_submit)
7981                 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7982
7983         if (!write) {
7984                 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
7985                 if (ret)
7986                         goto err;
7987         }
7988
7989         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
7990                 goto map;
7991
7992         if (write && async_submit) {
7993                 ret = btrfs_wq_submit_bio(inode, bio, 0, 0, file_offset,
7994                                           btrfs_submit_bio_start_direct_io);
7995                 goto err;
7996         } else if (write) {
7997                 /*
7998                  * If we aren't doing async submit, calculate the csum of the
7999                  * bio now.
8000                  */
8001                 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, file_offset, 1);
8002                 if (ret)
8003                         goto err;
8004         } else {
8005                 u64 csum_offset;
8006
8007                 csum_offset = file_offset - dip->logical_offset;
8008                 csum_offset >>= fs_info->sectorsize_bits;
8009                 csum_offset *= fs_info->csum_size;
8010                 btrfs_io_bio(bio)->csum = dip->csums + csum_offset;
8011         }
8012 map:
8013         ret = btrfs_map_bio(fs_info, bio, 0);
8014 err:
8015         return ret;
8016 }
8017
8018 /*
8019  * If this succeeds, the btrfs_dio_private is responsible for cleaning up locked
8020  * or ordered extents whether or not we submit any bios.
8021  */
8022 static struct btrfs_dio_private *btrfs_create_dio_private(struct bio *dio_bio,
8023                                                           struct inode *inode,
8024                                                           loff_t file_offset)
8025 {
8026         const bool write = (btrfs_op(dio_bio) == BTRFS_MAP_WRITE);
8027         const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
8028         size_t dip_size;
8029         struct btrfs_dio_private *dip;
8030
8031         dip_size = sizeof(*dip);
8032         if (!write && csum) {
8033                 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8034                 size_t nblocks;
8035
8036                 nblocks = dio_bio->bi_iter.bi_size >> fs_info->sectorsize_bits;
8037                 dip_size += fs_info->csum_size * nblocks;
8038         }
8039
8040         dip = kzalloc(dip_size, GFP_NOFS);
8041         if (!dip)
8042                 return NULL;
8043
8044         dip->inode = inode;
8045         dip->logical_offset = file_offset;
8046         dip->bytes = dio_bio->bi_iter.bi_size;
8047         dip->disk_bytenr = dio_bio->bi_iter.bi_sector << 9;
8048         dip->dio_bio = dio_bio;
8049         refcount_set(&dip->refs, 1);
8050         return dip;
8051 }
8052
8053 static blk_qc_t btrfs_submit_direct(struct inode *inode, struct iomap *iomap,
8054                 struct bio *dio_bio, loff_t file_offset)
8055 {
8056         const bool write = (btrfs_op(dio_bio) == BTRFS_MAP_WRITE);
8057         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8058         const bool raid56 = (btrfs_data_alloc_profile(fs_info) &
8059                              BTRFS_BLOCK_GROUP_RAID56_MASK);
8060         struct btrfs_dio_private *dip;
8061         struct bio *bio;
8062         u64 start_sector;
8063         int async_submit = 0;
8064         u64 submit_len;
8065         int clone_offset = 0;
8066         int clone_len;
8067         u64 logical;
8068         int ret;
8069         blk_status_t status;
8070         struct btrfs_io_geometry geom;
8071         struct btrfs_dio_data *dio_data = iomap->private;
8072         struct extent_map *em = NULL;
8073
8074         dip = btrfs_create_dio_private(dio_bio, inode, file_offset);
8075         if (!dip) {
8076                 if (!write) {
8077                         unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8078                                 file_offset + dio_bio->bi_iter.bi_size - 1);
8079                 }
8080                 dio_bio->bi_status = BLK_STS_RESOURCE;
8081                 bio_endio(dio_bio);
8082                 return BLK_QC_T_NONE;
8083         }
8084
8085         if (!write) {
8086                 /*
8087                  * Load the csums up front to reduce csum tree searches and
8088                  * contention when submitting bios.
8089                  *
8090                  * If we have csums disabled this will do nothing.
8091                  */
8092                 status = btrfs_lookup_bio_sums(inode, dio_bio, dip->csums);
8093                 if (status != BLK_STS_OK)
8094                         goto out_err;
8095         }
8096
8097         start_sector = dio_bio->bi_iter.bi_sector;
8098         submit_len = dio_bio->bi_iter.bi_size;
8099
8100         do {
8101                 logical = start_sector << 9;
8102                 em = btrfs_get_chunk_map(fs_info, logical, submit_len);
8103                 if (IS_ERR(em)) {
8104                         status = errno_to_blk_status(PTR_ERR(em));
8105                         em = NULL;
8106                         goto out_err_em;
8107                 }
8108                 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(dio_bio),
8109                                             logical, submit_len, &geom);
8110                 if (ret) {
8111                         status = errno_to_blk_status(ret);
8112                         goto out_err_em;
8113                 }
8114                 ASSERT(geom.len <= INT_MAX);
8115
8116                 clone_len = min_t(int, submit_len, geom.len);
8117
8118                 /*
8119                  * This will never fail as it's passing GPF_NOFS and
8120                  * the allocation is backed by btrfs_bioset.
8121                  */
8122                 bio = btrfs_bio_clone_partial(dio_bio, clone_offset, clone_len);
8123                 bio->bi_private = dip;
8124                 bio->bi_end_io = btrfs_end_dio_bio;
8125                 btrfs_io_bio(bio)->logical = file_offset;
8126
8127                 ASSERT(submit_len >= clone_len);
8128                 submit_len -= clone_len;
8129
8130                 /*
8131                  * Increase the count before we submit the bio so we know
8132                  * the end IO handler won't happen before we increase the
8133                  * count. Otherwise, the dip might get freed before we're
8134                  * done setting it up.
8135                  *
8136                  * We transfer the initial reference to the last bio, so we
8137                  * don't need to increment the reference count for the last one.
8138                  */
8139                 if (submit_len > 0) {
8140                         refcount_inc(&dip->refs);
8141                         /*
8142                          * If we are submitting more than one bio, submit them
8143                          * all asynchronously. The exception is RAID 5 or 6, as
8144                          * asynchronous checksums make it difficult to collect
8145                          * full stripe writes.
8146                          */
8147                         if (!raid56)
8148                                 async_submit = 1;
8149                 }
8150
8151                 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8152                                                 async_submit);
8153                 if (status) {
8154                         bio_put(bio);
8155                         if (submit_len > 0)
8156                                 refcount_dec(&dip->refs);
8157                         goto out_err_em;
8158                 }
8159
8160                 dio_data->submitted += clone_len;
8161                 clone_offset += clone_len;
8162                 start_sector += clone_len >> 9;
8163                 file_offset += clone_len;
8164
8165                 free_extent_map(em);
8166         } while (submit_len > 0);
8167         return BLK_QC_T_NONE;
8168
8169 out_err_em:
8170         free_extent_map(em);
8171 out_err:
8172         dip->dio_bio->bi_status = status;
8173         btrfs_dio_private_put(dip);
8174
8175         return BLK_QC_T_NONE;
8176 }
8177
8178 const struct iomap_ops btrfs_dio_iomap_ops = {
8179         .iomap_begin            = btrfs_dio_iomap_begin,
8180         .iomap_end              = btrfs_dio_iomap_end,
8181 };
8182
8183 const struct iomap_dio_ops btrfs_dio_ops = {
8184         .submit_io              = btrfs_submit_direct,
8185 };
8186
8187 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8188                         u64 start, u64 len)
8189 {
8190         int     ret;
8191
8192         ret = fiemap_prep(inode, fieinfo, start, &len, 0);
8193         if (ret)
8194                 return ret;
8195
8196         return extent_fiemap(BTRFS_I(inode), fieinfo, start, len);
8197 }
8198
8199 int btrfs_readpage(struct file *file, struct page *page)
8200 {
8201         struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
8202         u64 start = page_offset(page);
8203         u64 end = start + PAGE_SIZE - 1;
8204         unsigned long bio_flags = 0;
8205         struct bio *bio = NULL;
8206         int ret;
8207
8208         btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
8209
8210         ret = btrfs_do_readpage(page, NULL, &bio, &bio_flags, 0, NULL);
8211         if (bio)
8212                 ret = submit_one_bio(bio, 0, bio_flags);
8213         return ret;
8214 }
8215
8216 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8217 {
8218         struct inode *inode = page->mapping->host;
8219         int ret;
8220
8221         if (current->flags & PF_MEMALLOC) {
8222                 redirty_page_for_writepage(wbc, page);
8223                 unlock_page(page);
8224                 return 0;
8225         }
8226
8227         /*
8228          * If we are under memory pressure we will call this directly from the
8229          * VM, we need to make sure we have the inode referenced for the ordered
8230          * extent.  If not just return like we didn't do anything.
8231          */
8232         if (!igrab(inode)) {
8233                 redirty_page_for_writepage(wbc, page);
8234                 return AOP_WRITEPAGE_ACTIVATE;
8235         }
8236         ret = extent_write_full_page(page, wbc);
8237         btrfs_add_delayed_iput(inode);
8238         return ret;
8239 }
8240
8241 static int btrfs_writepages(struct address_space *mapping,
8242                             struct writeback_control *wbc)
8243 {
8244         return extent_writepages(mapping, wbc);
8245 }
8246
8247 static void btrfs_readahead(struct readahead_control *rac)
8248 {
8249         extent_readahead(rac);
8250 }
8251
8252 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8253 {
8254         int ret = try_release_extent_mapping(page, gfp_flags);
8255         if (ret == 1)
8256                 clear_page_extent_mapped(page);
8257         return ret;
8258 }
8259
8260 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8261 {
8262         if (PageWriteback(page) || PageDirty(page))
8263                 return 0;
8264         return __btrfs_releasepage(page, gfp_flags);
8265 }
8266
8267 #ifdef CONFIG_MIGRATION
8268 static int btrfs_migratepage(struct address_space *mapping,
8269                              struct page *newpage, struct page *page,
8270                              enum migrate_mode mode)
8271 {
8272         int ret;
8273
8274         ret = migrate_page_move_mapping(mapping, newpage, page, 0);
8275         if (ret != MIGRATEPAGE_SUCCESS)
8276                 return ret;
8277
8278         if (page_has_private(page))
8279                 attach_page_private(newpage, detach_page_private(page));
8280
8281         if (PagePrivate2(page)) {
8282                 ClearPagePrivate2(page);
8283                 SetPagePrivate2(newpage);
8284         }
8285
8286         if (mode != MIGRATE_SYNC_NO_COPY)
8287                 migrate_page_copy(newpage, page);
8288         else
8289                 migrate_page_states(newpage, page);
8290         return MIGRATEPAGE_SUCCESS;
8291 }
8292 #endif
8293
8294 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8295                                  unsigned int length)
8296 {
8297         struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
8298         struct extent_io_tree *tree = &inode->io_tree;
8299         struct btrfs_ordered_extent *ordered;
8300         struct extent_state *cached_state = NULL;
8301         u64 page_start = page_offset(page);
8302         u64 page_end = page_start + PAGE_SIZE - 1;
8303         u64 start;
8304         u64 end;
8305         int inode_evicting = inode->vfs_inode.i_state & I_FREEING;
8306         bool found_ordered = false;
8307         bool completed_ordered = false;
8308
8309         /*
8310          * we have the page locked, so new writeback can't start,
8311          * and the dirty bit won't be cleared while we are here.
8312          *
8313          * Wait for IO on this page so that we can safely clear
8314          * the PagePrivate2 bit and do ordered accounting
8315          */
8316         wait_on_page_writeback(page);
8317
8318         if (offset) {
8319                 btrfs_releasepage(page, GFP_NOFS);
8320                 return;
8321         }
8322
8323         if (!inode_evicting)
8324                 lock_extent_bits(tree, page_start, page_end, &cached_state);
8325
8326         start = page_start;
8327 again:
8328         ordered = btrfs_lookup_ordered_range(inode, start, page_end - start + 1);
8329         if (ordered) {
8330                 found_ordered = true;
8331                 end = min(page_end,
8332                           ordered->file_offset + ordered->num_bytes - 1);
8333                 /*
8334                  * IO on this page will never be started, so we need to account
8335                  * for any ordered extents now. Don't clear EXTENT_DELALLOC_NEW
8336                  * here, must leave that up for the ordered extent completion.
8337                  */
8338                 if (!inode_evicting)
8339                         clear_extent_bit(tree, start, end,
8340                                          EXTENT_DELALLOC |
8341                                          EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8342                                          EXTENT_DEFRAG, 1, 0, &cached_state);
8343                 /*
8344                  * whoever cleared the private bit is responsible
8345                  * for the finish_ordered_io
8346                  */
8347                 if (TestClearPagePrivate2(page)) {
8348                         struct btrfs_ordered_inode_tree *tree;
8349                         u64 new_len;
8350
8351                         tree = &inode->ordered_tree;
8352
8353                         spin_lock_irq(&tree->lock);
8354                         set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8355                         new_len = start - ordered->file_offset;
8356                         if (new_len < ordered->truncated_len)
8357                                 ordered->truncated_len = new_len;
8358                         spin_unlock_irq(&tree->lock);
8359
8360                         if (btrfs_dec_test_ordered_pending(inode, &ordered,
8361                                                            start,
8362                                                            end - start + 1, 1)) {
8363                                 btrfs_finish_ordered_io(ordered);
8364                                 completed_ordered = true;
8365                         }
8366                 }
8367                 btrfs_put_ordered_extent(ordered);
8368                 if (!inode_evicting) {
8369                         cached_state = NULL;
8370                         lock_extent_bits(tree, start, end,
8371                                          &cached_state);
8372                 }
8373
8374                 start = end + 1;
8375                 if (start < page_end)
8376                         goto again;
8377         }
8378
8379         /*
8380          * Qgroup reserved space handler
8381          * Page here will be either
8382          * 1) Already written to disk or ordered extent already submitted
8383          *    Then its QGROUP_RESERVED bit in io_tree is already cleaned.
8384          *    Qgroup will be handled by its qgroup_record then.
8385          *    btrfs_qgroup_free_data() call will do nothing here.
8386          *
8387          * 2) Not written to disk yet
8388          *    Then btrfs_qgroup_free_data() call will clear the QGROUP_RESERVED
8389          *    bit of its io_tree, and free the qgroup reserved data space.
8390          *    Since the IO will never happen for this page.
8391          */
8392         btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8393         if (!inode_evicting) {
8394                 bool delete = true;
8395
8396                 /*
8397                  * If there's an ordered extent for this range and we have not
8398                  * finished it ourselves, we must leave EXTENT_DELALLOC_NEW set
8399                  * in the range for the ordered extent completion. We must also
8400                  * not delete the range, otherwise we would lose that bit (and
8401                  * any other bits set in the range). Make sure EXTENT_UPTODATE
8402                  * is cleared if we don't delete, otherwise it can lead to
8403                  * corruptions if the i_size is extented later.
8404                  */
8405                 if (found_ordered && !completed_ordered)
8406                         delete = false;
8407                 clear_extent_bit(tree, page_start, page_end, EXTENT_LOCKED |
8408                                  EXTENT_DELALLOC | EXTENT_UPTODATE |
8409                                  EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1,
8410                                  delete, &cached_state);
8411
8412                 __btrfs_releasepage(page, GFP_NOFS);
8413         }
8414
8415         ClearPageChecked(page);
8416         clear_page_extent_mapped(page);
8417 }
8418
8419 /*
8420  * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8421  * called from a page fault handler when a page is first dirtied. Hence we must
8422  * be careful to check for EOF conditions here. We set the page up correctly
8423  * for a written page which means we get ENOSPC checking when writing into
8424  * holes and correct delalloc and unwritten extent mapping on filesystems that
8425  * support these features.
8426  *
8427  * We are not allowed to take the i_mutex here so we have to play games to
8428  * protect against truncate races as the page could now be beyond EOF.  Because
8429  * truncate_setsize() writes the inode size before removing pages, once we have
8430  * the page lock we can determine safely if the page is beyond EOF. If it is not
8431  * beyond EOF, then the page is guaranteed safe against truncation until we
8432  * unlock the page.
8433  */
8434 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8435 {
8436         struct page *page = vmf->page;
8437         struct inode *inode = file_inode(vmf->vma->vm_file);
8438         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8439         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8440         struct btrfs_ordered_extent *ordered;
8441         struct extent_state *cached_state = NULL;
8442         struct extent_changeset *data_reserved = NULL;
8443         char *kaddr;
8444         unsigned long zero_start;
8445         loff_t size;
8446         vm_fault_t ret;
8447         int ret2;
8448         int reserved = 0;
8449         u64 reserved_space;
8450         u64 page_start;
8451         u64 page_end;
8452         u64 end;
8453
8454         reserved_space = PAGE_SIZE;
8455
8456         sb_start_pagefault(inode->i_sb);
8457         page_start = page_offset(page);
8458         page_end = page_start + PAGE_SIZE - 1;
8459         end = page_end;
8460
8461         /*
8462          * Reserving delalloc space after obtaining the page lock can lead to
8463          * deadlock. For example, if a dirty page is locked by this function
8464          * and the call to btrfs_delalloc_reserve_space() ends up triggering
8465          * dirty page write out, then the btrfs_writepage() function could
8466          * end up waiting indefinitely to get a lock on the page currently
8467          * being processed by btrfs_page_mkwrite() function.
8468          */
8469         ret2 = btrfs_delalloc_reserve_space(BTRFS_I(inode), &data_reserved,
8470                                             page_start, reserved_space);
8471         if (!ret2) {
8472                 ret2 = file_update_time(vmf->vma->vm_file);
8473                 reserved = 1;
8474         }
8475         if (ret2) {
8476                 ret = vmf_error(ret2);
8477                 if (reserved)
8478                         goto out;
8479                 goto out_noreserve;
8480         }
8481
8482         ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8483 again:
8484         lock_page(page);
8485         size = i_size_read(inode);
8486
8487         if ((page->mapping != inode->i_mapping) ||
8488             (page_start >= size)) {
8489                 /* page got truncated out from underneath us */
8490                 goto out_unlock;
8491         }
8492         wait_on_page_writeback(page);
8493
8494         lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8495         ret2 = set_page_extent_mapped(page);
8496         if (ret2 < 0) {
8497                 ret = vmf_error(ret2);
8498                 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8499                 goto out_unlock;
8500         }
8501
8502         /*
8503          * we can't set the delalloc bits if there are pending ordered
8504          * extents.  Drop our locks and wait for them to finish
8505          */
8506         ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8507                         PAGE_SIZE);
8508         if (ordered) {
8509                 unlock_extent_cached(io_tree, page_start, page_end,
8510                                      &cached_state);
8511                 unlock_page(page);
8512                 btrfs_start_ordered_extent(ordered, 1);
8513                 btrfs_put_ordered_extent(ordered);
8514                 goto again;
8515         }
8516
8517         if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8518                 reserved_space = round_up(size - page_start,
8519                                           fs_info->sectorsize);
8520                 if (reserved_space < PAGE_SIZE) {
8521                         end = page_start + reserved_space - 1;
8522                         btrfs_delalloc_release_space(BTRFS_I(inode),
8523                                         data_reserved, page_start,
8524                                         PAGE_SIZE - reserved_space, true);
8525                 }
8526         }
8527
8528         /*
8529          * page_mkwrite gets called when the page is firstly dirtied after it's
8530          * faulted in, but write(2) could also dirty a page and set delalloc
8531          * bits, thus in this case for space account reason, we still need to
8532          * clear any delalloc bits within this page range since we have to
8533          * reserve data&meta space before lock_page() (see above comments).
8534          */
8535         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8536                           EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8537                           EXTENT_DEFRAG, 0, 0, &cached_state);
8538
8539         ret2 = btrfs_set_extent_delalloc(BTRFS_I(inode), page_start, end, 0,
8540                                         &cached_state);
8541         if (ret2) {
8542                 unlock_extent_cached(io_tree, page_start, page_end,
8543                                      &cached_state);
8544                 ret = VM_FAULT_SIGBUS;
8545                 goto out_unlock;
8546         }
8547
8548         /* page is wholly or partially inside EOF */
8549         if (page_start + PAGE_SIZE > size)
8550                 zero_start = offset_in_page(size);
8551         else
8552                 zero_start = PAGE_SIZE;
8553
8554         if (zero_start != PAGE_SIZE) {
8555                 kaddr = kmap(page);
8556                 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
8557                 flush_dcache_page(page);
8558                 kunmap(page);
8559         }
8560         ClearPageChecked(page);
8561         set_page_dirty(page);
8562         SetPageUptodate(page);
8563
8564         BTRFS_I(inode)->last_trans = fs_info->generation;
8565         BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8566         BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8567
8568         unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8569
8570         btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8571         sb_end_pagefault(inode->i_sb);
8572         extent_changeset_free(data_reserved);
8573         return VM_FAULT_LOCKED;
8574
8575 out_unlock:
8576         unlock_page(page);
8577 out:
8578         btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8579         btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved, page_start,
8580                                      reserved_space, (ret != 0));
8581 out_noreserve:
8582         sb_end_pagefault(inode->i_sb);
8583         extent_changeset_free(data_reserved);
8584         return ret;
8585 }
8586
8587 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
8588 {
8589         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8590         struct btrfs_root *root = BTRFS_I(inode)->root;
8591         struct btrfs_block_rsv *rsv;
8592         int ret;
8593         struct btrfs_trans_handle *trans;
8594         u64 mask = fs_info->sectorsize - 1;
8595         u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
8596
8597         if (!skip_writeback) {
8598                 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8599                                                (u64)-1);
8600                 if (ret)
8601                         return ret;
8602         }
8603
8604         /*
8605          * Yes ladies and gentlemen, this is indeed ugly.  We have a couple of
8606          * things going on here:
8607          *
8608          * 1) We need to reserve space to update our inode.
8609          *
8610          * 2) We need to have something to cache all the space that is going to
8611          * be free'd up by the truncate operation, but also have some slack
8612          * space reserved in case it uses space during the truncate (thank you
8613          * very much snapshotting).
8614          *
8615          * And we need these to be separate.  The fact is we can use a lot of
8616          * space doing the truncate, and we have no earthly idea how much space
8617          * we will use, so we need the truncate reservation to be separate so it
8618          * doesn't end up using space reserved for updating the inode.  We also
8619          * need to be able to stop the transaction and start a new one, which
8620          * means we need to be able to update the inode several times, and we
8621          * have no idea of knowing how many times that will be, so we can't just
8622          * reserve 1 item for the entirety of the operation, so that has to be
8623          * done separately as well.
8624          *
8625          * So that leaves us with
8626          *
8627          * 1) rsv - for the truncate reservation, which we will steal from the
8628          * transaction reservation.
8629          * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8630          * updating the inode.
8631          */
8632         rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
8633         if (!rsv)
8634                 return -ENOMEM;
8635         rsv->size = min_size;
8636         rsv->failfast = 1;
8637
8638         /*
8639          * 1 for the truncate slack space
8640          * 1 for updating the inode.
8641          */
8642         trans = btrfs_start_transaction(root, 2);
8643         if (IS_ERR(trans)) {
8644                 ret = PTR_ERR(trans);
8645                 goto out;
8646         }
8647
8648         /* Migrate the slack space for the truncate to our reserve */
8649         ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
8650                                       min_size, false);
8651         BUG_ON(ret);
8652
8653         /*
8654          * So if we truncate and then write and fsync we normally would just
8655          * write the extents that changed, which is a problem if we need to
8656          * first truncate that entire inode.  So set this flag so we write out
8657          * all of the extents in the inode to the sync log so we're completely
8658          * safe.
8659          */
8660         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
8661         trans->block_rsv = rsv;
8662
8663         while (1) {
8664                 ret = btrfs_truncate_inode_items(trans, root, BTRFS_I(inode),
8665                                                  inode->i_size,
8666                                                  BTRFS_EXTENT_DATA_KEY);
8667                 trans->block_rsv = &fs_info->trans_block_rsv;
8668                 if (ret != -ENOSPC && ret != -EAGAIN)
8669                         break;
8670
8671                 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
8672                 if (ret)
8673                         break;
8674
8675                 btrfs_end_transaction(trans);
8676                 btrfs_btree_balance_dirty(fs_info);
8677
8678                 trans = btrfs_start_transaction(root, 2);
8679                 if (IS_ERR(trans)) {
8680                         ret = PTR_ERR(trans);
8681                         trans = NULL;
8682                         break;
8683                 }
8684
8685                 btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
8686                 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
8687                                               rsv, min_size, false);
8688                 BUG_ON(ret);    /* shouldn't happen */
8689                 trans->block_rsv = rsv;
8690         }
8691
8692         /*
8693          * We can't call btrfs_truncate_block inside a trans handle as we could
8694          * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
8695          * we've truncated everything except the last little bit, and can do
8696          * btrfs_truncate_block and then update the disk_i_size.
8697          */
8698         if (ret == NEED_TRUNCATE_BLOCK) {
8699                 btrfs_end_transaction(trans);
8700                 btrfs_btree_balance_dirty(fs_info);
8701
8702                 ret = btrfs_truncate_block(BTRFS_I(inode), inode->i_size, 0, 0);
8703                 if (ret)
8704                         goto out;
8705                 trans = btrfs_start_transaction(root, 1);
8706                 if (IS_ERR(trans)) {
8707                         ret = PTR_ERR(trans);
8708                         goto out;
8709                 }
8710                 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
8711         }
8712
8713         if (trans) {
8714                 int ret2;
8715
8716                 trans->block_rsv = &fs_info->trans_block_rsv;
8717                 ret2 = btrfs_update_inode(trans, root, BTRFS_I(inode));
8718                 if (ret2 && !ret)
8719                         ret = ret2;
8720
8721                 ret2 = btrfs_end_transaction(trans);
8722                 if (ret2 && !ret)
8723                         ret = ret2;
8724                 btrfs_btree_balance_dirty(fs_info);
8725         }
8726 out:
8727         btrfs_free_block_rsv(fs_info, rsv);
8728
8729         return ret;
8730 }
8731
8732 /*
8733  * create a new subvolume directory/inode (helper for the ioctl).
8734  */
8735 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
8736                              struct btrfs_root *new_root,
8737                              struct btrfs_root *parent_root)
8738 {
8739         struct inode *inode;
8740         int err;
8741         u64 index = 0;
8742         u64 ino;
8743
8744         err = btrfs_get_free_objectid(new_root, &ino);
8745         if (err < 0)
8746                 return err;
8747
8748         inode = btrfs_new_inode(trans, new_root, NULL, "..", 2, ino, ino,
8749                                 S_IFDIR | (~current_umask() & S_IRWXUGO),
8750                                 &index);
8751         if (IS_ERR(inode))
8752                 return PTR_ERR(inode);
8753         inode->i_op = &btrfs_dir_inode_operations;
8754         inode->i_fop = &btrfs_dir_file_operations;
8755
8756         set_nlink(inode, 1);
8757         btrfs_i_size_write(BTRFS_I(inode), 0);
8758         unlock_new_inode(inode);
8759
8760         err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8761         if (err)
8762                 btrfs_err(new_root->fs_info,
8763                           "error inheriting subvolume %llu properties: %d",
8764                           new_root->root_key.objectid, err);
8765
8766         err = btrfs_update_inode(trans, new_root, BTRFS_I(inode));
8767
8768         iput(inode);
8769         return err;
8770 }
8771
8772 struct inode *btrfs_alloc_inode(struct super_block *sb)
8773 {
8774         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
8775         struct btrfs_inode *ei;
8776         struct inode *inode;
8777
8778         ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
8779         if (!ei)
8780                 return NULL;
8781
8782         ei->root = NULL;
8783         ei->generation = 0;
8784         ei->last_trans = 0;
8785         ei->last_sub_trans = 0;
8786         ei->logged_trans = 0;
8787         ei->delalloc_bytes = 0;
8788         ei->new_delalloc_bytes = 0;
8789         ei->defrag_bytes = 0;
8790         ei->disk_i_size = 0;
8791         ei->flags = 0;
8792         ei->csum_bytes = 0;
8793         ei->index_cnt = (u64)-1;
8794         ei->dir_index = 0;
8795         ei->last_unlink_trans = 0;
8796         ei->last_reflink_trans = 0;
8797         ei->last_log_commit = 0;
8798
8799         spin_lock_init(&ei->lock);
8800         ei->outstanding_extents = 0;
8801         if (sb->s_magic != BTRFS_TEST_MAGIC)
8802                 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
8803                                               BTRFS_BLOCK_RSV_DELALLOC);
8804         ei->runtime_flags = 0;
8805         ei->prop_compress = BTRFS_COMPRESS_NONE;
8806         ei->defrag_compress = BTRFS_COMPRESS_NONE;
8807
8808         ei->delayed_node = NULL;
8809
8810         ei->i_otime.tv_sec = 0;
8811         ei->i_otime.tv_nsec = 0;
8812
8813         inode = &ei->vfs_inode;
8814         extent_map_tree_init(&ei->extent_tree);
8815         extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
8816         extent_io_tree_init(fs_info, &ei->io_failure_tree,
8817                             IO_TREE_INODE_IO_FAILURE, inode);
8818         extent_io_tree_init(fs_info, &ei->file_extent_tree,
8819                             IO_TREE_INODE_FILE_EXTENT, inode);
8820         ei->io_tree.track_uptodate = true;
8821         ei->io_failure_tree.track_uptodate = true;
8822         atomic_set(&ei->sync_writers, 0);
8823         mutex_init(&ei->log_mutex);
8824         btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8825         INIT_LIST_HEAD(&ei->delalloc_inodes);
8826         INIT_LIST_HEAD(&ei->delayed_iput);
8827         RB_CLEAR_NODE(&ei->rb_node);
8828
8829         return inode;
8830 }
8831
8832 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8833 void btrfs_test_destroy_inode(struct inode *inode)
8834 {
8835         btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
8836         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8837 }
8838 #endif
8839
8840 void btrfs_free_inode(struct inode *inode)
8841 {
8842         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8843 }
8844
8845 void btrfs_destroy_inode(struct inode *vfs_inode)
8846 {
8847         struct btrfs_ordered_extent *ordered;
8848         struct btrfs_inode *inode = BTRFS_I(vfs_inode);
8849         struct btrfs_root *root = inode->root;
8850
8851         WARN_ON(!hlist_empty(&vfs_inode->i_dentry));
8852         WARN_ON(vfs_inode->i_data.nrpages);
8853         WARN_ON(inode->block_rsv.reserved);
8854         WARN_ON(inode->block_rsv.size);
8855         WARN_ON(inode->outstanding_extents);
8856         WARN_ON(inode->delalloc_bytes);
8857         WARN_ON(inode->new_delalloc_bytes);
8858         WARN_ON(inode->csum_bytes);
8859         WARN_ON(inode->defrag_bytes);
8860
8861         /*
8862          * This can happen where we create an inode, but somebody else also
8863          * created the same inode and we need to destroy the one we already
8864          * created.
8865          */
8866         if (!root)
8867                 return;
8868
8869         while (1) {
8870                 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8871                 if (!ordered)
8872                         break;
8873                 else {
8874                         btrfs_err(root->fs_info,
8875                                   "found ordered extent %llu %llu on inode cleanup",
8876                                   ordered->file_offset, ordered->num_bytes);
8877                         btrfs_remove_ordered_extent(inode, ordered);
8878                         btrfs_put_ordered_extent(ordered);
8879                         btrfs_put_ordered_extent(ordered);
8880                 }
8881         }
8882         btrfs_qgroup_check_reserved_leak(inode);
8883         inode_tree_del(inode);
8884         btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8885         btrfs_inode_clear_file_extent_range(inode, 0, (u64)-1);
8886         btrfs_put_root(inode->root);
8887 }
8888
8889 int btrfs_drop_inode(struct inode *inode)
8890 {
8891         struct btrfs_root *root = BTRFS_I(inode)->root;
8892
8893         if (root == NULL)
8894                 return 1;
8895
8896         /* the snap/subvol tree is on deleting */
8897         if (btrfs_root_refs(&root->root_item) == 0)
8898                 return 1;
8899         else
8900                 return generic_drop_inode(inode);
8901 }
8902
8903 static void init_once(void *foo)
8904 {
8905         struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8906
8907         inode_init_once(&ei->vfs_inode);
8908 }
8909
8910 void __cold btrfs_destroy_cachep(void)
8911 {
8912         /*
8913          * Make sure all delayed rcu free inodes are flushed before we
8914          * destroy cache.
8915          */
8916         rcu_barrier();
8917         kmem_cache_destroy(btrfs_inode_cachep);
8918         kmem_cache_destroy(btrfs_trans_handle_cachep);
8919         kmem_cache_destroy(btrfs_path_cachep);
8920         kmem_cache_destroy(btrfs_free_space_cachep);
8921         kmem_cache_destroy(btrfs_free_space_bitmap_cachep);
8922 }
8923
8924 int __init btrfs_init_cachep(void)
8925 {
8926         btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8927                         sizeof(struct btrfs_inode), 0,
8928                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
8929                         init_once);
8930         if (!btrfs_inode_cachep)
8931                 goto fail;
8932
8933         btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8934                         sizeof(struct btrfs_trans_handle), 0,
8935                         SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
8936         if (!btrfs_trans_handle_cachep)
8937                 goto fail;
8938
8939         btrfs_path_cachep = kmem_cache_create("btrfs_path",
8940                         sizeof(struct btrfs_path), 0,
8941                         SLAB_MEM_SPREAD, NULL);
8942         if (!btrfs_path_cachep)
8943                 goto fail;
8944
8945         btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8946                         sizeof(struct btrfs_free_space), 0,
8947                         SLAB_MEM_SPREAD, NULL);
8948         if (!btrfs_free_space_cachep)
8949                 goto fail;
8950
8951         btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap",
8952                                                         PAGE_SIZE, PAGE_SIZE,
8953                                                         SLAB_RED_ZONE, NULL);
8954         if (!btrfs_free_space_bitmap_cachep)
8955                 goto fail;
8956
8957         return 0;
8958 fail:
8959         btrfs_destroy_cachep();
8960         return -ENOMEM;
8961 }
8962
8963 static int btrfs_getattr(const struct path *path, struct kstat *stat,
8964                          u32 request_mask, unsigned int flags)
8965 {
8966         u64 delalloc_bytes;
8967         u64 inode_bytes;
8968         struct inode *inode = d_inode(path->dentry);
8969         u32 blocksize = inode->i_sb->s_blocksize;
8970         u32 bi_flags = BTRFS_I(inode)->flags;
8971
8972         stat->result_mask |= STATX_BTIME;
8973         stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
8974         stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
8975         if (bi_flags & BTRFS_INODE_APPEND)
8976                 stat->attributes |= STATX_ATTR_APPEND;
8977         if (bi_flags & BTRFS_INODE_COMPRESS)
8978                 stat->attributes |= STATX_ATTR_COMPRESSED;
8979         if (bi_flags & BTRFS_INODE_IMMUTABLE)
8980                 stat->attributes |= STATX_ATTR_IMMUTABLE;
8981         if (bi_flags & BTRFS_INODE_NODUMP)
8982                 stat->attributes |= STATX_ATTR_NODUMP;
8983
8984         stat->attributes_mask |= (STATX_ATTR_APPEND |
8985                                   STATX_ATTR_COMPRESSED |
8986                                   STATX_ATTR_IMMUTABLE |
8987                                   STATX_ATTR_NODUMP);
8988
8989         generic_fillattr(inode, stat);
8990         stat->dev = BTRFS_I(inode)->root->anon_dev;
8991
8992         spin_lock(&BTRFS_I(inode)->lock);
8993         delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
8994         inode_bytes = inode_get_bytes(inode);
8995         spin_unlock(&BTRFS_I(inode)->lock);
8996         stat->blocks = (ALIGN(inode_bytes, blocksize) +
8997                         ALIGN(delalloc_bytes, blocksize)) >> 9;
8998         return 0;
8999 }
9000
9001 static int btrfs_rename_exchange(struct inode *old_dir,
9002                               struct dentry *old_dentry,
9003                               struct inode *new_dir,
9004                               struct dentry *new_dentry)
9005 {
9006         struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9007         struct btrfs_trans_handle *trans;
9008         struct btrfs_root *root = BTRFS_I(old_dir)->root;
9009         struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9010         struct inode *new_inode = new_dentry->d_inode;
9011         struct inode *old_inode = old_dentry->d_inode;
9012         struct timespec64 ctime = current_time(old_inode);
9013         u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9014         u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9015         u64 old_idx = 0;
9016         u64 new_idx = 0;
9017         int ret;
9018         int ret2;
9019         bool root_log_pinned = false;
9020         bool dest_log_pinned = false;
9021
9022         /* we only allow rename subvolume link between subvolumes */
9023         if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9024                 return -EXDEV;
9025
9026         /* close the race window with snapshot create/destroy ioctl */
9027         if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
9028             new_ino == BTRFS_FIRST_FREE_OBJECTID)
9029                 down_read(&fs_info->subvol_sem);
9030
9031         /*
9032          * We want to reserve the absolute worst case amount of items.  So if
9033          * both inodes are subvols and we need to unlink them then that would
9034          * require 4 item modifications, but if they are both normal inodes it
9035          * would require 5 item modifications, so we'll assume their normal
9036          * inodes.  So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9037          * should cover the worst case number of items we'll modify.
9038          */
9039         trans = btrfs_start_transaction(root, 12);
9040         if (IS_ERR(trans)) {
9041                 ret = PTR_ERR(trans);
9042                 goto out_notrans;
9043         }
9044
9045         if (dest != root)
9046                 btrfs_record_root_in_trans(trans, dest);
9047
9048         /*
9049          * We need to find a free sequence number both in the source and
9050          * in the destination directory for the exchange.
9051          */
9052         ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9053         if (ret)
9054                 goto out_fail;
9055         ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9056         if (ret)
9057                 goto out_fail;
9058
9059         BTRFS_I(old_inode)->dir_index = 0ULL;
9060         BTRFS_I(new_inode)->dir_index = 0ULL;
9061
9062         /* Reference for the source. */
9063         if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9064                 /* force full log commit if subvolume involved. */
9065                 btrfs_set_log_full_commit(trans);
9066         } else {
9067                 btrfs_pin_log_trans(root);
9068                 root_log_pinned = true;
9069                 ret = btrfs_insert_inode_ref(trans, dest,
9070                                              new_dentry->d_name.name,
9071                                              new_dentry->d_name.len,
9072                                              old_ino,
9073                                              btrfs_ino(BTRFS_I(new_dir)),
9074                                              old_idx);
9075                 if (ret)
9076                         goto out_fail;
9077         }
9078
9079         /* And now for the dest. */
9080         if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9081                 /* force full log commit if subvolume involved. */
9082                 btrfs_set_log_full_commit(trans);
9083         } else {
9084                 btrfs_pin_log_trans(dest);
9085                 dest_log_pinned = true;
9086                 ret = btrfs_insert_inode_ref(trans, root,
9087                                              old_dentry->d_name.name,
9088                                              old_dentry->d_name.len,
9089                                              new_ino,
9090                                              btrfs_ino(BTRFS_I(old_dir)),
9091                                              new_idx);
9092                 if (ret)
9093                         goto out_fail;
9094         }
9095
9096         /* Update inode version and ctime/mtime. */
9097         inode_inc_iversion(old_dir);
9098         inode_inc_iversion(new_dir);
9099         inode_inc_iversion(old_inode);
9100         inode_inc_iversion(new_inode);
9101         old_dir->i_ctime = old_dir->i_mtime = ctime;
9102         new_dir->i_ctime = new_dir->i_mtime = ctime;
9103         old_inode->i_ctime = ctime;
9104         new_inode->i_ctime = ctime;
9105
9106         if (old_dentry->d_parent != new_dentry->d_parent) {
9107                 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9108                                 BTRFS_I(old_inode), 1);
9109                 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9110                                 BTRFS_I(new_inode), 1);
9111         }
9112
9113         /* src is a subvolume */
9114         if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9115                 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9116         } else { /* src is an inode */
9117                 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9118                                            BTRFS_I(old_dentry->d_inode),
9119                                            old_dentry->d_name.name,
9120                                            old_dentry->d_name.len);
9121                 if (!ret)
9122                         ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
9123         }
9124         if (ret) {
9125                 btrfs_abort_transaction(trans, ret);
9126                 goto out_fail;
9127         }
9128
9129         /* dest is a subvolume */
9130         if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9131                 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9132         } else { /* dest is an inode */
9133                 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9134                                            BTRFS_I(new_dentry->d_inode),
9135                                            new_dentry->d_name.name,
9136                                            new_dentry->d_name.len);
9137                 if (!ret)
9138                         ret = btrfs_update_inode(trans, dest, BTRFS_I(new_inode));
9139         }
9140         if (ret) {
9141                 btrfs_abort_transaction(trans, ret);
9142                 goto out_fail;
9143         }
9144
9145         ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9146                              new_dentry->d_name.name,
9147                              new_dentry->d_name.len, 0, old_idx);
9148         if (ret) {
9149                 btrfs_abort_transaction(trans, ret);
9150                 goto out_fail;
9151         }
9152
9153         ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9154                              old_dentry->d_name.name,
9155                              old_dentry->d_name.len, 0, new_idx);
9156         if (ret) {
9157                 btrfs_abort_transaction(trans, ret);
9158                 goto out_fail;
9159         }
9160
9161         if (old_inode->i_nlink == 1)
9162                 BTRFS_I(old_inode)->dir_index = old_idx;
9163         if (new_inode->i_nlink == 1)
9164                 BTRFS_I(new_inode)->dir_index = new_idx;
9165
9166         if (root_log_pinned) {
9167                 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9168                                    new_dentry->d_parent);
9169                 btrfs_end_log_trans(root);
9170                 root_log_pinned = false;
9171         }
9172         if (dest_log_pinned) {
9173                 btrfs_log_new_name(trans, BTRFS_I(new_inode), BTRFS_I(new_dir),
9174                                    old_dentry->d_parent);
9175                 btrfs_end_log_trans(dest);
9176                 dest_log_pinned = false;
9177         }
9178 out_fail:
9179         /*
9180          * If we have pinned a log and an error happened, we unpin tasks
9181          * trying to sync the log and force them to fallback to a transaction
9182          * commit if the log currently contains any of the inodes involved in
9183          * this rename operation (to ensure we do not persist a log with an
9184          * inconsistent state for any of these inodes or leading to any
9185          * inconsistencies when replayed). If the transaction was aborted, the
9186          * abortion reason is propagated to userspace when attempting to commit
9187          * the transaction. If the log does not contain any of these inodes, we
9188          * allow the tasks to sync it.
9189          */
9190         if (ret && (root_log_pinned || dest_log_pinned)) {
9191                 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9192                     btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9193                     btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9194                     (new_inode &&
9195                      btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9196                         btrfs_set_log_full_commit(trans);
9197
9198                 if (root_log_pinned) {
9199                         btrfs_end_log_trans(root);
9200                         root_log_pinned = false;
9201                 }
9202                 if (dest_log_pinned) {
9203                         btrfs_end_log_trans(dest);
9204                         dest_log_pinned = false;
9205                 }
9206         }
9207         ret2 = btrfs_end_transaction(trans);
9208         ret = ret ? ret : ret2;
9209 out_notrans:
9210         if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
9211             old_ino == BTRFS_FIRST_FREE_OBJECTID)
9212                 up_read(&fs_info->subvol_sem);
9213
9214         return ret;
9215 }
9216
9217 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9218                                      struct btrfs_root *root,
9219                                      struct inode *dir,
9220                                      struct dentry *dentry)
9221 {
9222         int ret;
9223         struct inode *inode;
9224         u64 objectid;
9225         u64 index;
9226
9227         ret = btrfs_get_free_objectid(root, &objectid);
9228         if (ret)
9229                 return ret;
9230
9231         inode = btrfs_new_inode(trans, root, dir,
9232                                 dentry->d_name.name,
9233                                 dentry->d_name.len,
9234                                 btrfs_ino(BTRFS_I(dir)),
9235                                 objectid,
9236                                 S_IFCHR | WHITEOUT_MODE,
9237                                 &index);
9238
9239         if (IS_ERR(inode)) {
9240                 ret = PTR_ERR(inode);
9241                 return ret;
9242         }
9243
9244         inode->i_op = &btrfs_special_inode_operations;
9245         init_special_inode(inode, inode->i_mode,
9246                 WHITEOUT_DEV);
9247
9248         ret = btrfs_init_inode_security(trans, inode, dir,
9249                                 &dentry->d_name);
9250         if (ret)
9251                 goto out;
9252
9253         ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9254                                 BTRFS_I(inode), 0, index);
9255         if (ret)
9256                 goto out;
9257
9258         ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
9259 out:
9260         unlock_new_inode(inode);
9261         if (ret)
9262                 inode_dec_link_count(inode);
9263         iput(inode);
9264
9265         return ret;
9266 }
9267
9268 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9269                            struct inode *new_dir, struct dentry *new_dentry,
9270                            unsigned int flags)
9271 {
9272         struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9273         struct btrfs_trans_handle *trans;
9274         unsigned int trans_num_items;
9275         struct btrfs_root *root = BTRFS_I(old_dir)->root;
9276         struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9277         struct inode *new_inode = d_inode(new_dentry);
9278         struct inode *old_inode = d_inode(old_dentry);
9279         u64 index = 0;
9280         int ret;
9281         int ret2;
9282         u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9283         bool log_pinned = false;
9284
9285         if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9286                 return -EPERM;
9287
9288         /* we only allow rename subvolume link between subvolumes */
9289         if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9290                 return -EXDEV;
9291
9292         if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9293             (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9294                 return -ENOTEMPTY;
9295
9296         if (S_ISDIR(old_inode->i_mode) && new_inode &&
9297             new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9298                 return -ENOTEMPTY;
9299
9300
9301         /* check for collisions, even if the  name isn't there */
9302         ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9303                              new_dentry->d_name.name,
9304                              new_dentry->d_name.len);
9305
9306         if (ret) {
9307                 if (ret == -EEXIST) {
9308                         /* we shouldn't get
9309                          * eexist without a new_inode */
9310                         if (WARN_ON(!new_inode)) {
9311                                 return ret;
9312                         }
9313                 } else {
9314                         /* maybe -EOVERFLOW */
9315                         return ret;
9316                 }
9317         }
9318         ret = 0;
9319
9320         /*
9321          * we're using rename to replace one file with another.  Start IO on it
9322          * now so  we don't add too much work to the end of the transaction
9323          */
9324         if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9325                 filemap_flush(old_inode->i_mapping);
9326
9327         /* close the racy window with snapshot create/destroy ioctl */
9328         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9329                 down_read(&fs_info->subvol_sem);
9330         /*
9331          * We want to reserve the absolute worst case amount of items.  So if
9332          * both inodes are subvols and we need to unlink them then that would
9333          * require 4 item modifications, but if they are both normal inodes it
9334          * would require 5 item modifications, so we'll assume they are normal
9335          * inodes.  So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9336          * should cover the worst case number of items we'll modify.
9337          * If our rename has the whiteout flag, we need more 5 units for the
9338          * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9339          * when selinux is enabled).
9340          */
9341         trans_num_items = 11;
9342         if (flags & RENAME_WHITEOUT)
9343                 trans_num_items += 5;
9344         trans = btrfs_start_transaction(root, trans_num_items);
9345         if (IS_ERR(trans)) {
9346                 ret = PTR_ERR(trans);
9347                 goto out_notrans;
9348         }
9349
9350         if (dest != root)
9351                 btrfs_record_root_in_trans(trans, dest);
9352
9353         ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9354         if (ret)
9355                 goto out_fail;
9356
9357         BTRFS_I(old_inode)->dir_index = 0ULL;
9358         if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9359                 /* force full log commit if subvolume involved. */
9360                 btrfs_set_log_full_commit(trans);
9361         } else {
9362                 btrfs_pin_log_trans(root);
9363                 log_pinned = true;
9364                 ret = btrfs_insert_inode_ref(trans, dest,
9365                                              new_dentry->d_name.name,
9366                                              new_dentry->d_name.len,
9367                                              old_ino,
9368                                              btrfs_ino(BTRFS_I(new_dir)), index);
9369                 if (ret)
9370                         goto out_fail;
9371         }
9372
9373         inode_inc_iversion(old_dir);
9374         inode_inc_iversion(new_dir);
9375         inode_inc_iversion(old_inode);
9376         old_dir->i_ctime = old_dir->i_mtime =
9377         new_dir->i_ctime = new_dir->i_mtime =
9378         old_inode->i_ctime = current_time(old_dir);
9379
9380         if (old_dentry->d_parent != new_dentry->d_parent)
9381                 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9382                                 BTRFS_I(old_inode), 1);
9383
9384         if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9385                 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9386         } else {
9387                 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9388                                         BTRFS_I(d_inode(old_dentry)),
9389                                         old_dentry->d_name.name,
9390                                         old_dentry->d_name.len);
9391                 if (!ret)
9392                         ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
9393         }
9394         if (ret) {
9395                 btrfs_abort_transaction(trans, ret);
9396                 goto out_fail;
9397         }
9398
9399         if (new_inode) {
9400                 inode_inc_iversion(new_inode);
9401                 new_inode->i_ctime = current_time(new_inode);
9402                 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9403                              BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9404                         ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9405                         BUG_ON(new_inode->i_nlink == 0);
9406                 } else {
9407                         ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9408                                                  BTRFS_I(d_inode(new_dentry)),
9409                                                  new_dentry->d_name.name,
9410                                                  new_dentry->d_name.len);
9411                 }
9412                 if (!ret && new_inode->i_nlink == 0)
9413                         ret = btrfs_orphan_add(trans,
9414                                         BTRFS_I(d_inode(new_dentry)));
9415                 if (ret) {
9416                         btrfs_abort_transaction(trans, ret);
9417                         goto out_fail;
9418                 }
9419         }
9420
9421         ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9422                              new_dentry->d_name.name,
9423                              new_dentry->d_name.len, 0, index);
9424         if (ret) {
9425                 btrfs_abort_transaction(trans, ret);
9426                 goto out_fail;
9427         }
9428
9429         if (old_inode->i_nlink == 1)
9430                 BTRFS_I(old_inode)->dir_index = index;
9431
9432         if (log_pinned) {
9433                 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9434                                    new_dentry->d_parent);
9435                 btrfs_end_log_trans(root);
9436                 log_pinned = false;
9437         }
9438
9439         if (flags & RENAME_WHITEOUT) {
9440                 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9441                                                 old_dentry);
9442
9443                 if (ret) {
9444                         btrfs_abort_transaction(trans, ret);
9445                         goto out_fail;
9446                 }
9447         }
9448 out_fail:
9449         /*
9450          * If we have pinned the log and an error happened, we unpin tasks
9451          * trying to sync the log and force them to fallback to a transaction
9452          * commit if the log currently contains any of the inodes involved in
9453          * this rename operation (to ensure we do not persist a log with an
9454          * inconsistent state for any of these inodes or leading to any
9455          * inconsistencies when replayed). If the transaction was aborted, the
9456          * abortion reason is propagated to userspace when attempting to commit
9457          * the transaction. If the log does not contain any of these inodes, we
9458          * allow the tasks to sync it.
9459          */
9460         if (ret && log_pinned) {
9461                 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9462                     btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9463                     btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9464                     (new_inode &&
9465                      btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9466                         btrfs_set_log_full_commit(trans);
9467
9468                 btrfs_end_log_trans(root);
9469                 log_pinned = false;
9470         }
9471         ret2 = btrfs_end_transaction(trans);
9472         ret = ret ? ret : ret2;
9473 out_notrans:
9474         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9475                 up_read(&fs_info->subvol_sem);
9476
9477         return ret;
9478 }
9479
9480 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9481                          struct inode *new_dir, struct dentry *new_dentry,
9482                          unsigned int flags)
9483 {
9484         if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9485                 return -EINVAL;
9486
9487         if (flags & RENAME_EXCHANGE)
9488                 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9489                                           new_dentry);
9490
9491         return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9492 }
9493
9494 struct btrfs_delalloc_work {
9495         struct inode *inode;
9496         struct completion completion;
9497         struct list_head list;
9498         struct btrfs_work work;
9499 };
9500
9501 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9502 {
9503         struct btrfs_delalloc_work *delalloc_work;
9504         struct inode *inode;
9505
9506         delalloc_work = container_of(work, struct btrfs_delalloc_work,
9507                                      work);
9508         inode = delalloc_work->inode;
9509         filemap_flush(inode->i_mapping);
9510         if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9511                                 &BTRFS_I(inode)->runtime_flags))
9512                 filemap_flush(inode->i_mapping);
9513
9514         iput(inode);
9515         complete(&delalloc_work->completion);
9516 }
9517
9518 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9519 {
9520         struct btrfs_delalloc_work *work;
9521
9522         work = kmalloc(sizeof(*work), GFP_NOFS);
9523         if (!work)
9524                 return NULL;
9525
9526         init_completion(&work->completion);
9527         INIT_LIST_HEAD(&work->list);
9528         work->inode = inode;
9529         btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
9530
9531         return work;
9532 }
9533
9534 /*
9535  * some fairly slow code that needs optimization. This walks the list
9536  * of all the inodes with pending delalloc and forces them to disk.
9537  */
9538 static int start_delalloc_inodes(struct btrfs_root *root,
9539                                  struct writeback_control *wbc, bool snapshot,
9540                                  bool in_reclaim_context)
9541 {
9542         struct btrfs_inode *binode;
9543         struct inode *inode;
9544         struct btrfs_delalloc_work *work, *next;
9545         struct list_head works;
9546         struct list_head splice;
9547         int ret = 0;
9548         bool full_flush = wbc->nr_to_write == LONG_MAX;
9549
9550         INIT_LIST_HEAD(&works);
9551         INIT_LIST_HEAD(&splice);
9552
9553         mutex_lock(&root->delalloc_mutex);
9554         spin_lock(&root->delalloc_lock);
9555         list_splice_init(&root->delalloc_inodes, &splice);
9556         while (!list_empty(&splice)) {
9557                 binode = list_entry(splice.next, struct btrfs_inode,
9558                                     delalloc_inodes);
9559
9560                 list_move_tail(&binode->delalloc_inodes,
9561                                &root->delalloc_inodes);
9562
9563                 if (in_reclaim_context &&
9564                     test_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &binode->runtime_flags))
9565                         continue;
9566
9567                 inode = igrab(&binode->vfs_inode);
9568                 if (!inode) {
9569                         cond_resched_lock(&root->delalloc_lock);
9570                         continue;
9571                 }
9572                 spin_unlock(&root->delalloc_lock);
9573
9574                 if (snapshot)
9575                         set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
9576                                 &binode->runtime_flags);
9577                 if (full_flush) {
9578                         work = btrfs_alloc_delalloc_work(inode);
9579                         if (!work) {
9580                                 iput(inode);
9581                                 ret = -ENOMEM;
9582                                 goto out;
9583                         }
9584                         list_add_tail(&work->list, &works);
9585                         btrfs_queue_work(root->fs_info->flush_workers,
9586                                          &work->work);
9587                 } else {
9588                         ret = sync_inode(inode, wbc);
9589                         if (!ret &&
9590                             test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9591                                      &BTRFS_I(inode)->runtime_flags))
9592                                 ret = sync_inode(inode, wbc);
9593                         btrfs_add_delayed_iput(inode);
9594                         if (ret || wbc->nr_to_write <= 0)
9595                                 goto out;
9596                 }
9597                 cond_resched();
9598                 spin_lock(&root->delalloc_lock);
9599         }
9600         spin_unlock(&root->delalloc_lock);
9601
9602 out:
9603         list_for_each_entry_safe(work, next, &works, list) {
9604                 list_del_init(&work->list);
9605                 wait_for_completion(&work->completion);
9606                 kfree(work);
9607         }
9608
9609         if (!list_empty(&splice)) {
9610                 spin_lock(&root->delalloc_lock);
9611                 list_splice_tail(&splice, &root->delalloc_inodes);
9612                 spin_unlock(&root->delalloc_lock);
9613         }
9614         mutex_unlock(&root->delalloc_mutex);
9615         return ret;
9616 }
9617
9618 int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
9619 {
9620         struct writeback_control wbc = {
9621                 .nr_to_write = LONG_MAX,
9622                 .sync_mode = WB_SYNC_NONE,
9623                 .range_start = 0,
9624                 .range_end = LLONG_MAX,
9625         };
9626         struct btrfs_fs_info *fs_info = root->fs_info;
9627
9628         if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9629                 return -EROFS;
9630
9631         return start_delalloc_inodes(root, &wbc, true, false);
9632 }
9633
9634 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, long nr,
9635                                bool in_reclaim_context)
9636 {
9637         struct writeback_control wbc = {
9638                 .nr_to_write = nr,
9639                 .sync_mode = WB_SYNC_NONE,
9640                 .range_start = 0,
9641                 .range_end = LLONG_MAX,
9642         };
9643         struct btrfs_root *root;
9644         struct list_head splice;
9645         int ret;
9646
9647         if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9648                 return -EROFS;
9649
9650         INIT_LIST_HEAD(&splice);
9651
9652         mutex_lock(&fs_info->delalloc_root_mutex);
9653         spin_lock(&fs_info->delalloc_root_lock);
9654         list_splice_init(&fs_info->delalloc_roots, &splice);
9655         while (!list_empty(&splice)) {
9656                 /*
9657                  * Reset nr_to_write here so we know that we're doing a full
9658                  * flush.
9659                  */
9660                 if (nr == LONG_MAX)
9661                         wbc.nr_to_write = LONG_MAX;
9662
9663                 root = list_first_entry(&splice, struct btrfs_root,
9664                                         delalloc_root);
9665                 root = btrfs_grab_root(root);
9666                 BUG_ON(!root);
9667                 list_move_tail(&root->delalloc_root,
9668                                &fs_info->delalloc_roots);
9669                 spin_unlock(&fs_info->delalloc_root_lock);
9670
9671                 ret = start_delalloc_inodes(root, &wbc, false, in_reclaim_context);
9672                 btrfs_put_root(root);
9673                 if (ret < 0 || wbc.nr_to_write <= 0)
9674                         goto out;
9675                 spin_lock(&fs_info->delalloc_root_lock);
9676         }
9677         spin_unlock(&fs_info->delalloc_root_lock);
9678
9679         ret = 0;
9680 out:
9681         if (!list_empty(&splice)) {
9682                 spin_lock(&fs_info->delalloc_root_lock);
9683                 list_splice_tail(&splice, &fs_info->delalloc_roots);
9684                 spin_unlock(&fs_info->delalloc_root_lock);
9685         }
9686         mutex_unlock(&fs_info->delalloc_root_mutex);
9687         return ret;
9688 }
9689
9690 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
9691                          const char *symname)
9692 {
9693         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9694         struct btrfs_trans_handle *trans;
9695         struct btrfs_root *root = BTRFS_I(dir)->root;
9696         struct btrfs_path *path;
9697         struct btrfs_key key;
9698         struct inode *inode = NULL;
9699         int err;
9700         u64 objectid;
9701         u64 index = 0;
9702         int name_len;
9703         int datasize;
9704         unsigned long ptr;
9705         struct btrfs_file_extent_item *ei;
9706         struct extent_buffer *leaf;
9707
9708         name_len = strlen(symname);
9709         if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
9710                 return -ENAMETOOLONG;
9711
9712         /*
9713          * 2 items for inode item and ref
9714          * 2 items for dir items
9715          * 1 item for updating parent inode item
9716          * 1 item for the inline extent item
9717          * 1 item for xattr if selinux is on
9718          */
9719         trans = btrfs_start_transaction(root, 7);
9720         if (IS_ERR(trans))
9721                 return PTR_ERR(trans);
9722
9723         err = btrfs_get_free_objectid(root, &objectid);
9724         if (err)
9725                 goto out_unlock;
9726
9727         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9728                                 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
9729                                 objectid, S_IFLNK|S_IRWXUGO, &index);
9730         if (IS_ERR(inode)) {
9731                 err = PTR_ERR(inode);
9732                 inode = NULL;
9733                 goto out_unlock;
9734         }
9735
9736         /*
9737         * If the active LSM wants to access the inode during
9738         * d_instantiate it needs these. Smack checks to see
9739         * if the filesystem supports xattrs by looking at the
9740         * ops vector.
9741         */
9742         inode->i_fop = &btrfs_file_operations;
9743         inode->i_op = &btrfs_file_inode_operations;
9744         inode->i_mapping->a_ops = &btrfs_aops;
9745
9746         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9747         if (err)
9748                 goto out_unlock;
9749
9750         path = btrfs_alloc_path();
9751         if (!path) {
9752                 err = -ENOMEM;
9753                 goto out_unlock;
9754         }
9755         key.objectid = btrfs_ino(BTRFS_I(inode));
9756         key.offset = 0;
9757         key.type = BTRFS_EXTENT_DATA_KEY;
9758         datasize = btrfs_file_extent_calc_inline_size(name_len);
9759         err = btrfs_insert_empty_item(trans, root, path, &key,
9760                                       datasize);
9761         if (err) {
9762                 btrfs_free_path(path);
9763                 goto out_unlock;
9764         }
9765         leaf = path->nodes[0];
9766         ei = btrfs_item_ptr(leaf, path->slots[0],
9767                             struct btrfs_file_extent_item);
9768         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9769         btrfs_set_file_extent_type(leaf, ei,
9770                                    BTRFS_FILE_EXTENT_INLINE);
9771         btrfs_set_file_extent_encryption(leaf, ei, 0);
9772         btrfs_set_file_extent_compression(leaf, ei, 0);
9773         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9774         btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9775
9776         ptr = btrfs_file_extent_inline_start(ei);
9777         write_extent_buffer(leaf, symname, ptr, name_len);
9778         btrfs_mark_buffer_dirty(leaf);
9779         btrfs_free_path(path);
9780
9781         inode->i_op = &btrfs_symlink_inode_operations;
9782         inode_nohighmem(inode);
9783         inode_set_bytes(inode, name_len);
9784         btrfs_i_size_write(BTRFS_I(inode), name_len);
9785         err = btrfs_update_inode(trans, root, BTRFS_I(inode));
9786         /*
9787          * Last step, add directory indexes for our symlink inode. This is the
9788          * last step to avoid extra cleanup of these indexes if an error happens
9789          * elsewhere above.
9790          */
9791         if (!err)
9792                 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9793                                 BTRFS_I(inode), 0, index);
9794         if (err)
9795                 goto out_unlock;
9796
9797         d_instantiate_new(dentry, inode);
9798
9799 out_unlock:
9800         btrfs_end_transaction(trans);
9801         if (err && inode) {
9802                 inode_dec_link_count(inode);
9803                 discard_new_inode(inode);
9804         }
9805         btrfs_btree_balance_dirty(fs_info);
9806         return err;
9807 }
9808
9809 static struct btrfs_trans_handle *insert_prealloc_file_extent(
9810                                        struct btrfs_trans_handle *trans_in,
9811                                        struct btrfs_inode *inode,
9812                                        struct btrfs_key *ins,
9813                                        u64 file_offset)
9814 {
9815         struct btrfs_file_extent_item stack_fi;
9816         struct btrfs_replace_extent_info extent_info;
9817         struct btrfs_trans_handle *trans = trans_in;
9818         struct btrfs_path *path;
9819         u64 start = ins->objectid;
9820         u64 len = ins->offset;
9821         int ret;
9822
9823         memset(&stack_fi, 0, sizeof(stack_fi));
9824
9825         btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_PREALLOC);
9826         btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, start);
9827         btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, len);
9828         btrfs_set_stack_file_extent_num_bytes(&stack_fi, len);
9829         btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len);
9830         btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE);
9831         /* Encryption and other encoding is reserved and all 0 */
9832
9833         ret = btrfs_qgroup_release_data(inode, file_offset, len);
9834         if (ret < 0)
9835                 return ERR_PTR(ret);
9836
9837         if (trans) {
9838                 ret = insert_reserved_file_extent(trans, inode,
9839                                                   file_offset, &stack_fi,
9840                                                   true, ret);
9841                 if (ret)
9842                         return ERR_PTR(ret);
9843                 return trans;
9844         }
9845
9846         extent_info.disk_offset = start;
9847         extent_info.disk_len = len;
9848         extent_info.data_offset = 0;
9849         extent_info.data_len = len;
9850         extent_info.file_offset = file_offset;
9851         extent_info.extent_buf = (char *)&stack_fi;
9852         extent_info.is_new_extent = true;
9853         extent_info.qgroup_reserved = ret;
9854         extent_info.insertions = 0;
9855
9856         path = btrfs_alloc_path();
9857         if (!path)
9858                 return ERR_PTR(-ENOMEM);
9859
9860         ret = btrfs_replace_file_extents(&inode->vfs_inode, path, file_offset,
9861                                      file_offset + len - 1, &extent_info,
9862                                      &trans);
9863         btrfs_free_path(path);
9864         if (ret)
9865                 return ERR_PTR(ret);
9866
9867         return trans;
9868 }
9869
9870 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9871                                        u64 start, u64 num_bytes, u64 min_size,
9872                                        loff_t actual_len, u64 *alloc_hint,
9873                                        struct btrfs_trans_handle *trans)
9874 {
9875         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9876         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9877         struct extent_map *em;
9878         struct btrfs_root *root = BTRFS_I(inode)->root;
9879         struct btrfs_key ins;
9880         u64 cur_offset = start;
9881         u64 clear_offset = start;
9882         u64 i_size;
9883         u64 cur_bytes;
9884         u64 last_alloc = (u64)-1;
9885         int ret = 0;
9886         bool own_trans = true;
9887         u64 end = start + num_bytes - 1;
9888
9889         if (trans)
9890                 own_trans = false;
9891         while (num_bytes > 0) {
9892                 cur_bytes = min_t(u64, num_bytes, SZ_256M);
9893                 cur_bytes = max(cur_bytes, min_size);
9894                 /*
9895                  * If we are severely fragmented we could end up with really
9896                  * small allocations, so if the allocator is returning small
9897                  * chunks lets make its job easier by only searching for those
9898                  * sized chunks.
9899                  */
9900                 cur_bytes = min(cur_bytes, last_alloc);
9901                 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9902                                 min_size, 0, *alloc_hint, &ins, 1, 0);
9903                 if (ret)
9904                         break;
9905
9906                 /*
9907                  * We've reserved this space, and thus converted it from
9908                  * ->bytes_may_use to ->bytes_reserved.  Any error that happens
9909                  * from here on out we will only need to clear our reservation
9910                  * for the remaining unreserved area, so advance our
9911                  * clear_offset by our extent size.
9912                  */
9913                 clear_offset += ins.offset;
9914
9915                 last_alloc = ins.offset;
9916                 trans = insert_prealloc_file_extent(trans, BTRFS_I(inode),
9917                                                     &ins, cur_offset);
9918                 /*
9919                  * Now that we inserted the prealloc extent we can finally
9920                  * decrement the number of reservations in the block group.
9921                  * If we did it before, we could race with relocation and have
9922                  * relocation miss the reserved extent, making it fail later.
9923                  */
9924                 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9925                 if (IS_ERR(trans)) {
9926                         ret = PTR_ERR(trans);
9927                         btrfs_free_reserved_extent(fs_info, ins.objectid,
9928                                                    ins.offset, 0);
9929                         break;
9930                 }
9931
9932                 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
9933                                         cur_offset + ins.offset -1, 0);
9934
9935                 em = alloc_extent_map();
9936                 if (!em) {
9937                         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
9938                                 &BTRFS_I(inode)->runtime_flags);
9939                         goto next;
9940                 }
9941
9942                 em->start = cur_offset;
9943                 em->orig_start = cur_offset;
9944                 em->len = ins.offset;
9945                 em->block_start = ins.objectid;
9946                 em->block_len = ins.offset;
9947                 em->orig_block_len = ins.offset;
9948                 em->ram_bytes = ins.offset;
9949                 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9950                 em->generation = trans->transid;
9951
9952                 while (1) {
9953                         write_lock(&em_tree->lock);
9954                         ret = add_extent_mapping(em_tree, em, 1);
9955                         write_unlock(&em_tree->lock);
9956                         if (ret != -EEXIST)
9957                                 break;
9958                         btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
9959                                                 cur_offset + ins.offset - 1,
9960                                                 0);
9961                 }
9962                 free_extent_map(em);
9963 next:
9964                 num_bytes -= ins.offset;
9965                 cur_offset += ins.offset;
9966                 *alloc_hint = ins.objectid + ins.offset;
9967
9968                 inode_inc_iversion(inode);
9969                 inode->i_ctime = current_time(inode);
9970                 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9971                 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9972                     (actual_len > inode->i_size) &&
9973                     (cur_offset > inode->i_size)) {
9974                         if (cur_offset > actual_len)
9975                                 i_size = actual_len;
9976                         else
9977                                 i_size = cur_offset;
9978                         i_size_write(inode, i_size);
9979                         btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
9980                 }
9981
9982                 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
9983
9984                 if (ret) {
9985                         btrfs_abort_transaction(trans, ret);
9986                         if (own_trans)
9987                                 btrfs_end_transaction(trans);
9988                         break;
9989                 }
9990
9991                 if (own_trans) {
9992                         btrfs_end_transaction(trans);
9993                         trans = NULL;
9994                 }
9995         }
9996         if (clear_offset < end)
9997                 btrfs_free_reserved_data_space(BTRFS_I(inode), NULL, clear_offset,
9998                         end - clear_offset + 1);
9999         return ret;
10000 }
10001
10002 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10003                               u64 start, u64 num_bytes, u64 min_size,
10004                               loff_t actual_len, u64 *alloc_hint)
10005 {
10006         return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10007                                            min_size, actual_len, alloc_hint,
10008                                            NULL);
10009 }
10010
10011 int btrfs_prealloc_file_range_trans(struct inode *inode,
10012                                     struct btrfs_trans_handle *trans, int mode,
10013                                     u64 start, u64 num_bytes, u64 min_size,
10014                                     loff_t actual_len, u64 *alloc_hint)
10015 {
10016         return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10017                                            min_size, actual_len, alloc_hint, trans);
10018 }
10019
10020 static int btrfs_set_page_dirty(struct page *page)
10021 {
10022         return __set_page_dirty_nobuffers(page);
10023 }
10024
10025 static int btrfs_permission(struct inode *inode, int mask)
10026 {
10027         struct btrfs_root *root = BTRFS_I(inode)->root;
10028         umode_t mode = inode->i_mode;
10029
10030         if (mask & MAY_WRITE &&
10031             (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10032                 if (btrfs_root_readonly(root))
10033                         return -EROFS;
10034                 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10035                         return -EACCES;
10036         }
10037         return generic_permission(inode, mask);
10038 }
10039
10040 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10041 {
10042         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10043         struct btrfs_trans_handle *trans;
10044         struct btrfs_root *root = BTRFS_I(dir)->root;
10045         struct inode *inode = NULL;
10046         u64 objectid;
10047         u64 index;
10048         int ret = 0;
10049
10050         /*
10051          * 5 units required for adding orphan entry
10052          */
10053         trans = btrfs_start_transaction(root, 5);
10054         if (IS_ERR(trans))
10055                 return PTR_ERR(trans);
10056
10057         ret = btrfs_get_free_objectid(root, &objectid);
10058         if (ret)
10059                 goto out;
10060
10061         inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10062                         btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10063         if (IS_ERR(inode)) {
10064                 ret = PTR_ERR(inode);
10065                 inode = NULL;
10066                 goto out;
10067         }
10068
10069         inode->i_fop = &btrfs_file_operations;
10070         inode->i_op = &btrfs_file_inode_operations;
10071
10072         inode->i_mapping->a_ops = &btrfs_aops;
10073
10074         ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10075         if (ret)
10076                 goto out;
10077
10078         ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
10079         if (ret)
10080                 goto out;
10081         ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10082         if (ret)
10083                 goto out;
10084
10085         /*
10086          * We set number of links to 0 in btrfs_new_inode(), and here we set
10087          * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10088          * through:
10089          *
10090          *    d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10091          */
10092         set_nlink(inode, 1);
10093         d_tmpfile(dentry, inode);
10094         unlock_new_inode(inode);
10095         mark_inode_dirty(inode);
10096 out:
10097         btrfs_end_transaction(trans);
10098         if (ret && inode)
10099                 discard_new_inode(inode);
10100         btrfs_btree_balance_dirty(fs_info);
10101         return ret;
10102 }
10103
10104 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
10105 {
10106         struct inode *inode = tree->private_data;
10107         unsigned long index = start >> PAGE_SHIFT;
10108         unsigned long end_index = end >> PAGE_SHIFT;
10109         struct page *page;
10110
10111         while (index <= end_index) {
10112                 page = find_get_page(inode->i_mapping, index);
10113                 ASSERT(page); /* Pages should be in the extent_io_tree */
10114                 set_page_writeback(page);
10115                 put_page(page);
10116                 index++;
10117         }
10118 }
10119
10120 #ifdef CONFIG_SWAP
10121 /*
10122  * Add an entry indicating a block group or device which is pinned by a
10123  * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10124  * negative errno on failure.
10125  */
10126 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10127                                   bool is_block_group)
10128 {
10129         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10130         struct btrfs_swapfile_pin *sp, *entry;
10131         struct rb_node **p;
10132         struct rb_node *parent = NULL;
10133
10134         sp = kmalloc(sizeof(*sp), GFP_NOFS);
10135         if (!sp)
10136                 return -ENOMEM;
10137         sp->ptr = ptr;
10138         sp->inode = inode;
10139         sp->is_block_group = is_block_group;
10140
10141         spin_lock(&fs_info->swapfile_pins_lock);
10142         p = &fs_info->swapfile_pins.rb_node;
10143         while (*p) {
10144                 parent = *p;
10145                 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10146                 if (sp->ptr < entry->ptr ||
10147                     (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10148                         p = &(*p)->rb_left;
10149                 } else if (sp->ptr > entry->ptr ||
10150                            (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10151                         p = &(*p)->rb_right;
10152                 } else {
10153                         spin_unlock(&fs_info->swapfile_pins_lock);
10154                         kfree(sp);
10155                         return 1;
10156                 }
10157         }
10158         rb_link_node(&sp->node, parent, p);
10159         rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10160         spin_unlock(&fs_info->swapfile_pins_lock);
10161         return 0;
10162 }
10163
10164 /* Free all of the entries pinned by this swapfile. */
10165 static void btrfs_free_swapfile_pins(struct inode *inode)
10166 {
10167         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10168         struct btrfs_swapfile_pin *sp;
10169         struct rb_node *node, *next;
10170
10171         spin_lock(&fs_info->swapfile_pins_lock);
10172         node = rb_first(&fs_info->swapfile_pins);
10173         while (node) {
10174                 next = rb_next(node);
10175                 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10176                 if (sp->inode == inode) {
10177                         rb_erase(&sp->node, &fs_info->swapfile_pins);
10178                         if (sp->is_block_group)
10179                                 btrfs_put_block_group(sp->ptr);
10180                         kfree(sp);
10181                 }
10182                 node = next;
10183         }
10184         spin_unlock(&fs_info->swapfile_pins_lock);
10185 }
10186
10187 struct btrfs_swap_info {
10188         u64 start;
10189         u64 block_start;
10190         u64 block_len;
10191         u64 lowest_ppage;
10192         u64 highest_ppage;
10193         unsigned long nr_pages;
10194         int nr_extents;
10195 };
10196
10197 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10198                                  struct btrfs_swap_info *bsi)
10199 {
10200         unsigned long nr_pages;
10201         u64 first_ppage, first_ppage_reported, next_ppage;
10202         int ret;
10203
10204         first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
10205         next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
10206                                 PAGE_SIZE) >> PAGE_SHIFT;
10207
10208         if (first_ppage >= next_ppage)
10209                 return 0;
10210         nr_pages = next_ppage - first_ppage;
10211
10212         first_ppage_reported = first_ppage;
10213         if (bsi->start == 0)
10214                 first_ppage_reported++;
10215         if (bsi->lowest_ppage > first_ppage_reported)
10216                 bsi->lowest_ppage = first_ppage_reported;
10217         if (bsi->highest_ppage < (next_ppage - 1))
10218                 bsi->highest_ppage = next_ppage - 1;
10219
10220         ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10221         if (ret < 0)
10222                 return ret;
10223         bsi->nr_extents += ret;
10224         bsi->nr_pages += nr_pages;
10225         return 0;
10226 }
10227
10228 static void btrfs_swap_deactivate(struct file *file)
10229 {
10230         struct inode *inode = file_inode(file);
10231
10232         btrfs_free_swapfile_pins(inode);
10233         atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10234 }
10235
10236 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10237                                sector_t *span)
10238 {
10239         struct inode *inode = file_inode(file);
10240         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10241         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10242         struct extent_state *cached_state = NULL;
10243         struct extent_map *em = NULL;
10244         struct btrfs_device *device = NULL;
10245         struct btrfs_swap_info bsi = {
10246                 .lowest_ppage = (sector_t)-1ULL,
10247         };
10248         int ret = 0;
10249         u64 isize;
10250         u64 start;
10251
10252         /*
10253          * If the swap file was just created, make sure delalloc is done. If the
10254          * file changes again after this, the user is doing something stupid and
10255          * we don't really care.
10256          */
10257         ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10258         if (ret)
10259                 return ret;
10260
10261         /*
10262          * The inode is locked, so these flags won't change after we check them.
10263          */
10264         if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10265                 btrfs_warn(fs_info, "swapfile must not be compressed");
10266                 return -EINVAL;
10267         }
10268         if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10269                 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10270                 return -EINVAL;
10271         }
10272         if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10273                 btrfs_warn(fs_info, "swapfile must not be checksummed");
10274                 return -EINVAL;
10275         }
10276
10277         /*
10278          * Balance or device remove/replace/resize can move stuff around from
10279          * under us. The exclop protection makes sure they aren't running/won't
10280          * run concurrently while we are mapping the swap extents, and
10281          * fs_info->swapfile_pins prevents them from running while the swap
10282          * file is active and moving the extents. Note that this also prevents
10283          * a concurrent device add which isn't actually necessary, but it's not
10284          * really worth the trouble to allow it.
10285          */
10286         if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_SWAP_ACTIVATE)) {
10287                 btrfs_warn(fs_info,
10288            "cannot activate swapfile while exclusive operation is running");
10289                 return -EBUSY;
10290         }
10291         /*
10292          * Snapshots can create extents which require COW even if NODATACOW is
10293          * set. We use this counter to prevent snapshots. We must increment it
10294          * before walking the extents because we don't want a concurrent
10295          * snapshot to run after we've already checked the extents.
10296          */
10297         atomic_inc(&BTRFS_I(inode)->root->nr_swapfiles);
10298
10299         isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10300
10301         lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
10302         start = 0;
10303         while (start < isize) {
10304                 u64 logical_block_start, physical_block_start;
10305                 struct btrfs_block_group *bg;
10306                 u64 len = isize - start;
10307
10308                 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
10309                 if (IS_ERR(em)) {
10310                         ret = PTR_ERR(em);
10311                         goto out;
10312                 }
10313
10314                 if (em->block_start == EXTENT_MAP_HOLE) {
10315                         btrfs_warn(fs_info, "swapfile must not have holes");
10316                         ret = -EINVAL;
10317                         goto out;
10318                 }
10319                 if (em->block_start == EXTENT_MAP_INLINE) {
10320                         /*
10321                          * It's unlikely we'll ever actually find ourselves
10322                          * here, as a file small enough to fit inline won't be
10323                          * big enough to store more than the swap header, but in
10324                          * case something changes in the future, let's catch it
10325                          * here rather than later.
10326                          */
10327                         btrfs_warn(fs_info, "swapfile must not be inline");
10328                         ret = -EINVAL;
10329                         goto out;
10330                 }
10331                 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10332                         btrfs_warn(fs_info, "swapfile must not be compressed");
10333                         ret = -EINVAL;
10334                         goto out;
10335                 }
10336
10337                 logical_block_start = em->block_start + (start - em->start);
10338                 len = min(len, em->len - (start - em->start));
10339                 free_extent_map(em);
10340                 em = NULL;
10341
10342                 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL, true);
10343                 if (ret < 0) {
10344                         goto out;
10345                 } else if (ret) {
10346                         ret = 0;
10347                 } else {
10348                         btrfs_warn(fs_info,
10349                                    "swapfile must not be copy-on-write");
10350                         ret = -EINVAL;
10351                         goto out;
10352                 }
10353
10354                 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10355                 if (IS_ERR(em)) {
10356                         ret = PTR_ERR(em);
10357                         goto out;
10358                 }
10359
10360                 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10361                         btrfs_warn(fs_info,
10362                                    "swapfile must have single data profile");
10363                         ret = -EINVAL;
10364                         goto out;
10365                 }
10366
10367                 if (device == NULL) {
10368                         device = em->map_lookup->stripes[0].dev;
10369                         ret = btrfs_add_swapfile_pin(inode, device, false);
10370                         if (ret == 1)
10371                                 ret = 0;
10372                         else if (ret)
10373                                 goto out;
10374                 } else if (device != em->map_lookup->stripes[0].dev) {
10375                         btrfs_warn(fs_info, "swapfile must be on one device");
10376                         ret = -EINVAL;
10377                         goto out;
10378                 }
10379
10380                 physical_block_start = (em->map_lookup->stripes[0].physical +
10381                                         (logical_block_start - em->start));
10382                 len = min(len, em->len - (logical_block_start - em->start));
10383                 free_extent_map(em);
10384                 em = NULL;
10385
10386                 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10387                 if (!bg) {
10388                         btrfs_warn(fs_info,
10389                            "could not find block group containing swapfile");
10390                         ret = -EINVAL;
10391                         goto out;
10392                 }
10393
10394                 ret = btrfs_add_swapfile_pin(inode, bg, true);
10395                 if (ret) {
10396                         btrfs_put_block_group(bg);
10397                         if (ret == 1)
10398                                 ret = 0;
10399                         else
10400                                 goto out;
10401                 }
10402
10403                 if (bsi.block_len &&
10404                     bsi.block_start + bsi.block_len == physical_block_start) {
10405                         bsi.block_len += len;
10406                 } else {
10407                         if (bsi.block_len) {
10408                                 ret = btrfs_add_swap_extent(sis, &bsi);
10409                                 if (ret)
10410                                         goto out;
10411                         }
10412                         bsi.start = start;
10413                         bsi.block_start = physical_block_start;
10414                         bsi.block_len = len;
10415                 }
10416
10417                 start += len;
10418         }
10419
10420         if (bsi.block_len)
10421                 ret = btrfs_add_swap_extent(sis, &bsi);
10422
10423 out:
10424         if (!IS_ERR_OR_NULL(em))
10425                 free_extent_map(em);
10426
10427         unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10428
10429         if (ret)
10430                 btrfs_swap_deactivate(file);
10431
10432         btrfs_exclop_finish(fs_info);
10433
10434         if (ret)
10435                 return ret;
10436
10437         if (device)
10438                 sis->bdev = device->bdev;
10439         *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10440         sis->max = bsi.nr_pages;
10441         sis->pages = bsi.nr_pages - 1;
10442         sis->highest_bit = bsi.nr_pages - 1;
10443         return bsi.nr_extents;
10444 }
10445 #else
10446 static void btrfs_swap_deactivate(struct file *file)
10447 {
10448 }
10449
10450 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10451                                sector_t *span)
10452 {
10453         return -EOPNOTSUPP;
10454 }
10455 #endif
10456
10457 /*
10458  * Update the number of bytes used in the VFS' inode. When we replace extents in
10459  * a range (clone, dedupe, fallocate's zero range), we must update the number of
10460  * bytes used by the inode in an atomic manner, so that concurrent stat(2) calls
10461  * always get a correct value.
10462  */
10463 void btrfs_update_inode_bytes(struct btrfs_inode *inode,
10464                               const u64 add_bytes,
10465                               const u64 del_bytes)
10466 {
10467         if (add_bytes == del_bytes)
10468                 return;
10469
10470         spin_lock(&inode->lock);
10471         if (del_bytes > 0)
10472                 inode_sub_bytes(&inode->vfs_inode, del_bytes);
10473         if (add_bytes > 0)
10474                 inode_add_bytes(&inode->vfs_inode, add_bytes);
10475         spin_unlock(&inode->lock);
10476 }
10477
10478 static const struct inode_operations btrfs_dir_inode_operations = {
10479         .getattr        = btrfs_getattr,
10480         .lookup         = btrfs_lookup,
10481         .create         = btrfs_create,
10482         .unlink         = btrfs_unlink,
10483         .link           = btrfs_link,
10484         .mkdir          = btrfs_mkdir,
10485         .rmdir          = btrfs_rmdir,
10486         .rename         = btrfs_rename2,
10487         .symlink        = btrfs_symlink,
10488         .setattr        = btrfs_setattr,
10489         .mknod          = btrfs_mknod,
10490         .listxattr      = btrfs_listxattr,
10491         .permission     = btrfs_permission,
10492         .get_acl        = btrfs_get_acl,
10493         .set_acl        = btrfs_set_acl,
10494         .update_time    = btrfs_update_time,
10495         .tmpfile        = btrfs_tmpfile,
10496 };
10497
10498 static const struct file_operations btrfs_dir_file_operations = {
10499         .llseek         = generic_file_llseek,
10500         .read           = generic_read_dir,
10501         .iterate_shared = btrfs_real_readdir,
10502         .open           = btrfs_opendir,
10503         .unlocked_ioctl = btrfs_ioctl,
10504 #ifdef CONFIG_COMPAT
10505         .compat_ioctl   = btrfs_compat_ioctl,
10506 #endif
10507         .release        = btrfs_release_file,
10508         .fsync          = btrfs_sync_file,
10509 };
10510
10511 /*
10512  * btrfs doesn't support the bmap operation because swapfiles
10513  * use bmap to make a mapping of extents in the file.  They assume
10514  * these extents won't change over the life of the file and they
10515  * use the bmap result to do IO directly to the drive.
10516  *
10517  * the btrfs bmap call would return logical addresses that aren't
10518  * suitable for IO and they also will change frequently as COW
10519  * operations happen.  So, swapfile + btrfs == corruption.
10520  *
10521  * For now we're avoiding this by dropping bmap.
10522  */
10523 static const struct address_space_operations btrfs_aops = {
10524         .readpage       = btrfs_readpage,
10525         .writepage      = btrfs_writepage,
10526         .writepages     = btrfs_writepages,
10527         .readahead      = btrfs_readahead,
10528         .direct_IO      = noop_direct_IO,
10529         .invalidatepage = btrfs_invalidatepage,
10530         .releasepage    = btrfs_releasepage,
10531 #ifdef CONFIG_MIGRATION
10532         .migratepage    = btrfs_migratepage,
10533 #endif
10534         .set_page_dirty = btrfs_set_page_dirty,
10535         .error_remove_page = generic_error_remove_page,
10536         .swap_activate  = btrfs_swap_activate,
10537         .swap_deactivate = btrfs_swap_deactivate,
10538 };
10539
10540 static const struct inode_operations btrfs_file_inode_operations = {
10541         .getattr        = btrfs_getattr,
10542         .setattr        = btrfs_setattr,
10543         .listxattr      = btrfs_listxattr,
10544         .permission     = btrfs_permission,
10545         .fiemap         = btrfs_fiemap,
10546         .get_acl        = btrfs_get_acl,
10547         .set_acl        = btrfs_set_acl,
10548         .update_time    = btrfs_update_time,
10549 };
10550 static const struct inode_operations btrfs_special_inode_operations = {
10551         .getattr        = btrfs_getattr,
10552         .setattr        = btrfs_setattr,
10553         .permission     = btrfs_permission,
10554         .listxattr      = btrfs_listxattr,
10555         .get_acl        = btrfs_get_acl,
10556         .set_acl        = btrfs_set_acl,
10557         .update_time    = btrfs_update_time,
10558 };
10559 static const struct inode_operations btrfs_symlink_inode_operations = {
10560         .get_link       = page_get_link,
10561         .getattr        = btrfs_getattr,
10562         .setattr        = btrfs_setattr,
10563         .permission     = btrfs_permission,
10564         .listxattr      = btrfs_listxattr,
10565         .update_time    = btrfs_update_time,
10566 };
10567
10568 const struct dentry_operations btrfs_dentry_operations = {
10569         .d_delete       = btrfs_dentry_delete,
10570 };