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