inode.c revision cceaa89f
1// SPDX-License-Identifier: GPL-2.0
2/*
3 * Copyright (C) 2007 Oracle.  All rights reserved.
4 */
5
6#include <crypto/hash.h>
7#include <linux/kernel.h>
8#include <linux/bio.h>
9#include <linux/file.h>
10#include <linux/fs.h>
11#include <linux/pagemap.h>
12#include <linux/highmem.h>
13#include <linux/time.h>
14#include <linux/init.h>
15#include <linux/string.h>
16#include <linux/backing-dev.h>
17#include <linux/writeback.h>
18#include <linux/compat.h>
19#include <linux/xattr.h>
20#include <linux/posix_acl.h>
21#include <linux/falloc.h>
22#include <linux/slab.h>
23#include <linux/ratelimit.h>
24#include <linux/btrfs.h>
25#include <linux/blkdev.h>
26#include <linux/posix_acl_xattr.h>
27#include <linux/uio.h>
28#include <linux/magic.h>
29#include <linux/iversion.h>
30#include <linux/swap.h>
31#include <linux/migrate.h>
32#include <linux/sched/mm.h>
33#include <linux/iomap.h>
34#include <asm/unaligned.h>
35#include "misc.h"
36#include "ctree.h"
37#include "disk-io.h"
38#include "transaction.h"
39#include "btrfs_inode.h"
40#include "print-tree.h"
41#include "ordered-data.h"
42#include "xattr.h"
43#include "tree-log.h"
44#include "volumes.h"
45#include "compression.h"
46#include "locking.h"
47#include "free-space-cache.h"
48#include "props.h"
49#include "qgroup.h"
50#include "delalloc-space.h"
51#include "block-group.h"
52#include "space-info.h"
53#include "zoned.h"
54#include "subpage.h"
55
56struct btrfs_iget_args {
57	u64 ino;
58	struct btrfs_root *root;
59};
60
61struct btrfs_dio_data {
62	u64 reserve;
63	loff_t length;
64	ssize_t submitted;
65	struct extent_changeset *data_reserved;
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 * btrfs_inode_lock - lock inode i_rwsem based on arguments passed
100 *
101 * ilock_flags can have the following bit set:
102 *
103 * BTRFS_ILOCK_SHARED - acquire a shared lock on the inode
104 * BTRFS_ILOCK_TRY - try to acquire the lock, if fails on first attempt
105 *		     return -EAGAIN
106 * BTRFS_ILOCK_MMAP - acquire a write lock on the i_mmap_lock
107 */
108int btrfs_inode_lock(struct inode *inode, unsigned int ilock_flags)
109{
110	if (ilock_flags & BTRFS_ILOCK_SHARED) {
111		if (ilock_flags & BTRFS_ILOCK_TRY) {
112			if (!inode_trylock_shared(inode))
113				return -EAGAIN;
114			else
115				return 0;
116		}
117		inode_lock_shared(inode);
118	} else {
119		if (ilock_flags & BTRFS_ILOCK_TRY) {
120			if (!inode_trylock(inode))
121				return -EAGAIN;
122			else
123				return 0;
124		}
125		inode_lock(inode);
126	}
127	if (ilock_flags & BTRFS_ILOCK_MMAP)
128		down_write(&BTRFS_I(inode)->i_mmap_lock);
129	return 0;
130}
131
132/*
133 * btrfs_inode_unlock - unock inode i_rwsem
134 *
135 * ilock_flags should contain the same bits set as passed to btrfs_inode_lock()
136 * to decide whether the lock acquired is shared or exclusive.
137 */
138void btrfs_inode_unlock(struct inode *inode, unsigned int ilock_flags)
139{
140	if (ilock_flags & BTRFS_ILOCK_MMAP)
141		up_write(&BTRFS_I(inode)->i_mmap_lock);
142	if (ilock_flags & BTRFS_ILOCK_SHARED)
143		inode_unlock_shared(inode);
144	else
145		inode_unlock(inode);
146}
147
148/*
149 * Cleanup all submitted ordered extents in specified range to handle errors
150 * from the btrfs_run_delalloc_range() callback.
151 *
152 * NOTE: caller must ensure that when an error happens, it can not call
153 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
154 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
155 * to be released, which we want to happen only when finishing the ordered
156 * extent (btrfs_finish_ordered_io()).
157 */
158static inline void btrfs_cleanup_ordered_extents(struct btrfs_inode *inode,
159						 struct page *locked_page,
160						 u64 offset, u64 bytes)
161{
162	unsigned long index = offset >> PAGE_SHIFT;
163	unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
164	u64 page_start = page_offset(locked_page);
165	u64 page_end = page_start + PAGE_SIZE - 1;
166
167	struct page *page;
168
169	while (index <= end_index) {
170		/*
171		 * For locked page, we will call end_extent_writepage() on it
172		 * in run_delalloc_range() for the error handling.  That
173		 * end_extent_writepage() function will call
174		 * btrfs_mark_ordered_io_finished() to clear page Ordered and
175		 * run the ordered extent accounting.
176		 *
177		 * Here we can't just clear the Ordered bit, or
178		 * btrfs_mark_ordered_io_finished() would skip the accounting
179		 * for the page range, and the ordered extent will never finish.
180		 */
181		if (index == (page_offset(locked_page) >> PAGE_SHIFT)) {
182			index++;
183			continue;
184		}
185		page = find_get_page(inode->vfs_inode.i_mapping, index);
186		index++;
187		if (!page)
188			continue;
189
190		/*
191		 * Here we just clear all Ordered bits for every page in the
192		 * range, then __endio_write_update_ordered() will handle
193		 * the ordered extent accounting for the range.
194		 */
195		btrfs_page_clamp_clear_ordered(inode->root->fs_info, page,
196					       offset, bytes);
197		put_page(page);
198	}
199
200	/* The locked page covers the full range, nothing needs to be done */
201	if (bytes + offset <= page_offset(locked_page) + PAGE_SIZE)
202		return;
203	/*
204	 * In case this page belongs to the delalloc range being instantiated
205	 * then skip it, since the first page of a range is going to be
206	 * properly cleaned up by the caller of run_delalloc_range
207	 */
208	if (page_start >= offset && page_end <= (offset + bytes - 1)) {
209		bytes = offset + bytes - page_offset(locked_page) - PAGE_SIZE;
210		offset = page_offset(locked_page) + PAGE_SIZE;
211	}
212
213	return __endio_write_update_ordered(inode, offset, bytes, false);
214}
215
216static int btrfs_dirty_inode(struct inode *inode);
217
218static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
219				     struct inode *inode,  struct inode *dir,
220				     const struct qstr *qstr)
221{
222	int err;
223
224	err = btrfs_init_acl(trans, inode, dir);
225	if (!err)
226		err = btrfs_xattr_security_init(trans, inode, dir, qstr);
227	return err;
228}
229
230/*
231 * this does all the hard work for inserting an inline extent into
232 * the btree.  The caller should have done a btrfs_drop_extents so that
233 * no overlapping inline items exist in the btree
234 */
235static int insert_inline_extent(struct btrfs_trans_handle *trans,
236				struct btrfs_path *path, bool extent_inserted,
237				struct btrfs_root *root, struct inode *inode,
238				u64 start, size_t size, size_t compressed_size,
239				int compress_type,
240				struct page **compressed_pages)
241{
242	struct extent_buffer *leaf;
243	struct page *page = NULL;
244	char *kaddr;
245	unsigned long ptr;
246	struct btrfs_file_extent_item *ei;
247	int ret;
248	size_t cur_size = size;
249	unsigned long offset;
250
251	ASSERT((compressed_size > 0 && compressed_pages) ||
252	       (compressed_size == 0 && !compressed_pages));
253
254	if (compressed_size && compressed_pages)
255		cur_size = compressed_size;
256
257	if (!extent_inserted) {
258		struct btrfs_key key;
259		size_t datasize;
260
261		key.objectid = btrfs_ino(BTRFS_I(inode));
262		key.offset = start;
263		key.type = BTRFS_EXTENT_DATA_KEY;
264
265		datasize = btrfs_file_extent_calc_inline_size(cur_size);
266		ret = btrfs_insert_empty_item(trans, root, path, &key,
267					      datasize);
268		if (ret)
269			goto fail;
270	}
271	leaf = path->nodes[0];
272	ei = btrfs_item_ptr(leaf, path->slots[0],
273			    struct btrfs_file_extent_item);
274	btrfs_set_file_extent_generation(leaf, ei, trans->transid);
275	btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
276	btrfs_set_file_extent_encryption(leaf, ei, 0);
277	btrfs_set_file_extent_other_encoding(leaf, ei, 0);
278	btrfs_set_file_extent_ram_bytes(leaf, ei, size);
279	ptr = btrfs_file_extent_inline_start(ei);
280
281	if (compress_type != BTRFS_COMPRESS_NONE) {
282		struct page *cpage;
283		int i = 0;
284		while (compressed_size > 0) {
285			cpage = compressed_pages[i];
286			cur_size = min_t(unsigned long, compressed_size,
287				       PAGE_SIZE);
288
289			kaddr = page_address(cpage);
290			write_extent_buffer(leaf, kaddr, ptr, cur_size);
291
292			i++;
293			ptr += cur_size;
294			compressed_size -= cur_size;
295		}
296		btrfs_set_file_extent_compression(leaf, ei,
297						  compress_type);
298	} else {
299		page = find_get_page(inode->i_mapping,
300				     start >> PAGE_SHIFT);
301		btrfs_set_file_extent_compression(leaf, ei, 0);
302		kaddr = kmap_atomic(page);
303		offset = offset_in_page(start);
304		write_extent_buffer(leaf, kaddr + offset, ptr, size);
305		kunmap_atomic(kaddr);
306		put_page(page);
307	}
308	btrfs_mark_buffer_dirty(leaf);
309	btrfs_release_path(path);
310
311	/*
312	 * We align size to sectorsize for inline extents just for simplicity
313	 * sake.
314	 */
315	size = ALIGN(size, root->fs_info->sectorsize);
316	ret = btrfs_inode_set_file_extent_range(BTRFS_I(inode), start, size);
317	if (ret)
318		goto fail;
319
320	/*
321	 * we're an inline extent, so nobody can
322	 * extend the file past i_size without locking
323	 * a page we already have locked.
324	 *
325	 * We must do any isize and inode updates
326	 * before we unlock the pages.  Otherwise we
327	 * could end up racing with unlink.
328	 */
329	BTRFS_I(inode)->disk_i_size = inode->i_size;
330fail:
331	return ret;
332}
333
334
335/*
336 * conditionally insert an inline extent into the file.  This
337 * does the checks required to make sure the data is small enough
338 * to fit as an inline extent.
339 */
340static noinline int cow_file_range_inline(struct btrfs_inode *inode, u64 start,
341					  u64 end, size_t compressed_size,
342					  int compress_type,
343					  struct page **compressed_pages)
344{
345	struct btrfs_drop_extents_args drop_args = { 0 };
346	struct btrfs_root *root = inode->root;
347	struct btrfs_fs_info *fs_info = root->fs_info;
348	struct btrfs_trans_handle *trans;
349	u64 isize = i_size_read(&inode->vfs_inode);
350	u64 actual_end = min(end + 1, isize);
351	u64 inline_len = actual_end - start;
352	u64 aligned_end = ALIGN(end, fs_info->sectorsize);
353	u64 data_len = inline_len;
354	int ret;
355	struct btrfs_path *path;
356
357	if (compressed_size)
358		data_len = compressed_size;
359
360	if (start > 0 ||
361	    actual_end > fs_info->sectorsize ||
362	    data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
363	    (!compressed_size &&
364	    (actual_end & (fs_info->sectorsize - 1)) == 0) ||
365	    end + 1 < isize ||
366	    data_len > fs_info->max_inline) {
367		return 1;
368	}
369
370	path = btrfs_alloc_path();
371	if (!path)
372		return -ENOMEM;
373
374	trans = btrfs_join_transaction(root);
375	if (IS_ERR(trans)) {
376		btrfs_free_path(path);
377		return PTR_ERR(trans);
378	}
379	trans->block_rsv = &inode->block_rsv;
380
381	drop_args.path = path;
382	drop_args.start = start;
383	drop_args.end = aligned_end;
384	drop_args.drop_cache = true;
385	drop_args.replace_extent = true;
386
387	if (compressed_size && compressed_pages)
388		drop_args.extent_item_size = btrfs_file_extent_calc_inline_size(
389		   compressed_size);
390	else
391		drop_args.extent_item_size = btrfs_file_extent_calc_inline_size(
392		    inline_len);
393
394	ret = btrfs_drop_extents(trans, root, inode, &drop_args);
395	if (ret) {
396		btrfs_abort_transaction(trans, ret);
397		goto out;
398	}
399
400	if (isize > actual_end)
401		inline_len = min_t(u64, isize, actual_end);
402	ret = insert_inline_extent(trans, path, drop_args.extent_inserted,
403				   root, &inode->vfs_inode, start,
404				   inline_len, compressed_size,
405				   compress_type, compressed_pages);
406	if (ret && ret != -ENOSPC) {
407		btrfs_abort_transaction(trans, ret);
408		goto out;
409	} else if (ret == -ENOSPC) {
410		ret = 1;
411		goto out;
412	}
413
414	btrfs_update_inode_bytes(inode, inline_len, drop_args.bytes_found);
415	ret = btrfs_update_inode(trans, root, inode);
416	if (ret && ret != -ENOSPC) {
417		btrfs_abort_transaction(trans, ret);
418		goto out;
419	} else if (ret == -ENOSPC) {
420		ret = 1;
421		goto out;
422	}
423
424	set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
425out:
426	/*
427	 * Don't forget to free the reserved space, as for inlined extent
428	 * it won't count as data extent, free them directly here.
429	 * And at reserve time, it's always aligned to page size, so
430	 * just free one page here.
431	 */
432	btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
433	btrfs_free_path(path);
434	btrfs_end_transaction(trans);
435	return ret;
436}
437
438struct async_extent {
439	u64 start;
440	u64 ram_size;
441	u64 compressed_size;
442	struct page **pages;
443	unsigned long nr_pages;
444	int compress_type;
445	struct list_head list;
446};
447
448struct async_chunk {
449	struct inode *inode;
450	struct page *locked_page;
451	u64 start;
452	u64 end;
453	unsigned int write_flags;
454	struct list_head extents;
455	struct cgroup_subsys_state *blkcg_css;
456	struct btrfs_work work;
457	atomic_t *pending;
458};
459
460struct async_cow {
461	/* Number of chunks in flight; must be first in the structure */
462	atomic_t num_chunks;
463	struct async_chunk chunks[];
464};
465
466static noinline int add_async_extent(struct async_chunk *cow,
467				     u64 start, u64 ram_size,
468				     u64 compressed_size,
469				     struct page **pages,
470				     unsigned long nr_pages,
471				     int compress_type)
472{
473	struct async_extent *async_extent;
474
475	async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
476	BUG_ON(!async_extent); /* -ENOMEM */
477	async_extent->start = start;
478	async_extent->ram_size = ram_size;
479	async_extent->compressed_size = compressed_size;
480	async_extent->pages = pages;
481	async_extent->nr_pages = nr_pages;
482	async_extent->compress_type = compress_type;
483	list_add_tail(&async_extent->list, &cow->extents);
484	return 0;
485}
486
487/*
488 * Check if the inode has flags compatible with compression
489 */
490static inline bool inode_can_compress(struct btrfs_inode *inode)
491{
492	if (inode->flags & BTRFS_INODE_NODATACOW ||
493	    inode->flags & BTRFS_INODE_NODATASUM)
494		return false;
495	return true;
496}
497
498/*
499 * Check if the inode needs to be submitted to compression, based on mount
500 * options, defragmentation, properties or heuristics.
501 */
502static inline int inode_need_compress(struct btrfs_inode *inode, u64 start,
503				      u64 end)
504{
505	struct btrfs_fs_info *fs_info = inode->root->fs_info;
506
507	if (!inode_can_compress(inode)) {
508		WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
509			KERN_ERR "BTRFS: unexpected compression for ino %llu\n",
510			btrfs_ino(inode));
511		return 0;
512	}
513	/* force compress */
514	if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
515		return 1;
516	/* defrag ioctl */
517	if (inode->defrag_compress)
518		return 1;
519	/* bad compression ratios */
520	if (inode->flags & BTRFS_INODE_NOCOMPRESS)
521		return 0;
522	if (btrfs_test_opt(fs_info, COMPRESS) ||
523	    inode->flags & BTRFS_INODE_COMPRESS ||
524	    inode->prop_compress)
525		return btrfs_compress_heuristic(&inode->vfs_inode, start, end);
526	return 0;
527}
528
529static inline void inode_should_defrag(struct btrfs_inode *inode,
530		u64 start, u64 end, u64 num_bytes, u64 small_write)
531{
532	/* If this is a small write inside eof, kick off a defrag */
533	if (num_bytes < small_write &&
534	    (start > 0 || end + 1 < inode->disk_i_size))
535		btrfs_add_inode_defrag(NULL, inode);
536}
537
538/*
539 * we create compressed extents in two phases.  The first
540 * phase compresses a range of pages that have already been
541 * locked (both pages and state bits are locked).
542 *
543 * This is done inside an ordered work queue, and the compression
544 * is spread across many cpus.  The actual IO submission is step
545 * two, and the ordered work queue takes care of making sure that
546 * happens in the same order things were put onto the queue by
547 * writepages and friends.
548 *
549 * If this code finds it can't get good compression, it puts an
550 * entry onto the work queue to write the uncompressed bytes.  This
551 * makes sure that both compressed inodes and uncompressed inodes
552 * are written in the same order that the flusher thread sent them
553 * down.
554 */
555static noinline int compress_file_range(struct async_chunk *async_chunk)
556{
557	struct inode *inode = async_chunk->inode;
558	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
559	u64 blocksize = fs_info->sectorsize;
560	u64 start = async_chunk->start;
561	u64 end = async_chunk->end;
562	u64 actual_end;
563	u64 i_size;
564	int ret = 0;
565	struct page **pages = NULL;
566	unsigned long nr_pages;
567	unsigned long total_compressed = 0;
568	unsigned long total_in = 0;
569	int i;
570	int will_compress;
571	int compress_type = fs_info->compress_type;
572	int compressed_extents = 0;
573	int redirty = 0;
574
575	inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
576			SZ_16K);
577
578	/*
579	 * We need to save i_size before now because it could change in between
580	 * us evaluating the size and assigning it.  This is because we lock and
581	 * unlock the page in truncate and fallocate, and then modify the i_size
582	 * later on.
583	 *
584	 * The barriers are to emulate READ_ONCE, remove that once i_size_read
585	 * does that for us.
586	 */
587	barrier();
588	i_size = i_size_read(inode);
589	barrier();
590	actual_end = min_t(u64, i_size, end + 1);
591again:
592	will_compress = 0;
593	nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
594	BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
595	nr_pages = min_t(unsigned long, nr_pages,
596			BTRFS_MAX_COMPRESSED / PAGE_SIZE);
597
598	/*
599	 * we don't want to send crud past the end of i_size through
600	 * compression, that's just a waste of CPU time.  So, if the
601	 * end of the file is before the start of our current
602	 * requested range of bytes, we bail out to the uncompressed
603	 * cleanup code that can deal with all of this.
604	 *
605	 * It isn't really the fastest way to fix things, but this is a
606	 * very uncommon corner.
607	 */
608	if (actual_end <= start)
609		goto cleanup_and_bail_uncompressed;
610
611	total_compressed = actual_end - start;
612
613	/*
614	 * skip compression for a small file range(<=blocksize) that
615	 * isn't an inline extent, since it doesn't save disk space at all.
616	 */
617	if (total_compressed <= blocksize &&
618	   (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
619		goto cleanup_and_bail_uncompressed;
620
621	total_compressed = min_t(unsigned long, total_compressed,
622			BTRFS_MAX_UNCOMPRESSED);
623	total_in = 0;
624	ret = 0;
625
626	/*
627	 * we do compression for mount -o compress and when the
628	 * inode has not been flagged as nocompress.  This flag can
629	 * change at any time if we discover bad compression ratios.
630	 */
631	if (nr_pages > 1 && inode_need_compress(BTRFS_I(inode), start, end)) {
632		WARN_ON(pages);
633		pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
634		if (!pages) {
635			/* just bail out to the uncompressed code */
636			nr_pages = 0;
637			goto cont;
638		}
639
640		if (BTRFS_I(inode)->defrag_compress)
641			compress_type = BTRFS_I(inode)->defrag_compress;
642		else if (BTRFS_I(inode)->prop_compress)
643			compress_type = BTRFS_I(inode)->prop_compress;
644
645		/*
646		 * we need to call clear_page_dirty_for_io on each
647		 * page in the range.  Otherwise applications with the file
648		 * mmap'd can wander in and change the page contents while
649		 * we are compressing them.
650		 *
651		 * If the compression fails for any reason, we set the pages
652		 * dirty again later on.
653		 *
654		 * Note that the remaining part is redirtied, the start pointer
655		 * has moved, the end is the original one.
656		 */
657		if (!redirty) {
658			extent_range_clear_dirty_for_io(inode, start, end);
659			redirty = 1;
660		}
661
662		/* Compression level is applied here and only here */
663		ret = btrfs_compress_pages(
664			compress_type | (fs_info->compress_level << 4),
665					   inode->i_mapping, start,
666					   pages,
667					   &nr_pages,
668					   &total_in,
669					   &total_compressed);
670
671		if (!ret) {
672			unsigned long offset = offset_in_page(total_compressed);
673			struct page *page = pages[nr_pages - 1];
674
675			/* zero the tail end of the last page, we might be
676			 * sending it down to disk
677			 */
678			if (offset)
679				memzero_page(page, offset, PAGE_SIZE - offset);
680			will_compress = 1;
681		}
682	}
683cont:
684	if (start == 0) {
685		/* lets try to make an inline extent */
686		if (ret || total_in < actual_end) {
687			/* we didn't compress the entire range, try
688			 * to make an uncompressed inline extent.
689			 */
690			ret = cow_file_range_inline(BTRFS_I(inode), start, end,
691						    0, BTRFS_COMPRESS_NONE,
692						    NULL);
693		} else {
694			/* try making a compressed inline extent */
695			ret = cow_file_range_inline(BTRFS_I(inode), start, end,
696						    total_compressed,
697						    compress_type, pages);
698		}
699		if (ret <= 0) {
700			unsigned long clear_flags = EXTENT_DELALLOC |
701				EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
702				EXTENT_DO_ACCOUNTING;
703			unsigned long page_error_op;
704
705			page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
706
707			/*
708			 * inline extent creation worked or returned error,
709			 * we don't need to create any more async work items.
710			 * Unlock and free up our temp pages.
711			 *
712			 * We use DO_ACCOUNTING here because we need the
713			 * delalloc_release_metadata to be done _after_ we drop
714			 * our outstanding extent for clearing delalloc for this
715			 * range.
716			 */
717			extent_clear_unlock_delalloc(BTRFS_I(inode), start, end,
718						     NULL,
719						     clear_flags,
720						     PAGE_UNLOCK |
721						     PAGE_START_WRITEBACK |
722						     page_error_op |
723						     PAGE_END_WRITEBACK);
724
725			/*
726			 * Ensure we only free the compressed pages if we have
727			 * them allocated, as we can still reach here with
728			 * inode_need_compress() == false.
729			 */
730			if (pages) {
731				for (i = 0; i < nr_pages; i++) {
732					WARN_ON(pages[i]->mapping);
733					put_page(pages[i]);
734				}
735				kfree(pages);
736			}
737			return 0;
738		}
739	}
740
741	if (will_compress) {
742		/*
743		 * we aren't doing an inline extent round the compressed size
744		 * up to a block size boundary so the allocator does sane
745		 * things
746		 */
747		total_compressed = ALIGN(total_compressed, blocksize);
748
749		/*
750		 * one last check to make sure the compression is really a
751		 * win, compare the page count read with the blocks on disk,
752		 * compression must free at least one sector size
753		 */
754		total_in = ALIGN(total_in, PAGE_SIZE);
755		if (total_compressed + blocksize <= total_in) {
756			compressed_extents++;
757
758			/*
759			 * The async work queues will take care of doing actual
760			 * allocation on disk for these compressed pages, and
761			 * will submit them to the elevator.
762			 */
763			add_async_extent(async_chunk, start, total_in,
764					total_compressed, pages, nr_pages,
765					compress_type);
766
767			if (start + total_in < end) {
768				start += total_in;
769				pages = NULL;
770				cond_resched();
771				goto again;
772			}
773			return compressed_extents;
774		}
775	}
776	if (pages) {
777		/*
778		 * the compression code ran but failed to make things smaller,
779		 * free any pages it allocated and our page pointer array
780		 */
781		for (i = 0; i < nr_pages; i++) {
782			WARN_ON(pages[i]->mapping);
783			put_page(pages[i]);
784		}
785		kfree(pages);
786		pages = NULL;
787		total_compressed = 0;
788		nr_pages = 0;
789
790		/* flag the file so we don't compress in the future */
791		if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
792		    !(BTRFS_I(inode)->prop_compress)) {
793			BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
794		}
795	}
796cleanup_and_bail_uncompressed:
797	/*
798	 * No compression, but we still need to write the pages in the file
799	 * we've been given so far.  redirty the locked page if it corresponds
800	 * to our extent and set things up for the async work queue to run
801	 * cow_file_range to do the normal delalloc dance.
802	 */
803	if (async_chunk->locked_page &&
804	    (page_offset(async_chunk->locked_page) >= start &&
805	     page_offset(async_chunk->locked_page)) <= end) {
806		__set_page_dirty_nobuffers(async_chunk->locked_page);
807		/* unlocked later on in the async handlers */
808	}
809
810	if (redirty)
811		extent_range_redirty_for_io(inode, start, end);
812	add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
813			 BTRFS_COMPRESS_NONE);
814	compressed_extents++;
815
816	return compressed_extents;
817}
818
819static void free_async_extent_pages(struct async_extent *async_extent)
820{
821	int i;
822
823	if (!async_extent->pages)
824		return;
825
826	for (i = 0; i < async_extent->nr_pages; i++) {
827		WARN_ON(async_extent->pages[i]->mapping);
828		put_page(async_extent->pages[i]);
829	}
830	kfree(async_extent->pages);
831	async_extent->nr_pages = 0;
832	async_extent->pages = NULL;
833}
834
835/*
836 * phase two of compressed writeback.  This is the ordered portion
837 * of the code, which only gets called in the order the work was
838 * queued.  We walk all the async extents created by compress_file_range
839 * and send them down to the disk.
840 */
841static noinline void submit_compressed_extents(struct async_chunk *async_chunk)
842{
843	struct btrfs_inode *inode = BTRFS_I(async_chunk->inode);
844	struct btrfs_fs_info *fs_info = inode->root->fs_info;
845	struct async_extent *async_extent;
846	u64 alloc_hint = 0;
847	struct btrfs_key ins;
848	struct extent_map *em;
849	struct btrfs_root *root = inode->root;
850	struct extent_io_tree *io_tree = &inode->io_tree;
851	int ret = 0;
852
853again:
854	while (!list_empty(&async_chunk->extents)) {
855		async_extent = list_entry(async_chunk->extents.next,
856					  struct async_extent, list);
857		list_del(&async_extent->list);
858
859retry:
860		lock_extent(io_tree, async_extent->start,
861			    async_extent->start + async_extent->ram_size - 1);
862		/* did the compression code fall back to uncompressed IO? */
863		if (!async_extent->pages) {
864			int page_started = 0;
865			unsigned long nr_written = 0;
866
867			/* allocate blocks */
868			ret = cow_file_range(inode, async_chunk->locked_page,
869					     async_extent->start,
870					     async_extent->start +
871					     async_extent->ram_size - 1,
872					     &page_started, &nr_written, 0);
873
874			/* JDM XXX */
875
876			/*
877			 * if page_started, cow_file_range inserted an
878			 * inline extent and took care of all the unlocking
879			 * and IO for us.  Otherwise, we need to submit
880			 * all those pages down to the drive.
881			 */
882			if (!page_started && !ret)
883				extent_write_locked_range(&inode->vfs_inode,
884						  async_extent->start,
885						  async_extent->start +
886						  async_extent->ram_size - 1,
887						  WB_SYNC_ALL);
888			else if (ret && async_chunk->locked_page)
889				unlock_page(async_chunk->locked_page);
890			kfree(async_extent);
891			cond_resched();
892			continue;
893		}
894
895		ret = btrfs_reserve_extent(root, async_extent->ram_size,
896					   async_extent->compressed_size,
897					   async_extent->compressed_size,
898					   0, alloc_hint, &ins, 1, 1);
899		if (ret) {
900			free_async_extent_pages(async_extent);
901
902			if (ret == -ENOSPC) {
903				unlock_extent(io_tree, async_extent->start,
904					      async_extent->start +
905					      async_extent->ram_size - 1);
906
907				/*
908				 * we need to redirty the pages if we decide to
909				 * fallback to uncompressed IO, otherwise we
910				 * will not submit these pages down to lower
911				 * layers.
912				 */
913				extent_range_redirty_for_io(&inode->vfs_inode,
914						async_extent->start,
915						async_extent->start +
916						async_extent->ram_size - 1);
917
918				goto retry;
919			}
920			goto out_free;
921		}
922		/*
923		 * here we're doing allocation and writeback of the
924		 * compressed pages
925		 */
926		em = create_io_em(inode, async_extent->start,
927				  async_extent->ram_size, /* len */
928				  async_extent->start, /* orig_start */
929				  ins.objectid, /* block_start */
930				  ins.offset, /* block_len */
931				  ins.offset, /* orig_block_len */
932				  async_extent->ram_size, /* ram_bytes */
933				  async_extent->compress_type,
934				  BTRFS_ORDERED_COMPRESSED);
935		if (IS_ERR(em))
936			/* ret value is not necessary due to void function */
937			goto out_free_reserve;
938		free_extent_map(em);
939
940		ret = btrfs_add_ordered_extent_compress(inode,
941						async_extent->start,
942						ins.objectid,
943						async_extent->ram_size,
944						ins.offset,
945						async_extent->compress_type);
946		if (ret) {
947			btrfs_drop_extent_cache(inode, async_extent->start,
948						async_extent->start +
949						async_extent->ram_size - 1, 0);
950			goto out_free_reserve;
951		}
952		btrfs_dec_block_group_reservations(fs_info, ins.objectid);
953
954		/*
955		 * clear dirty, set writeback and unlock the pages.
956		 */
957		extent_clear_unlock_delalloc(inode, async_extent->start,
958				async_extent->start +
959				async_extent->ram_size - 1,
960				NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
961				PAGE_UNLOCK | PAGE_START_WRITEBACK);
962		if (btrfs_submit_compressed_write(inode, async_extent->start,
963				    async_extent->ram_size,
964				    ins.objectid,
965				    ins.offset, async_extent->pages,
966				    async_extent->nr_pages,
967				    async_chunk->write_flags,
968				    async_chunk->blkcg_css)) {
969			struct page *p = async_extent->pages[0];
970			const u64 start = async_extent->start;
971			const u64 end = start + async_extent->ram_size - 1;
972
973			p->mapping = inode->vfs_inode.i_mapping;
974			btrfs_writepage_endio_finish_ordered(inode, p, start,
975							     end, 0);
976
977			p->mapping = NULL;
978			extent_clear_unlock_delalloc(inode, start, end, NULL, 0,
979						     PAGE_END_WRITEBACK |
980						     PAGE_SET_ERROR);
981			free_async_extent_pages(async_extent);
982		}
983		alloc_hint = ins.objectid + ins.offset;
984		kfree(async_extent);
985		cond_resched();
986	}
987	return;
988out_free_reserve:
989	btrfs_dec_block_group_reservations(fs_info, ins.objectid);
990	btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
991out_free:
992	extent_clear_unlock_delalloc(inode, async_extent->start,
993				     async_extent->start +
994				     async_extent->ram_size - 1,
995				     NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
996				     EXTENT_DELALLOC_NEW |
997				     EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
998				     PAGE_UNLOCK | PAGE_START_WRITEBACK |
999				     PAGE_END_WRITEBACK | PAGE_SET_ERROR);
1000	free_async_extent_pages(async_extent);
1001	kfree(async_extent);
1002	goto again;
1003}
1004
1005static u64 get_extent_allocation_hint(struct btrfs_inode *inode, u64 start,
1006				      u64 num_bytes)
1007{
1008	struct extent_map_tree *em_tree = &inode->extent_tree;
1009	struct extent_map *em;
1010	u64 alloc_hint = 0;
1011
1012	read_lock(&em_tree->lock);
1013	em = search_extent_mapping(em_tree, start, num_bytes);
1014	if (em) {
1015		/*
1016		 * if block start isn't an actual block number then find the
1017		 * first block in this inode and use that as a hint.  If that
1018		 * block is also bogus then just don't worry about it.
1019		 */
1020		if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
1021			free_extent_map(em);
1022			em = search_extent_mapping(em_tree, 0, 0);
1023			if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
1024				alloc_hint = em->block_start;
1025			if (em)
1026				free_extent_map(em);
1027		} else {
1028			alloc_hint = em->block_start;
1029			free_extent_map(em);
1030		}
1031	}
1032	read_unlock(&em_tree->lock);
1033
1034	return alloc_hint;
1035}
1036
1037/*
1038 * when extent_io.c finds a delayed allocation range in the file,
1039 * the call backs end up in this code.  The basic idea is to
1040 * allocate extents on disk for the range, and create ordered data structs
1041 * in ram to track those extents.
1042 *
1043 * locked_page is the page that writepage had locked already.  We use
1044 * it to make sure we don't do extra locks or unlocks.
1045 *
1046 * *page_started is set to one if we unlock locked_page and do everything
1047 * required to start IO on it.  It may be clean and already done with
1048 * IO when we return.
1049 */
1050static noinline int cow_file_range(struct btrfs_inode *inode,
1051				   struct page *locked_page,
1052				   u64 start, u64 end, int *page_started,
1053				   unsigned long *nr_written, int unlock)
1054{
1055	struct btrfs_root *root = inode->root;
1056	struct btrfs_fs_info *fs_info = root->fs_info;
1057	u64 alloc_hint = 0;
1058	u64 num_bytes;
1059	unsigned long ram_size;
1060	u64 cur_alloc_size = 0;
1061	u64 min_alloc_size;
1062	u64 blocksize = fs_info->sectorsize;
1063	struct btrfs_key ins;
1064	struct extent_map *em;
1065	unsigned clear_bits;
1066	unsigned long page_ops;
1067	bool extent_reserved = false;
1068	int ret = 0;
1069
1070	if (btrfs_is_free_space_inode(inode)) {
1071		WARN_ON_ONCE(1);
1072		ret = -EINVAL;
1073		goto out_unlock;
1074	}
1075
1076	num_bytes = ALIGN(end - start + 1, blocksize);
1077	num_bytes = max(blocksize,  num_bytes);
1078	ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
1079
1080	inode_should_defrag(inode, start, end, num_bytes, SZ_64K);
1081
1082	if (start == 0) {
1083		/* lets try to make an inline extent */
1084		ret = cow_file_range_inline(inode, start, end, 0,
1085					    BTRFS_COMPRESS_NONE, NULL);
1086		if (ret == 0) {
1087			/*
1088			 * We use DO_ACCOUNTING here because we need the
1089			 * delalloc_release_metadata to be run _after_ we drop
1090			 * our outstanding extent for clearing delalloc for this
1091			 * range.
1092			 */
1093			extent_clear_unlock_delalloc(inode, start, end,
1094				     locked_page,
1095				     EXTENT_LOCKED | EXTENT_DELALLOC |
1096				     EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1097				     EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1098				     PAGE_START_WRITEBACK | PAGE_END_WRITEBACK);
1099			*nr_written = *nr_written +
1100			     (end - start + PAGE_SIZE) / PAGE_SIZE;
1101			*page_started = 1;
1102			/*
1103			 * locked_page is locked by the caller of
1104			 * writepage_delalloc(), not locked by
1105			 * __process_pages_contig().
1106			 *
1107			 * We can't let __process_pages_contig() to unlock it,
1108			 * as it doesn't have any subpage::writers recorded.
1109			 *
1110			 * Here we manually unlock the page, since the caller
1111			 * can't use page_started to determine if it's an
1112			 * inline extent or a compressed extent.
1113			 */
1114			unlock_page(locked_page);
1115			goto out;
1116		} else if (ret < 0) {
1117			goto out_unlock;
1118		}
1119	}
1120
1121	alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1122	btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
1123
1124	/*
1125	 * Relocation relies on the relocated extents to have exactly the same
1126	 * size as the original extents. Normally writeback for relocation data
1127	 * extents follows a NOCOW path because relocation preallocates the
1128	 * extents. However, due to an operation such as scrub turning a block
1129	 * group to RO mode, it may fallback to COW mode, so we must make sure
1130	 * an extent allocated during COW has exactly the requested size and can
1131	 * not be split into smaller extents, otherwise relocation breaks and
1132	 * fails during the stage where it updates the bytenr of file extent
1133	 * items.
1134	 */
1135	if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1136		min_alloc_size = num_bytes;
1137	else
1138		min_alloc_size = fs_info->sectorsize;
1139
1140	while (num_bytes > 0) {
1141		cur_alloc_size = num_bytes;
1142		ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1143					   min_alloc_size, 0, alloc_hint,
1144					   &ins, 1, 1);
1145		if (ret < 0)
1146			goto out_unlock;
1147		cur_alloc_size = ins.offset;
1148		extent_reserved = true;
1149
1150		ram_size = ins.offset;
1151		em = create_io_em(inode, start, ins.offset, /* len */
1152				  start, /* orig_start */
1153				  ins.objectid, /* block_start */
1154				  ins.offset, /* block_len */
1155				  ins.offset, /* orig_block_len */
1156				  ram_size, /* ram_bytes */
1157				  BTRFS_COMPRESS_NONE, /* compress_type */
1158				  BTRFS_ORDERED_REGULAR /* type */);
1159		if (IS_ERR(em)) {
1160			ret = PTR_ERR(em);
1161			goto out_reserve;
1162		}
1163		free_extent_map(em);
1164
1165		ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1166					       ram_size, cur_alloc_size,
1167					       BTRFS_ORDERED_REGULAR);
1168		if (ret)
1169			goto out_drop_extent_cache;
1170
1171		if (root->root_key.objectid ==
1172		    BTRFS_DATA_RELOC_TREE_OBJECTID) {
1173			ret = btrfs_reloc_clone_csums(inode, start,
1174						      cur_alloc_size);
1175			/*
1176			 * Only drop cache here, and process as normal.
1177			 *
1178			 * We must not allow extent_clear_unlock_delalloc()
1179			 * at out_unlock label to free meta of this ordered
1180			 * extent, as its meta should be freed by
1181			 * btrfs_finish_ordered_io().
1182			 *
1183			 * So we must continue until @start is increased to
1184			 * skip current ordered extent.
1185			 */
1186			if (ret)
1187				btrfs_drop_extent_cache(inode, start,
1188						start + ram_size - 1, 0);
1189		}
1190
1191		btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1192
1193		/*
1194		 * We're not doing compressed IO, don't unlock the first page
1195		 * (which the caller expects to stay locked), don't clear any
1196		 * dirty bits and don't set any writeback bits
1197		 *
1198		 * Do set the Ordered (Private2) bit so we know this page was
1199		 * properly setup for writepage.
1200		 */
1201		page_ops = unlock ? PAGE_UNLOCK : 0;
1202		page_ops |= PAGE_SET_ORDERED;
1203
1204		extent_clear_unlock_delalloc(inode, start, start + ram_size - 1,
1205					     locked_page,
1206					     EXTENT_LOCKED | EXTENT_DELALLOC,
1207					     page_ops);
1208		if (num_bytes < cur_alloc_size)
1209			num_bytes = 0;
1210		else
1211			num_bytes -= cur_alloc_size;
1212		alloc_hint = ins.objectid + ins.offset;
1213		start += cur_alloc_size;
1214		extent_reserved = false;
1215
1216		/*
1217		 * btrfs_reloc_clone_csums() error, since start is increased
1218		 * extent_clear_unlock_delalloc() at out_unlock label won't
1219		 * free metadata of current ordered extent, we're OK to exit.
1220		 */
1221		if (ret)
1222			goto out_unlock;
1223	}
1224out:
1225	return ret;
1226
1227out_drop_extent_cache:
1228	btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0);
1229out_reserve:
1230	btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1231	btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1232out_unlock:
1233	clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1234		EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1235	page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK | PAGE_END_WRITEBACK;
1236	/*
1237	 * If we reserved an extent for our delalloc range (or a subrange) and
1238	 * failed to create the respective ordered extent, then it means that
1239	 * when we reserved the extent we decremented the extent's size from
1240	 * the data space_info's bytes_may_use counter and incremented the
1241	 * space_info's bytes_reserved counter by the same amount. We must make
1242	 * sure extent_clear_unlock_delalloc() does not try to decrement again
1243	 * the data space_info's bytes_may_use counter, therefore we do not pass
1244	 * it the flag EXTENT_CLEAR_DATA_RESV.
1245	 */
1246	if (extent_reserved) {
1247		extent_clear_unlock_delalloc(inode, start,
1248					     start + cur_alloc_size - 1,
1249					     locked_page,
1250					     clear_bits,
1251					     page_ops);
1252		start += cur_alloc_size;
1253		if (start >= end)
1254			goto out;
1255	}
1256	extent_clear_unlock_delalloc(inode, start, end, locked_page,
1257				     clear_bits | EXTENT_CLEAR_DATA_RESV,
1258				     page_ops);
1259	goto out;
1260}
1261
1262/*
1263 * work queue call back to started compression on a file and pages
1264 */
1265static noinline void async_cow_start(struct btrfs_work *work)
1266{
1267	struct async_chunk *async_chunk;
1268	int compressed_extents;
1269
1270	async_chunk = container_of(work, struct async_chunk, work);
1271
1272	compressed_extents = compress_file_range(async_chunk);
1273	if (compressed_extents == 0) {
1274		btrfs_add_delayed_iput(async_chunk->inode);
1275		async_chunk->inode = NULL;
1276	}
1277}
1278
1279/*
1280 * work queue call back to submit previously compressed pages
1281 */
1282static noinline void async_cow_submit(struct btrfs_work *work)
1283{
1284	struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1285						     work);
1286	struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1287	unsigned long nr_pages;
1288
1289	nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1290		PAGE_SHIFT;
1291
1292	/* atomic_sub_return implies a barrier */
1293	if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1294	    5 * SZ_1M)
1295		cond_wake_up_nomb(&fs_info->async_submit_wait);
1296
1297	/*
1298	 * ->inode could be NULL if async_chunk_start has failed to compress,
1299	 * in which case we don't have anything to submit, yet we need to
1300	 * always adjust ->async_delalloc_pages as its paired with the init
1301	 * happening in cow_file_range_async
1302	 */
1303	if (async_chunk->inode)
1304		submit_compressed_extents(async_chunk);
1305}
1306
1307static noinline void async_cow_free(struct btrfs_work *work)
1308{
1309	struct async_chunk *async_chunk;
1310
1311	async_chunk = container_of(work, struct async_chunk, work);
1312	if (async_chunk->inode)
1313		btrfs_add_delayed_iput(async_chunk->inode);
1314	if (async_chunk->blkcg_css)
1315		css_put(async_chunk->blkcg_css);
1316	/*
1317	 * Since the pointer to 'pending' is at the beginning of the array of
1318	 * async_chunk's, freeing it ensures the whole array has been freed.
1319	 */
1320	if (atomic_dec_and_test(async_chunk->pending))
1321		kvfree(async_chunk->pending);
1322}
1323
1324static int cow_file_range_async(struct btrfs_inode *inode,
1325				struct writeback_control *wbc,
1326				struct page *locked_page,
1327				u64 start, u64 end, int *page_started,
1328				unsigned long *nr_written)
1329{
1330	struct btrfs_fs_info *fs_info = inode->root->fs_info;
1331	struct cgroup_subsys_state *blkcg_css = wbc_blkcg_css(wbc);
1332	struct async_cow *ctx;
1333	struct async_chunk *async_chunk;
1334	unsigned long nr_pages;
1335	u64 cur_end;
1336	u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1337	int i;
1338	bool should_compress;
1339	unsigned nofs_flag;
1340	const unsigned int write_flags = wbc_to_write_flags(wbc);
1341
1342	unlock_extent(&inode->io_tree, start, end);
1343
1344	if (inode->flags & BTRFS_INODE_NOCOMPRESS &&
1345	    !btrfs_test_opt(fs_info, FORCE_COMPRESS)) {
1346		num_chunks = 1;
1347		should_compress = false;
1348	} else {
1349		should_compress = true;
1350	}
1351
1352	nofs_flag = memalloc_nofs_save();
1353	ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
1354	memalloc_nofs_restore(nofs_flag);
1355
1356	if (!ctx) {
1357		unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC |
1358			EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1359			EXTENT_DO_ACCOUNTING;
1360		unsigned long page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK |
1361					 PAGE_END_WRITEBACK | PAGE_SET_ERROR;
1362
1363		extent_clear_unlock_delalloc(inode, start, end, locked_page,
1364					     clear_bits, page_ops);
1365		return -ENOMEM;
1366	}
1367
1368	async_chunk = ctx->chunks;
1369	atomic_set(&ctx->num_chunks, num_chunks);
1370
1371	for (i = 0; i < num_chunks; i++) {
1372		if (should_compress)
1373			cur_end = min(end, start + SZ_512K - 1);
1374		else
1375			cur_end = end;
1376
1377		/*
1378		 * igrab is called higher up in the call chain, take only the
1379		 * lightweight reference for the callback lifetime
1380		 */
1381		ihold(&inode->vfs_inode);
1382		async_chunk[i].pending = &ctx->num_chunks;
1383		async_chunk[i].inode = &inode->vfs_inode;
1384		async_chunk[i].start = start;
1385		async_chunk[i].end = cur_end;
1386		async_chunk[i].write_flags = write_flags;
1387		INIT_LIST_HEAD(&async_chunk[i].extents);
1388
1389		/*
1390		 * The locked_page comes all the way from writepage and its
1391		 * the original page we were actually given.  As we spread
1392		 * this large delalloc region across multiple async_chunk
1393		 * structs, only the first struct needs a pointer to locked_page
1394		 *
1395		 * This way we don't need racey decisions about who is supposed
1396		 * to unlock it.
1397		 */
1398		if (locked_page) {
1399			/*
1400			 * Depending on the compressibility, the pages might or
1401			 * might not go through async.  We want all of them to
1402			 * be accounted against wbc once.  Let's do it here
1403			 * before the paths diverge.  wbc accounting is used
1404			 * only for foreign writeback detection and doesn't
1405			 * need full accuracy.  Just account the whole thing
1406			 * against the first page.
1407			 */
1408			wbc_account_cgroup_owner(wbc, locked_page,
1409						 cur_end - start);
1410			async_chunk[i].locked_page = locked_page;
1411			locked_page = NULL;
1412		} else {
1413			async_chunk[i].locked_page = NULL;
1414		}
1415
1416		if (blkcg_css != blkcg_root_css) {
1417			css_get(blkcg_css);
1418			async_chunk[i].blkcg_css = blkcg_css;
1419		} else {
1420			async_chunk[i].blkcg_css = NULL;
1421		}
1422
1423		btrfs_init_work(&async_chunk[i].work, async_cow_start,
1424				async_cow_submit, async_cow_free);
1425
1426		nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1427		atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1428
1429		btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1430
1431		*nr_written += nr_pages;
1432		start = cur_end + 1;
1433	}
1434	*page_started = 1;
1435	return 0;
1436}
1437
1438static noinline int run_delalloc_zoned(struct btrfs_inode *inode,
1439				       struct page *locked_page, u64 start,
1440				       u64 end, int *page_started,
1441				       unsigned long *nr_written)
1442{
1443	int ret;
1444
1445	ret = cow_file_range(inode, locked_page, start, end, page_started,
1446			     nr_written, 0);
1447	if (ret)
1448		return ret;
1449
1450	if (*page_started)
1451		return 0;
1452
1453	__set_page_dirty_nobuffers(locked_page);
1454	account_page_redirty(locked_page);
1455	extent_write_locked_range(&inode->vfs_inode, start, end, WB_SYNC_ALL);
1456	*page_started = 1;
1457
1458	return 0;
1459}
1460
1461static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1462					u64 bytenr, u64 num_bytes)
1463{
1464	int ret;
1465	struct btrfs_ordered_sum *sums;
1466	LIST_HEAD(list);
1467
1468	ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1469				       bytenr + num_bytes - 1, &list, 0);
1470	if (ret == 0 && list_empty(&list))
1471		return 0;
1472
1473	while (!list_empty(&list)) {
1474		sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1475		list_del(&sums->list);
1476		kfree(sums);
1477	}
1478	if (ret < 0)
1479		return ret;
1480	return 1;
1481}
1482
1483static int fallback_to_cow(struct btrfs_inode *inode, struct page *locked_page,
1484			   const u64 start, const u64 end,
1485			   int *page_started, unsigned long *nr_written)
1486{
1487	const bool is_space_ino = btrfs_is_free_space_inode(inode);
1488	const bool is_reloc_ino = (inode->root->root_key.objectid ==
1489				   BTRFS_DATA_RELOC_TREE_OBJECTID);
1490	const u64 range_bytes = end + 1 - start;
1491	struct extent_io_tree *io_tree = &inode->io_tree;
1492	u64 range_start = start;
1493	u64 count;
1494
1495	/*
1496	 * If EXTENT_NORESERVE is set it means that when the buffered write was
1497	 * made we had not enough available data space and therefore we did not
1498	 * reserve data space for it, since we though we could do NOCOW for the
1499	 * respective file range (either there is prealloc extent or the inode
1500	 * has the NOCOW bit set).
1501	 *
1502	 * However when we need to fallback to COW mode (because for example the
1503	 * block group for the corresponding extent was turned to RO mode by a
1504	 * scrub or relocation) we need to do the following:
1505	 *
1506	 * 1) We increment the bytes_may_use counter of the data space info.
1507	 *    If COW succeeds, it allocates a new data extent and after doing
1508	 *    that it decrements the space info's bytes_may_use counter and
1509	 *    increments its bytes_reserved counter by the same amount (we do
1510	 *    this at btrfs_add_reserved_bytes()). So we need to increment the
1511	 *    bytes_may_use counter to compensate (when space is reserved at
1512	 *    buffered write time, the bytes_may_use counter is incremented);
1513	 *
1514	 * 2) We clear the EXTENT_NORESERVE bit from the range. We do this so
1515	 *    that if the COW path fails for any reason, it decrements (through
1516	 *    extent_clear_unlock_delalloc()) the bytes_may_use counter of the
1517	 *    data space info, which we incremented in the step above.
1518	 *
1519	 * If we need to fallback to cow and the inode corresponds to a free
1520	 * space cache inode or an inode of the data relocation tree, we must
1521	 * also increment bytes_may_use of the data space_info for the same
1522	 * reason. Space caches and relocated data extents always get a prealloc
1523	 * extent for them, however scrub or balance may have set the block
1524	 * group that contains that extent to RO mode and therefore force COW
1525	 * when starting writeback.
1526	 */
1527	count = count_range_bits(io_tree, &range_start, end, range_bytes,
1528				 EXTENT_NORESERVE, 0);
1529	if (count > 0 || is_space_ino || is_reloc_ino) {
1530		u64 bytes = count;
1531		struct btrfs_fs_info *fs_info = inode->root->fs_info;
1532		struct btrfs_space_info *sinfo = fs_info->data_sinfo;
1533
1534		if (is_space_ino || is_reloc_ino)
1535			bytes = range_bytes;
1536
1537		spin_lock(&sinfo->lock);
1538		btrfs_space_info_update_bytes_may_use(fs_info, sinfo, bytes);
1539		spin_unlock(&sinfo->lock);
1540
1541		if (count > 0)
1542			clear_extent_bit(io_tree, start, end, EXTENT_NORESERVE,
1543					 0, 0, NULL);
1544	}
1545
1546	return cow_file_range(inode, locked_page, start, end, page_started,
1547			      nr_written, 1);
1548}
1549
1550/*
1551 * when nowcow writeback call back.  This checks for snapshots or COW copies
1552 * of the extents that exist in the file, and COWs the file as required.
1553 *
1554 * If no cow copies or snapshots exist, we write directly to the existing
1555 * blocks on disk
1556 */
1557static noinline int run_delalloc_nocow(struct btrfs_inode *inode,
1558				       struct page *locked_page,
1559				       const u64 start, const u64 end,
1560				       int *page_started,
1561				       unsigned long *nr_written)
1562{
1563	struct btrfs_fs_info *fs_info = inode->root->fs_info;
1564	struct btrfs_root *root = inode->root;
1565	struct btrfs_path *path;
1566	u64 cow_start = (u64)-1;
1567	u64 cur_offset = start;
1568	int ret;
1569	bool check_prev = true;
1570	const bool freespace_inode = btrfs_is_free_space_inode(inode);
1571	u64 ino = btrfs_ino(inode);
1572	bool nocow = false;
1573	u64 disk_bytenr = 0;
1574	const bool force = inode->flags & BTRFS_INODE_NODATACOW;
1575
1576	path = btrfs_alloc_path();
1577	if (!path) {
1578		extent_clear_unlock_delalloc(inode, start, end, locked_page,
1579					     EXTENT_LOCKED | EXTENT_DELALLOC |
1580					     EXTENT_DO_ACCOUNTING |
1581					     EXTENT_DEFRAG, PAGE_UNLOCK |
1582					     PAGE_START_WRITEBACK |
1583					     PAGE_END_WRITEBACK);
1584		return -ENOMEM;
1585	}
1586
1587	while (1) {
1588		struct btrfs_key found_key;
1589		struct btrfs_file_extent_item *fi;
1590		struct extent_buffer *leaf;
1591		u64 extent_end;
1592		u64 extent_offset;
1593		u64 num_bytes = 0;
1594		u64 disk_num_bytes;
1595		u64 ram_bytes;
1596		int extent_type;
1597
1598		nocow = false;
1599
1600		ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1601					       cur_offset, 0);
1602		if (ret < 0)
1603			goto error;
1604
1605		/*
1606		 * If there is no extent for our range when doing the initial
1607		 * search, then go back to the previous slot as it will be the
1608		 * one containing the search offset
1609		 */
1610		if (ret > 0 && path->slots[0] > 0 && check_prev) {
1611			leaf = path->nodes[0];
1612			btrfs_item_key_to_cpu(leaf, &found_key,
1613					      path->slots[0] - 1);
1614			if (found_key.objectid == ino &&
1615			    found_key.type == BTRFS_EXTENT_DATA_KEY)
1616				path->slots[0]--;
1617		}
1618		check_prev = false;
1619next_slot:
1620		/* Go to next leaf if we have exhausted the current one */
1621		leaf = path->nodes[0];
1622		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1623			ret = btrfs_next_leaf(root, path);
1624			if (ret < 0) {
1625				if (cow_start != (u64)-1)
1626					cur_offset = cow_start;
1627				goto error;
1628			}
1629			if (ret > 0)
1630				break;
1631			leaf = path->nodes[0];
1632		}
1633
1634		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1635
1636		/* Didn't find anything for our INO */
1637		if (found_key.objectid > ino)
1638			break;
1639		/*
1640		 * Keep searching until we find an EXTENT_ITEM or there are no
1641		 * more extents for this inode
1642		 */
1643		if (WARN_ON_ONCE(found_key.objectid < ino) ||
1644		    found_key.type < BTRFS_EXTENT_DATA_KEY) {
1645			path->slots[0]++;
1646			goto next_slot;
1647		}
1648
1649		/* Found key is not EXTENT_DATA_KEY or starts after req range */
1650		if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1651		    found_key.offset > end)
1652			break;
1653
1654		/*
1655		 * If the found extent starts after requested offset, then
1656		 * adjust extent_end to be right before this extent begins
1657		 */
1658		if (found_key.offset > cur_offset) {
1659			extent_end = found_key.offset;
1660			extent_type = 0;
1661			goto out_check;
1662		}
1663
1664		/*
1665		 * Found extent which begins before our range and potentially
1666		 * intersect it
1667		 */
1668		fi = btrfs_item_ptr(leaf, path->slots[0],
1669				    struct btrfs_file_extent_item);
1670		extent_type = btrfs_file_extent_type(leaf, fi);
1671
1672		ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1673		if (extent_type == BTRFS_FILE_EXTENT_REG ||
1674		    extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1675			disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1676			extent_offset = btrfs_file_extent_offset(leaf, fi);
1677			extent_end = found_key.offset +
1678				btrfs_file_extent_num_bytes(leaf, fi);
1679			disk_num_bytes =
1680				btrfs_file_extent_disk_num_bytes(leaf, fi);
1681			/*
1682			 * If the extent we got ends before our current offset,
1683			 * skip to the next extent.
1684			 */
1685			if (extent_end <= cur_offset) {
1686				path->slots[0]++;
1687				goto next_slot;
1688			}
1689			/* Skip holes */
1690			if (disk_bytenr == 0)
1691				goto out_check;
1692			/* Skip compressed/encrypted/encoded extents */
1693			if (btrfs_file_extent_compression(leaf, fi) ||
1694			    btrfs_file_extent_encryption(leaf, fi) ||
1695			    btrfs_file_extent_other_encoding(leaf, fi))
1696				goto out_check;
1697			/*
1698			 * If extent is created before the last volume's snapshot
1699			 * this implies the extent is shared, hence we can't do
1700			 * nocow. This is the same check as in
1701			 * btrfs_cross_ref_exist but without calling
1702			 * btrfs_search_slot.
1703			 */
1704			if (!freespace_inode &&
1705			    btrfs_file_extent_generation(leaf, fi) <=
1706			    btrfs_root_last_snapshot(&root->root_item))
1707				goto out_check;
1708			if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1709				goto out_check;
1710
1711			/*
1712			 * The following checks can be expensive, as they need to
1713			 * take other locks and do btree or rbtree searches, so
1714			 * release the path to avoid blocking other tasks for too
1715			 * long.
1716			 */
1717			btrfs_release_path(path);
1718
1719			ret = btrfs_cross_ref_exist(root, ino,
1720						    found_key.offset -
1721						    extent_offset, disk_bytenr, false);
1722			if (ret) {
1723				/*
1724				 * ret could be -EIO if the above fails to read
1725				 * metadata.
1726				 */
1727				if (ret < 0) {
1728					if (cow_start != (u64)-1)
1729						cur_offset = cow_start;
1730					goto error;
1731				}
1732
1733				WARN_ON_ONCE(freespace_inode);
1734				goto out_check;
1735			}
1736			disk_bytenr += extent_offset;
1737			disk_bytenr += cur_offset - found_key.offset;
1738			num_bytes = min(end + 1, extent_end) - cur_offset;
1739			/*
1740			 * If there are pending snapshots for this root, we
1741			 * fall into common COW way
1742			 */
1743			if (!freespace_inode && atomic_read(&root->snapshot_force_cow))
1744				goto out_check;
1745			/*
1746			 * force cow if csum exists in the range.
1747			 * this ensure that csum for a given extent are
1748			 * either valid or do not exist.
1749			 */
1750			ret = csum_exist_in_range(fs_info, disk_bytenr,
1751						  num_bytes);
1752			if (ret) {
1753				/*
1754				 * ret could be -EIO if the above fails to read
1755				 * metadata.
1756				 */
1757				if (ret < 0) {
1758					if (cow_start != (u64)-1)
1759						cur_offset = cow_start;
1760					goto error;
1761				}
1762				WARN_ON_ONCE(freespace_inode);
1763				goto out_check;
1764			}
1765			/* If the extent's block group is RO, we must COW */
1766			if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1767				goto out_check;
1768			nocow = true;
1769		} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1770			extent_end = found_key.offset + ram_bytes;
1771			extent_end = ALIGN(extent_end, fs_info->sectorsize);
1772			/* Skip extents outside of our requested range */
1773			if (extent_end <= start) {
1774				path->slots[0]++;
1775				goto next_slot;
1776			}
1777		} else {
1778			/* If this triggers then we have a memory corruption */
1779			BUG();
1780		}
1781out_check:
1782		/*
1783		 * If nocow is false then record the beginning of the range
1784		 * that needs to be COWed
1785		 */
1786		if (!nocow) {
1787			if (cow_start == (u64)-1)
1788				cow_start = cur_offset;
1789			cur_offset = extent_end;
1790			if (cur_offset > end)
1791				break;
1792			if (!path->nodes[0])
1793				continue;
1794			path->slots[0]++;
1795			goto next_slot;
1796		}
1797
1798		/*
1799		 * COW range from cow_start to found_key.offset - 1. As the key
1800		 * will contain the beginning of the first extent that can be
1801		 * NOCOW, following one which needs to be COW'ed
1802		 */
1803		if (cow_start != (u64)-1) {
1804			ret = fallback_to_cow(inode, locked_page,
1805					      cow_start, found_key.offset - 1,
1806					      page_started, nr_written);
1807			if (ret)
1808				goto error;
1809			cow_start = (u64)-1;
1810		}
1811
1812		if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1813			u64 orig_start = found_key.offset - extent_offset;
1814			struct extent_map *em;
1815
1816			em = create_io_em(inode, cur_offset, num_bytes,
1817					  orig_start,
1818					  disk_bytenr, /* block_start */
1819					  num_bytes, /* block_len */
1820					  disk_num_bytes, /* orig_block_len */
1821					  ram_bytes, BTRFS_COMPRESS_NONE,
1822					  BTRFS_ORDERED_PREALLOC);
1823			if (IS_ERR(em)) {
1824				ret = PTR_ERR(em);
1825				goto error;
1826			}
1827			free_extent_map(em);
1828			ret = btrfs_add_ordered_extent(inode, cur_offset,
1829						       disk_bytenr, num_bytes,
1830						       num_bytes,
1831						       BTRFS_ORDERED_PREALLOC);
1832			if (ret) {
1833				btrfs_drop_extent_cache(inode, cur_offset,
1834							cur_offset + num_bytes - 1,
1835							0);
1836				goto error;
1837			}
1838		} else {
1839			ret = btrfs_add_ordered_extent(inode, cur_offset,
1840						       disk_bytenr, num_bytes,
1841						       num_bytes,
1842						       BTRFS_ORDERED_NOCOW);
1843			if (ret)
1844				goto error;
1845		}
1846
1847		if (nocow)
1848			btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1849		nocow = false;
1850
1851		if (root->root_key.objectid ==
1852		    BTRFS_DATA_RELOC_TREE_OBJECTID)
1853			/*
1854			 * Error handled later, as we must prevent
1855			 * extent_clear_unlock_delalloc() in error handler
1856			 * from freeing metadata of created ordered extent.
1857			 */
1858			ret = btrfs_reloc_clone_csums(inode, cur_offset,
1859						      num_bytes);
1860
1861		extent_clear_unlock_delalloc(inode, cur_offset,
1862					     cur_offset + num_bytes - 1,
1863					     locked_page, EXTENT_LOCKED |
1864					     EXTENT_DELALLOC |
1865					     EXTENT_CLEAR_DATA_RESV,
1866					     PAGE_UNLOCK | PAGE_SET_ORDERED);
1867
1868		cur_offset = extent_end;
1869
1870		/*
1871		 * btrfs_reloc_clone_csums() error, now we're OK to call error
1872		 * handler, as metadata for created ordered extent will only
1873		 * be freed by btrfs_finish_ordered_io().
1874		 */
1875		if (ret)
1876			goto error;
1877		if (cur_offset > end)
1878			break;
1879	}
1880	btrfs_release_path(path);
1881
1882	if (cur_offset <= end && cow_start == (u64)-1)
1883		cow_start = cur_offset;
1884
1885	if (cow_start != (u64)-1) {
1886		cur_offset = end;
1887		ret = fallback_to_cow(inode, locked_page, cow_start, end,
1888				      page_started, nr_written);
1889		if (ret)
1890			goto error;
1891	}
1892
1893error:
1894	if (nocow)
1895		btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1896
1897	if (ret && cur_offset < end)
1898		extent_clear_unlock_delalloc(inode, cur_offset, end,
1899					     locked_page, EXTENT_LOCKED |
1900					     EXTENT_DELALLOC | EXTENT_DEFRAG |
1901					     EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1902					     PAGE_START_WRITEBACK |
1903					     PAGE_END_WRITEBACK);
1904	btrfs_free_path(path);
1905	return ret;
1906}
1907
1908static bool should_nocow(struct btrfs_inode *inode, u64 start, u64 end)
1909{
1910	if (inode->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)) {
1911		if (inode->defrag_bytes &&
1912		    test_range_bit(&inode->io_tree, start, end, EXTENT_DEFRAG,
1913				   0, NULL))
1914			return false;
1915		return true;
1916	}
1917	return false;
1918}
1919
1920/*
1921 * Function to process delayed allocation (create CoW) for ranges which are
1922 * being touched for the first time.
1923 */
1924int btrfs_run_delalloc_range(struct btrfs_inode *inode, struct page *locked_page,
1925		u64 start, u64 end, int *page_started, unsigned long *nr_written,
1926		struct writeback_control *wbc)
1927{
1928	int ret;
1929	const bool zoned = btrfs_is_zoned(inode->root->fs_info);
1930
1931	if (should_nocow(inode, start, end)) {
1932		ASSERT(!zoned);
1933		ret = run_delalloc_nocow(inode, locked_page, start, end,
1934					 page_started, nr_written);
1935	} else if (!inode_can_compress(inode) ||
1936		   !inode_need_compress(inode, start, end)) {
1937		if (zoned)
1938			ret = run_delalloc_zoned(inode, locked_page, start, end,
1939						 page_started, nr_written);
1940		else
1941			ret = cow_file_range(inode, locked_page, start, end,
1942					     page_started, nr_written, 1);
1943	} else {
1944		set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &inode->runtime_flags);
1945		ret = cow_file_range_async(inode, wbc, locked_page, start, end,
1946					   page_started, nr_written);
1947	}
1948	if (ret)
1949		btrfs_cleanup_ordered_extents(inode, locked_page, start,
1950					      end - start + 1);
1951	return ret;
1952}
1953
1954void btrfs_split_delalloc_extent(struct inode *inode,
1955				 struct extent_state *orig, u64 split)
1956{
1957	u64 size;
1958
1959	/* not delalloc, ignore it */
1960	if (!(orig->state & EXTENT_DELALLOC))
1961		return;
1962
1963	size = orig->end - orig->start + 1;
1964	if (size > BTRFS_MAX_EXTENT_SIZE) {
1965		u32 num_extents;
1966		u64 new_size;
1967
1968		/*
1969		 * See the explanation in btrfs_merge_delalloc_extent, the same
1970		 * applies here, just in reverse.
1971		 */
1972		new_size = orig->end - split + 1;
1973		num_extents = count_max_extents(new_size);
1974		new_size = split - orig->start;
1975		num_extents += count_max_extents(new_size);
1976		if (count_max_extents(size) >= num_extents)
1977			return;
1978	}
1979
1980	spin_lock(&BTRFS_I(inode)->lock);
1981	btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1982	spin_unlock(&BTRFS_I(inode)->lock);
1983}
1984
1985/*
1986 * Handle merged delayed allocation extents so we can keep track of new extents
1987 * that are just merged onto old extents, such as when we are doing sequential
1988 * writes, so we can properly account for the metadata space we'll need.
1989 */
1990void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
1991				 struct extent_state *other)
1992{
1993	u64 new_size, old_size;
1994	u32 num_extents;
1995
1996	/* not delalloc, ignore it */
1997	if (!(other->state & EXTENT_DELALLOC))
1998		return;
1999
2000	if (new->start > other->start)
2001		new_size = new->end - other->start + 1;
2002	else
2003		new_size = other->end - new->start + 1;
2004
2005	/* we're not bigger than the max, unreserve the space and go */
2006	if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
2007		spin_lock(&BTRFS_I(inode)->lock);
2008		btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
2009		spin_unlock(&BTRFS_I(inode)->lock);
2010		return;
2011	}
2012
2013	/*
2014	 * We have to add up either side to figure out how many extents were
2015	 * accounted for before we merged into one big extent.  If the number of
2016	 * extents we accounted for is <= the amount we need for the new range
2017	 * then we can return, otherwise drop.  Think of it like this
2018	 *
2019	 * [ 4k][MAX_SIZE]
2020	 *
2021	 * So we've grown the extent by a MAX_SIZE extent, this would mean we
2022	 * need 2 outstanding extents, on one side we have 1 and the other side
2023	 * we have 1 so they are == and we can return.  But in this case
2024	 *
2025	 * [MAX_SIZE+4k][MAX_SIZE+4k]
2026	 *
2027	 * Each range on their own accounts for 2 extents, but merged together
2028	 * they are only 3 extents worth of accounting, so we need to drop in
2029	 * this case.
2030	 */
2031	old_size = other->end - other->start + 1;
2032	num_extents = count_max_extents(old_size);
2033	old_size = new->end - new->start + 1;
2034	num_extents += count_max_extents(old_size);
2035	if (count_max_extents(new_size) >= num_extents)
2036		return;
2037
2038	spin_lock(&BTRFS_I(inode)->lock);
2039	btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
2040	spin_unlock(&BTRFS_I(inode)->lock);
2041}
2042
2043static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
2044				      struct inode *inode)
2045{
2046	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2047
2048	spin_lock(&root->delalloc_lock);
2049	if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
2050		list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
2051			      &root->delalloc_inodes);
2052		set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2053			&BTRFS_I(inode)->runtime_flags);
2054		root->nr_delalloc_inodes++;
2055		if (root->nr_delalloc_inodes == 1) {
2056			spin_lock(&fs_info->delalloc_root_lock);
2057			BUG_ON(!list_empty(&root->delalloc_root));
2058			list_add_tail(&root->delalloc_root,
2059				      &fs_info->delalloc_roots);
2060			spin_unlock(&fs_info->delalloc_root_lock);
2061		}
2062	}
2063	spin_unlock(&root->delalloc_lock);
2064}
2065
2066
2067void __btrfs_del_delalloc_inode(struct btrfs_root *root,
2068				struct btrfs_inode *inode)
2069{
2070	struct btrfs_fs_info *fs_info = root->fs_info;
2071
2072	if (!list_empty(&inode->delalloc_inodes)) {
2073		list_del_init(&inode->delalloc_inodes);
2074		clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2075			  &inode->runtime_flags);
2076		root->nr_delalloc_inodes--;
2077		if (!root->nr_delalloc_inodes) {
2078			ASSERT(list_empty(&root->delalloc_inodes));
2079			spin_lock(&fs_info->delalloc_root_lock);
2080			BUG_ON(list_empty(&root->delalloc_root));
2081			list_del_init(&root->delalloc_root);
2082			spin_unlock(&fs_info->delalloc_root_lock);
2083		}
2084	}
2085}
2086
2087static void btrfs_del_delalloc_inode(struct btrfs_root *root,
2088				     struct btrfs_inode *inode)
2089{
2090	spin_lock(&root->delalloc_lock);
2091	__btrfs_del_delalloc_inode(root, inode);
2092	spin_unlock(&root->delalloc_lock);
2093}
2094
2095/*
2096 * Properly track delayed allocation bytes in the inode and to maintain the
2097 * list of inodes that have pending delalloc work to be done.
2098 */
2099void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
2100			       unsigned *bits)
2101{
2102	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2103
2104	if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
2105		WARN_ON(1);
2106	/*
2107	 * set_bit and clear bit hooks normally require _irqsave/restore
2108	 * but in this case, we are only testing for the DELALLOC
2109	 * bit, which is only set or cleared with irqs on
2110	 */
2111	if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
2112		struct btrfs_root *root = BTRFS_I(inode)->root;
2113		u64 len = state->end + 1 - state->start;
2114		u32 num_extents = count_max_extents(len);
2115		bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
2116
2117		spin_lock(&BTRFS_I(inode)->lock);
2118		btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
2119		spin_unlock(&BTRFS_I(inode)->lock);
2120
2121		/* For sanity tests */
2122		if (btrfs_is_testing(fs_info))
2123			return;
2124
2125		percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
2126					 fs_info->delalloc_batch);
2127		spin_lock(&BTRFS_I(inode)->lock);
2128		BTRFS_I(inode)->delalloc_bytes += len;
2129		if (*bits & EXTENT_DEFRAG)
2130			BTRFS_I(inode)->defrag_bytes += len;
2131		if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2132					 &BTRFS_I(inode)->runtime_flags))
2133			btrfs_add_delalloc_inodes(root, inode);
2134		spin_unlock(&BTRFS_I(inode)->lock);
2135	}
2136
2137	if (!(state->state & EXTENT_DELALLOC_NEW) &&
2138	    (*bits & EXTENT_DELALLOC_NEW)) {
2139		spin_lock(&BTRFS_I(inode)->lock);
2140		BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
2141			state->start;
2142		spin_unlock(&BTRFS_I(inode)->lock);
2143	}
2144}
2145
2146/*
2147 * Once a range is no longer delalloc this function ensures that proper
2148 * accounting happens.
2149 */
2150void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
2151				 struct extent_state *state, unsigned *bits)
2152{
2153	struct btrfs_inode *inode = BTRFS_I(vfs_inode);
2154	struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
2155	u64 len = state->end + 1 - state->start;
2156	u32 num_extents = count_max_extents(len);
2157
2158	if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
2159		spin_lock(&inode->lock);
2160		inode->defrag_bytes -= len;
2161		spin_unlock(&inode->lock);
2162	}
2163
2164	/*
2165	 * set_bit and clear bit hooks normally require _irqsave/restore
2166	 * but in this case, we are only testing for the DELALLOC
2167	 * bit, which is only set or cleared with irqs on
2168	 */
2169	if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
2170		struct btrfs_root *root = inode->root;
2171		bool do_list = !btrfs_is_free_space_inode(inode);
2172
2173		spin_lock(&inode->lock);
2174		btrfs_mod_outstanding_extents(inode, -num_extents);
2175		spin_unlock(&inode->lock);
2176
2177		/*
2178		 * We don't reserve metadata space for space cache inodes so we
2179		 * don't need to call delalloc_release_metadata if there is an
2180		 * error.
2181		 */
2182		if (*bits & EXTENT_CLEAR_META_RESV &&
2183		    root != fs_info->tree_root)
2184			btrfs_delalloc_release_metadata(inode, len, false);
2185
2186		/* For sanity tests. */
2187		if (btrfs_is_testing(fs_info))
2188			return;
2189
2190		if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
2191		    do_list && !(state->state & EXTENT_NORESERVE) &&
2192		    (*bits & EXTENT_CLEAR_DATA_RESV))
2193			btrfs_free_reserved_data_space_noquota(fs_info, len);
2194
2195		percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
2196					 fs_info->delalloc_batch);
2197		spin_lock(&inode->lock);
2198		inode->delalloc_bytes -= len;
2199		if (do_list && inode->delalloc_bytes == 0 &&
2200		    test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2201					&inode->runtime_flags))
2202			btrfs_del_delalloc_inode(root, inode);
2203		spin_unlock(&inode->lock);
2204	}
2205
2206	if ((state->state & EXTENT_DELALLOC_NEW) &&
2207	    (*bits & EXTENT_DELALLOC_NEW)) {
2208		spin_lock(&inode->lock);
2209		ASSERT(inode->new_delalloc_bytes >= len);
2210		inode->new_delalloc_bytes -= len;
2211		if (*bits & EXTENT_ADD_INODE_BYTES)
2212			inode_add_bytes(&inode->vfs_inode, len);
2213		spin_unlock(&inode->lock);
2214	}
2215}
2216
2217/*
2218 * btrfs_bio_fits_in_stripe - Checks whether the size of the given bio will fit
2219 * in a chunk's stripe. This function ensures that bios do not span a
2220 * stripe/chunk
2221 *
2222 * @page - The page we are about to add to the bio
2223 * @size - size we want to add to the bio
2224 * @bio - bio we want to ensure is smaller than a stripe
2225 * @bio_flags - flags of the bio
2226 *
2227 * return 1 if page cannot be added to the bio
2228 * return 0 if page can be added to the bio
2229 * return error otherwise
2230 */
2231int btrfs_bio_fits_in_stripe(struct page *page, size_t size, struct bio *bio,
2232			     unsigned long bio_flags)
2233{
2234	struct inode *inode = page->mapping->host;
2235	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2236	u64 logical = bio->bi_iter.bi_sector << 9;
2237	u32 bio_len = bio->bi_iter.bi_size;
2238	struct extent_map *em;
2239	int ret = 0;
2240	struct btrfs_io_geometry geom;
2241
2242	if (bio_flags & EXTENT_BIO_COMPRESSED)
2243		return 0;
2244
2245	em = btrfs_get_chunk_map(fs_info, logical, fs_info->sectorsize);
2246	if (IS_ERR(em))
2247		return PTR_ERR(em);
2248	ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(bio), logical, &geom);
2249	if (ret < 0)
2250		goto out;
2251
2252	if (geom.len < bio_len + size)
2253		ret = 1;
2254out:
2255	free_extent_map(em);
2256	return ret;
2257}
2258
2259/*
2260 * in order to insert checksums into the metadata in large chunks,
2261 * we wait until bio submission time.   All the pages in the bio are
2262 * checksummed and sums are attached onto the ordered extent record.
2263 *
2264 * At IO completion time the cums attached on the ordered extent record
2265 * are inserted into the btree
2266 */
2267static blk_status_t btrfs_submit_bio_start(struct inode *inode, struct bio *bio,
2268					   u64 dio_file_offset)
2269{
2270	return btrfs_csum_one_bio(BTRFS_I(inode), bio, 0, 0);
2271}
2272
2273/*
2274 * Split an extent_map at [start, start + len]
2275 *
2276 * This function is intended to be used only for extract_ordered_extent().
2277 */
2278static int split_zoned_em(struct btrfs_inode *inode, u64 start, u64 len,
2279			  u64 pre, u64 post)
2280{
2281	struct extent_map_tree *em_tree = &inode->extent_tree;
2282	struct extent_map *em;
2283	struct extent_map *split_pre = NULL;
2284	struct extent_map *split_mid = NULL;
2285	struct extent_map *split_post = NULL;
2286	int ret = 0;
2287	int modified;
2288	unsigned long flags;
2289
2290	/* Sanity check */
2291	if (pre == 0 && post == 0)
2292		return 0;
2293
2294	split_pre = alloc_extent_map();
2295	if (pre)
2296		split_mid = alloc_extent_map();
2297	if (post)
2298		split_post = alloc_extent_map();
2299	if (!split_pre || (pre && !split_mid) || (post && !split_post)) {
2300		ret = -ENOMEM;
2301		goto out;
2302	}
2303
2304	ASSERT(pre + post < len);
2305
2306	lock_extent(&inode->io_tree, start, start + len - 1);
2307	write_lock(&em_tree->lock);
2308	em = lookup_extent_mapping(em_tree, start, len);
2309	if (!em) {
2310		ret = -EIO;
2311		goto out_unlock;
2312	}
2313
2314	ASSERT(em->len == len);
2315	ASSERT(!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags));
2316	ASSERT(em->block_start < EXTENT_MAP_LAST_BYTE);
2317
2318	flags = em->flags;
2319	clear_bit(EXTENT_FLAG_PINNED, &em->flags);
2320	clear_bit(EXTENT_FLAG_LOGGING, &flags);
2321	modified = !list_empty(&em->list);
2322
2323	/* First, replace the em with a new extent_map starting from * em->start */
2324	split_pre->start = em->start;
2325	split_pre->len = (pre ? pre : em->len - post);
2326	split_pre->orig_start = split_pre->start;
2327	split_pre->block_start = em->block_start;
2328	split_pre->block_len = split_pre->len;
2329	split_pre->orig_block_len = split_pre->block_len;
2330	split_pre->ram_bytes = split_pre->len;
2331	split_pre->flags = flags;
2332	split_pre->compress_type = em->compress_type;
2333	split_pre->generation = em->generation;
2334
2335	replace_extent_mapping(em_tree, em, split_pre, modified);
2336
2337	/*
2338	 * Now we only have an extent_map at:
2339	 *     [em->start, em->start + pre] if pre != 0
2340	 *     [em->start, em->start + em->len - post] if pre == 0
2341	 */
2342
2343	if (pre) {
2344		/* Insert the middle extent_map */
2345		split_mid->start = em->start + pre;
2346		split_mid->len = em->len - pre - post;
2347		split_mid->orig_start = split_mid->start;
2348		split_mid->block_start = em->block_start + pre;
2349		split_mid->block_len = split_mid->len;
2350		split_mid->orig_block_len = split_mid->block_len;
2351		split_mid->ram_bytes = split_mid->len;
2352		split_mid->flags = flags;
2353		split_mid->compress_type = em->compress_type;
2354		split_mid->generation = em->generation;
2355		add_extent_mapping(em_tree, split_mid, modified);
2356	}
2357
2358	if (post) {
2359		split_post->start = em->start + em->len - post;
2360		split_post->len = post;
2361		split_post->orig_start = split_post->start;
2362		split_post->block_start = em->block_start + em->len - post;
2363		split_post->block_len = split_post->len;
2364		split_post->orig_block_len = split_post->block_len;
2365		split_post->ram_bytes = split_post->len;
2366		split_post->flags = flags;
2367		split_post->compress_type = em->compress_type;
2368		split_post->generation = em->generation;
2369		add_extent_mapping(em_tree, split_post, modified);
2370	}
2371
2372	/* Once for us */
2373	free_extent_map(em);
2374	/* Once for the tree */
2375	free_extent_map(em);
2376
2377out_unlock:
2378	write_unlock(&em_tree->lock);
2379	unlock_extent(&inode->io_tree, start, start + len - 1);
2380out:
2381	free_extent_map(split_pre);
2382	free_extent_map(split_mid);
2383	free_extent_map(split_post);
2384
2385	return ret;
2386}
2387
2388static blk_status_t extract_ordered_extent(struct btrfs_inode *inode,
2389					   struct bio *bio, loff_t file_offset)
2390{
2391	struct btrfs_ordered_extent *ordered;
2392	u64 start = (u64)bio->bi_iter.bi_sector << SECTOR_SHIFT;
2393	u64 file_len;
2394	u64 len = bio->bi_iter.bi_size;
2395	u64 end = start + len;
2396	u64 ordered_end;
2397	u64 pre, post;
2398	int ret = 0;
2399
2400	ordered = btrfs_lookup_ordered_extent(inode, file_offset);
2401	if (WARN_ON_ONCE(!ordered))
2402		return BLK_STS_IOERR;
2403
2404	/* No need to split */
2405	if (ordered->disk_num_bytes == len)
2406		goto out;
2407
2408	/* We cannot split once end_bio'd ordered extent */
2409	if (WARN_ON_ONCE(ordered->bytes_left != ordered->disk_num_bytes)) {
2410		ret = -EINVAL;
2411		goto out;
2412	}
2413
2414	/* We cannot split a compressed ordered extent */
2415	if (WARN_ON_ONCE(ordered->disk_num_bytes != ordered->num_bytes)) {
2416		ret = -EINVAL;
2417		goto out;
2418	}
2419
2420	ordered_end = ordered->disk_bytenr + ordered->disk_num_bytes;
2421	/* bio must be in one ordered extent */
2422	if (WARN_ON_ONCE(start < ordered->disk_bytenr || end > ordered_end)) {
2423		ret = -EINVAL;
2424		goto out;
2425	}
2426
2427	/* Checksum list should be empty */
2428	if (WARN_ON_ONCE(!list_empty(&ordered->list))) {
2429		ret = -EINVAL;
2430		goto out;
2431	}
2432
2433	file_len = ordered->num_bytes;
2434	pre = start - ordered->disk_bytenr;
2435	post = ordered_end - end;
2436
2437	ret = btrfs_split_ordered_extent(ordered, pre, post);
2438	if (ret)
2439		goto out;
2440	ret = split_zoned_em(inode, file_offset, file_len, pre, post);
2441
2442out:
2443	btrfs_put_ordered_extent(ordered);
2444
2445	return errno_to_blk_status(ret);
2446}
2447
2448/*
2449 * extent_io.c submission hook. This does the right thing for csum calculation
2450 * on write, or reading the csums from the tree before a read.
2451 *
2452 * Rules about async/sync submit,
2453 * a) read:				sync submit
2454 *
2455 * b) write without checksum:		sync submit
2456 *
2457 * c) write with checksum:
2458 *    c-1) if bio is issued by fsync:	sync submit
2459 *         (sync_writers != 0)
2460 *
2461 *    c-2) if root is reloc root:	sync submit
2462 *         (only in case of buffered IO)
2463 *
2464 *    c-3) otherwise:			async submit
2465 */
2466blk_status_t btrfs_submit_data_bio(struct inode *inode, struct bio *bio,
2467				   int mirror_num, unsigned long bio_flags)
2468
2469{
2470	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2471	struct btrfs_root *root = BTRFS_I(inode)->root;
2472	enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
2473	blk_status_t ret = 0;
2474	int skip_sum;
2475	int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2476
2477	skip_sum = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM) ||
2478		   !fs_info->csum_root;
2479
2480	if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2481		metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2482
2483	if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
2484		struct page *page = bio_first_bvec_all(bio)->bv_page;
2485		loff_t file_offset = page_offset(page);
2486
2487		ret = extract_ordered_extent(BTRFS_I(inode), bio, file_offset);
2488		if (ret)
2489			goto out;
2490	}
2491
2492	if (btrfs_op(bio) != BTRFS_MAP_WRITE) {
2493		ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2494		if (ret)
2495			goto out;
2496
2497		if (bio_flags & EXTENT_BIO_COMPRESSED) {
2498			ret = btrfs_submit_compressed_read(inode, bio,
2499							   mirror_num,
2500							   bio_flags);
2501			goto out;
2502		} else {
2503			/*
2504			 * Lookup bio sums does extra checks around whether we
2505			 * need to csum or not, which is why we ignore skip_sum
2506			 * here.
2507			 */
2508			ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2509			if (ret)
2510				goto out;
2511		}
2512		goto mapit;
2513	} else if (async && !skip_sum) {
2514		/* csum items have already been cloned */
2515		if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2516			goto mapit;
2517		/* we're doing a write, do the async checksumming */
2518		ret = btrfs_wq_submit_bio(inode, bio, mirror_num, bio_flags,
2519					  0, btrfs_submit_bio_start);
2520		goto out;
2521	} else if (!skip_sum) {
2522		ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, 0, 0);
2523		if (ret)
2524			goto out;
2525	}
2526
2527mapit:
2528	ret = btrfs_map_bio(fs_info, bio, mirror_num);
2529
2530out:
2531	if (ret) {
2532		bio->bi_status = ret;
2533		bio_endio(bio);
2534	}
2535	return ret;
2536}
2537
2538/*
2539 * given a list of ordered sums record them in the inode.  This happens
2540 * at IO completion time based on sums calculated at bio submission time.
2541 */
2542static int add_pending_csums(struct btrfs_trans_handle *trans,
2543			     struct list_head *list)
2544{
2545	struct btrfs_ordered_sum *sum;
2546	int ret;
2547
2548	list_for_each_entry(sum, list, list) {
2549		trans->adding_csums = true;
2550		ret = btrfs_csum_file_blocks(trans, trans->fs_info->csum_root, sum);
2551		trans->adding_csums = false;
2552		if (ret)
2553			return ret;
2554	}
2555	return 0;
2556}
2557
2558static int btrfs_find_new_delalloc_bytes(struct btrfs_inode *inode,
2559					 const u64 start,
2560					 const u64 len,
2561					 struct extent_state **cached_state)
2562{
2563	u64 search_start = start;
2564	const u64 end = start + len - 1;
2565
2566	while (search_start < end) {
2567		const u64 search_len = end - search_start + 1;
2568		struct extent_map *em;
2569		u64 em_len;
2570		int ret = 0;
2571
2572		em = btrfs_get_extent(inode, NULL, 0, search_start, search_len);
2573		if (IS_ERR(em))
2574			return PTR_ERR(em);
2575
2576		if (em->block_start != EXTENT_MAP_HOLE)
2577			goto next;
2578
2579		em_len = em->len;
2580		if (em->start < search_start)
2581			em_len -= search_start - em->start;
2582		if (em_len > search_len)
2583			em_len = search_len;
2584
2585		ret = set_extent_bit(&inode->io_tree, search_start,
2586				     search_start + em_len - 1,
2587				     EXTENT_DELALLOC_NEW, 0, NULL, cached_state,
2588				     GFP_NOFS, NULL);
2589next:
2590		search_start = extent_map_end(em);
2591		free_extent_map(em);
2592		if (ret)
2593			return ret;
2594	}
2595	return 0;
2596}
2597
2598int btrfs_set_extent_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2599			      unsigned int extra_bits,
2600			      struct extent_state **cached_state)
2601{
2602	WARN_ON(PAGE_ALIGNED(end));
2603
2604	if (start >= i_size_read(&inode->vfs_inode) &&
2605	    !(inode->flags & BTRFS_INODE_PREALLOC)) {
2606		/*
2607		 * There can't be any extents following eof in this case so just
2608		 * set the delalloc new bit for the range directly.
2609		 */
2610		extra_bits |= EXTENT_DELALLOC_NEW;
2611	} else {
2612		int ret;
2613
2614		ret = btrfs_find_new_delalloc_bytes(inode, start,
2615						    end + 1 - start,
2616						    cached_state);
2617		if (ret)
2618			return ret;
2619	}
2620
2621	return set_extent_delalloc(&inode->io_tree, start, end, extra_bits,
2622				   cached_state);
2623}
2624
2625/* see btrfs_writepage_start_hook for details on why this is required */
2626struct btrfs_writepage_fixup {
2627	struct page *page;
2628	struct inode *inode;
2629	struct btrfs_work work;
2630};
2631
2632static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2633{
2634	struct btrfs_writepage_fixup *fixup;
2635	struct btrfs_ordered_extent *ordered;
2636	struct extent_state *cached_state = NULL;
2637	struct extent_changeset *data_reserved = NULL;
2638	struct page *page;
2639	struct btrfs_inode *inode;
2640	u64 page_start;
2641	u64 page_end;
2642	int ret = 0;
2643	bool free_delalloc_space = true;
2644
2645	fixup = container_of(work, struct btrfs_writepage_fixup, work);
2646	page = fixup->page;
2647	inode = BTRFS_I(fixup->inode);
2648	page_start = page_offset(page);
2649	page_end = page_offset(page) + PAGE_SIZE - 1;
2650
2651	/*
2652	 * This is similar to page_mkwrite, we need to reserve the space before
2653	 * we take the page lock.
2654	 */
2655	ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2656					   PAGE_SIZE);
2657again:
2658	lock_page(page);
2659
2660	/*
2661	 * Before we queued this fixup, we took a reference on the page.
2662	 * page->mapping may go NULL, but it shouldn't be moved to a different
2663	 * address space.
2664	 */
2665	if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2666		/*
2667		 * Unfortunately this is a little tricky, either
2668		 *
2669		 * 1) We got here and our page had already been dealt with and
2670		 *    we reserved our space, thus ret == 0, so we need to just
2671		 *    drop our space reservation and bail.  This can happen the
2672		 *    first time we come into the fixup worker, or could happen
2673		 *    while waiting for the ordered extent.
2674		 * 2) Our page was already dealt with, but we happened to get an
2675		 *    ENOSPC above from the btrfs_delalloc_reserve_space.  In
2676		 *    this case we obviously don't have anything to release, but
2677		 *    because the page was already dealt with we don't want to
2678		 *    mark the page with an error, so make sure we're resetting
2679		 *    ret to 0.  This is why we have this check _before_ the ret
2680		 *    check, because we do not want to have a surprise ENOSPC
2681		 *    when the page was already properly dealt with.
2682		 */
2683		if (!ret) {
2684			btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2685			btrfs_delalloc_release_space(inode, data_reserved,
2686						     page_start, PAGE_SIZE,
2687						     true);
2688		}
2689		ret = 0;
2690		goto out_page;
2691	}
2692
2693	/*
2694	 * We can't mess with the page state unless it is locked, so now that
2695	 * it is locked bail if we failed to make our space reservation.
2696	 */
2697	if (ret)
2698		goto out_page;
2699
2700	lock_extent_bits(&inode->io_tree, page_start, page_end, &cached_state);
2701
2702	/* already ordered? We're done */
2703	if (PageOrdered(page))
2704		goto out_reserved;
2705
2706	ordered = btrfs_lookup_ordered_range(inode, page_start, PAGE_SIZE);
2707	if (ordered) {
2708		unlock_extent_cached(&inode->io_tree, page_start, page_end,
2709				     &cached_state);
2710		unlock_page(page);
2711		btrfs_start_ordered_extent(ordered, 1);
2712		btrfs_put_ordered_extent(ordered);
2713		goto again;
2714	}
2715
2716	ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2717					&cached_state);
2718	if (ret)
2719		goto out_reserved;
2720
2721	/*
2722	 * Everything went as planned, we're now the owner of a dirty page with
2723	 * delayed allocation bits set and space reserved for our COW
2724	 * destination.
2725	 *
2726	 * The page was dirty when we started, nothing should have cleaned it.
2727	 */
2728	BUG_ON(!PageDirty(page));
2729	free_delalloc_space = false;
2730out_reserved:
2731	btrfs_delalloc_release_extents(inode, PAGE_SIZE);
2732	if (free_delalloc_space)
2733		btrfs_delalloc_release_space(inode, data_reserved, page_start,
2734					     PAGE_SIZE, true);
2735	unlock_extent_cached(&inode->io_tree, page_start, page_end,
2736			     &cached_state);
2737out_page:
2738	if (ret) {
2739		/*
2740		 * We hit ENOSPC or other errors.  Update the mapping and page
2741		 * to reflect the errors and clean the page.
2742		 */
2743		mapping_set_error(page->mapping, ret);
2744		end_extent_writepage(page, ret, page_start, page_end);
2745		clear_page_dirty_for_io(page);
2746		SetPageError(page);
2747	}
2748	ClearPageChecked(page);
2749	unlock_page(page);
2750	put_page(page);
2751	kfree(fixup);
2752	extent_changeset_free(data_reserved);
2753	/*
2754	 * As a precaution, do a delayed iput in case it would be the last iput
2755	 * that could need flushing space. Recursing back to fixup worker would
2756	 * deadlock.
2757	 */
2758	btrfs_add_delayed_iput(&inode->vfs_inode);
2759}
2760
2761/*
2762 * There are a few paths in the higher layers of the kernel that directly
2763 * set the page dirty bit without asking the filesystem if it is a
2764 * good idea.  This causes problems because we want to make sure COW
2765 * properly happens and the data=ordered rules are followed.
2766 *
2767 * In our case any range that doesn't have the ORDERED bit set
2768 * hasn't been properly setup for IO.  We kick off an async process
2769 * to fix it up.  The async helper will wait for ordered extents, set
2770 * the delalloc bit and make it safe to write the page.
2771 */
2772int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end)
2773{
2774	struct inode *inode = page->mapping->host;
2775	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2776	struct btrfs_writepage_fixup *fixup;
2777
2778	/* This page has ordered extent covering it already */
2779	if (PageOrdered(page))
2780		return 0;
2781
2782	/*
2783	 * PageChecked is set below when we create a fixup worker for this page,
2784	 * don't try to create another one if we're already PageChecked()
2785	 *
2786	 * The extent_io writepage code will redirty the page if we send back
2787	 * EAGAIN.
2788	 */
2789	if (PageChecked(page))
2790		return -EAGAIN;
2791
2792	fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2793	if (!fixup)
2794		return -EAGAIN;
2795
2796	/*
2797	 * We are already holding a reference to this inode from
2798	 * write_cache_pages.  We need to hold it because the space reservation
2799	 * takes place outside of the page lock, and we can't trust
2800	 * page->mapping outside of the page lock.
2801	 */
2802	ihold(inode);
2803	SetPageChecked(page);
2804	get_page(page);
2805	btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL, NULL);
2806	fixup->page = page;
2807	fixup->inode = inode;
2808	btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2809
2810	return -EAGAIN;
2811}
2812
2813static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2814				       struct btrfs_inode *inode, u64 file_pos,
2815				       struct btrfs_file_extent_item *stack_fi,
2816				       const bool update_inode_bytes,
2817				       u64 qgroup_reserved)
2818{
2819	struct btrfs_root *root = inode->root;
2820	const u64 sectorsize = root->fs_info->sectorsize;
2821	struct btrfs_path *path;
2822	struct extent_buffer *leaf;
2823	struct btrfs_key ins;
2824	u64 disk_num_bytes = btrfs_stack_file_extent_disk_num_bytes(stack_fi);
2825	u64 disk_bytenr = btrfs_stack_file_extent_disk_bytenr(stack_fi);
2826	u64 num_bytes = btrfs_stack_file_extent_num_bytes(stack_fi);
2827	u64 ram_bytes = btrfs_stack_file_extent_ram_bytes(stack_fi);
2828	struct btrfs_drop_extents_args drop_args = { 0 };
2829	int ret;
2830
2831	path = btrfs_alloc_path();
2832	if (!path)
2833		return -ENOMEM;
2834
2835	/*
2836	 * we may be replacing one extent in the tree with another.
2837	 * The new extent is pinned in the extent map, and we don't want
2838	 * to drop it from the cache until it is completely in the btree.
2839	 *
2840	 * So, tell btrfs_drop_extents to leave this extent in the cache.
2841	 * the caller is expected to unpin it and allow it to be merged
2842	 * with the others.
2843	 */
2844	drop_args.path = path;
2845	drop_args.start = file_pos;
2846	drop_args.end = file_pos + num_bytes;
2847	drop_args.replace_extent = true;
2848	drop_args.extent_item_size = sizeof(*stack_fi);
2849	ret = btrfs_drop_extents(trans, root, inode, &drop_args);
2850	if (ret)
2851		goto out;
2852
2853	if (!drop_args.extent_inserted) {
2854		ins.objectid = btrfs_ino(inode);
2855		ins.offset = file_pos;
2856		ins.type = BTRFS_EXTENT_DATA_KEY;
2857
2858		ret = btrfs_insert_empty_item(trans, root, path, &ins,
2859					      sizeof(*stack_fi));
2860		if (ret)
2861			goto out;
2862	}
2863	leaf = path->nodes[0];
2864	btrfs_set_stack_file_extent_generation(stack_fi, trans->transid);
2865	write_extent_buffer(leaf, stack_fi,
2866			btrfs_item_ptr_offset(leaf, path->slots[0]),
2867			sizeof(struct btrfs_file_extent_item));
2868
2869	btrfs_mark_buffer_dirty(leaf);
2870	btrfs_release_path(path);
2871
2872	/*
2873	 * If we dropped an inline extent here, we know the range where it is
2874	 * was not marked with the EXTENT_DELALLOC_NEW bit, so we update the
2875	 * number of bytes only for that range containing the inline extent.
2876	 * The remaining of the range will be processed when clearning the
2877	 * EXTENT_DELALLOC_BIT bit through the ordered extent completion.
2878	 */
2879	if (file_pos == 0 && !IS_ALIGNED(drop_args.bytes_found, sectorsize)) {
2880		u64 inline_size = round_down(drop_args.bytes_found, sectorsize);
2881
2882		inline_size = drop_args.bytes_found - inline_size;
2883		btrfs_update_inode_bytes(inode, sectorsize, inline_size);
2884		drop_args.bytes_found -= inline_size;
2885		num_bytes -= sectorsize;
2886	}
2887
2888	if (update_inode_bytes)
2889		btrfs_update_inode_bytes(inode, num_bytes, drop_args.bytes_found);
2890
2891	ins.objectid = disk_bytenr;
2892	ins.offset = disk_num_bytes;
2893	ins.type = BTRFS_EXTENT_ITEM_KEY;
2894
2895	ret = btrfs_inode_set_file_extent_range(inode, file_pos, ram_bytes);
2896	if (ret)
2897		goto out;
2898
2899	ret = btrfs_alloc_reserved_file_extent(trans, root, btrfs_ino(inode),
2900					       file_pos, qgroup_reserved, &ins);
2901out:
2902	btrfs_free_path(path);
2903
2904	return ret;
2905}
2906
2907static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2908					 u64 start, u64 len)
2909{
2910	struct btrfs_block_group *cache;
2911
2912	cache = btrfs_lookup_block_group(fs_info, start);
2913	ASSERT(cache);
2914
2915	spin_lock(&cache->lock);
2916	cache->delalloc_bytes -= len;
2917	spin_unlock(&cache->lock);
2918
2919	btrfs_put_block_group(cache);
2920}
2921
2922static int insert_ordered_extent_file_extent(struct btrfs_trans_handle *trans,
2923					     struct btrfs_ordered_extent *oe)
2924{
2925	struct btrfs_file_extent_item stack_fi;
2926	u64 logical_len;
2927	bool update_inode_bytes;
2928
2929	memset(&stack_fi, 0, sizeof(stack_fi));
2930	btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_REG);
2931	btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, oe->disk_bytenr);
2932	btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi,
2933						   oe->disk_num_bytes);
2934	if (test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags))
2935		logical_len = oe->truncated_len;
2936	else
2937		logical_len = oe->num_bytes;
2938	btrfs_set_stack_file_extent_num_bytes(&stack_fi, logical_len);
2939	btrfs_set_stack_file_extent_ram_bytes(&stack_fi, logical_len);
2940	btrfs_set_stack_file_extent_compression(&stack_fi, oe->compress_type);
2941	/* Encryption and other encoding is reserved and all 0 */
2942
2943	/*
2944	 * For delalloc, when completing an ordered extent we update the inode's
2945	 * bytes when clearing the range in the inode's io tree, so pass false
2946	 * as the argument 'update_inode_bytes' to insert_reserved_file_extent(),
2947	 * except if the ordered extent was truncated.
2948	 */
2949	update_inode_bytes = test_bit(BTRFS_ORDERED_DIRECT, &oe->flags) ||
2950			     test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags);
2951
2952	return insert_reserved_file_extent(trans, BTRFS_I(oe->inode),
2953					   oe->file_offset, &stack_fi,
2954					   update_inode_bytes, oe->qgroup_rsv);
2955}
2956
2957/*
2958 * As ordered data IO finishes, this gets called so we can finish
2959 * an ordered extent if the range of bytes in the file it covers are
2960 * fully written.
2961 */
2962static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2963{
2964	struct btrfs_inode *inode = BTRFS_I(ordered_extent->inode);
2965	struct btrfs_root *root = inode->root;
2966	struct btrfs_fs_info *fs_info = root->fs_info;
2967	struct btrfs_trans_handle *trans = NULL;
2968	struct extent_io_tree *io_tree = &inode->io_tree;
2969	struct extent_state *cached_state = NULL;
2970	u64 start, end;
2971	int compress_type = 0;
2972	int ret = 0;
2973	u64 logical_len = ordered_extent->num_bytes;
2974	bool freespace_inode;
2975	bool truncated = false;
2976	bool clear_reserved_extent = true;
2977	unsigned int clear_bits = EXTENT_DEFRAG;
2978
2979	start = ordered_extent->file_offset;
2980	end = start + ordered_extent->num_bytes - 1;
2981
2982	if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2983	    !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2984	    !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2985		clear_bits |= EXTENT_DELALLOC_NEW;
2986
2987	freespace_inode = btrfs_is_free_space_inode(inode);
2988
2989	if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2990		ret = -EIO;
2991		goto out;
2992	}
2993
2994	if (ordered_extent->bdev)
2995		btrfs_rewrite_logical_zoned(ordered_extent);
2996
2997	btrfs_free_io_failure_record(inode, start, end);
2998
2999	if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
3000		truncated = true;
3001		logical_len = ordered_extent->truncated_len;
3002		/* Truncated the entire extent, don't bother adding */
3003		if (!logical_len)
3004			goto out;
3005	}
3006
3007	if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
3008		BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
3009
3010		btrfs_inode_safe_disk_i_size_write(inode, 0);
3011		if (freespace_inode)
3012			trans = btrfs_join_transaction_spacecache(root);
3013		else
3014			trans = btrfs_join_transaction(root);
3015		if (IS_ERR(trans)) {
3016			ret = PTR_ERR(trans);
3017			trans = NULL;
3018			goto out;
3019		}
3020		trans->block_rsv = &inode->block_rsv;
3021		ret = btrfs_update_inode_fallback(trans, root, inode);
3022		if (ret) /* -ENOMEM or corruption */
3023			btrfs_abort_transaction(trans, ret);
3024		goto out;
3025	}
3026
3027	clear_bits |= EXTENT_LOCKED;
3028	lock_extent_bits(io_tree, start, end, &cached_state);
3029
3030	if (freespace_inode)
3031		trans = btrfs_join_transaction_spacecache(root);
3032	else
3033		trans = btrfs_join_transaction(root);
3034	if (IS_ERR(trans)) {
3035		ret = PTR_ERR(trans);
3036		trans = NULL;
3037		goto out;
3038	}
3039
3040	trans->block_rsv = &inode->block_rsv;
3041
3042	if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3043		compress_type = ordered_extent->compress_type;
3044	if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3045		BUG_ON(compress_type);
3046		ret = btrfs_mark_extent_written(trans, inode,
3047						ordered_extent->file_offset,
3048						ordered_extent->file_offset +
3049						logical_len);
3050	} else {
3051		BUG_ON(root == fs_info->tree_root);
3052		ret = insert_ordered_extent_file_extent(trans, ordered_extent);
3053		if (!ret) {
3054			clear_reserved_extent = false;
3055			btrfs_release_delalloc_bytes(fs_info,
3056						ordered_extent->disk_bytenr,
3057						ordered_extent->disk_num_bytes);
3058		}
3059	}
3060	unpin_extent_cache(&inode->extent_tree, ordered_extent->file_offset,
3061			   ordered_extent->num_bytes, trans->transid);
3062	if (ret < 0) {
3063		btrfs_abort_transaction(trans, ret);
3064		goto out;
3065	}
3066
3067	ret = add_pending_csums(trans, &ordered_extent->list);
3068	if (ret) {
3069		btrfs_abort_transaction(trans, ret);
3070		goto out;
3071	}
3072
3073	/*
3074	 * If this is a new delalloc range, clear its new delalloc flag to
3075	 * update the inode's number of bytes. This needs to be done first
3076	 * before updating the inode item.
3077	 */
3078	if ((clear_bits & EXTENT_DELALLOC_NEW) &&
3079	    !test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags))
3080		clear_extent_bit(&inode->io_tree, start, end,
3081				 EXTENT_DELALLOC_NEW | EXTENT_ADD_INODE_BYTES,
3082				 0, 0, &cached_state);
3083
3084	btrfs_inode_safe_disk_i_size_write(inode, 0);
3085	ret = btrfs_update_inode_fallback(trans, root, inode);
3086	if (ret) { /* -ENOMEM or corruption */
3087		btrfs_abort_transaction(trans, ret);
3088		goto out;
3089	}
3090	ret = 0;
3091out:
3092	clear_extent_bit(&inode->io_tree, start, end, clear_bits,
3093			 (clear_bits & EXTENT_LOCKED) ? 1 : 0, 0,
3094			 &cached_state);
3095
3096	if (trans)
3097		btrfs_end_transaction(trans);
3098
3099	if (ret || truncated) {
3100		u64 unwritten_start = start;
3101
3102		/*
3103		 * If we failed to finish this ordered extent for any reason we
3104		 * need to make sure BTRFS_ORDERED_IOERR is set on the ordered
3105		 * extent, and mark the inode with the error if it wasn't
3106		 * already set.  Any error during writeback would have already
3107		 * set the mapping error, so we need to set it if we're the ones
3108		 * marking this ordered extent as failed.
3109		 */
3110		if (ret && !test_and_set_bit(BTRFS_ORDERED_IOERR,
3111					     &ordered_extent->flags))
3112			mapping_set_error(ordered_extent->inode->i_mapping, -EIO);
3113
3114		if (truncated)
3115			unwritten_start += logical_len;
3116		clear_extent_uptodate(io_tree, unwritten_start, end, NULL);
3117
3118		/* Drop the cache for the part of the extent we didn't write. */
3119		btrfs_drop_extent_cache(inode, unwritten_start, end, 0);
3120
3121		/*
3122		 * If the ordered extent had an IOERR or something else went
3123		 * wrong we need to return the space for this ordered extent
3124		 * back to the allocator.  We only free the extent in the
3125		 * truncated case if we didn't write out the extent at all.
3126		 *
3127		 * If we made it past insert_reserved_file_extent before we
3128		 * errored out then we don't need to do this as the accounting
3129		 * has already been done.
3130		 */
3131		if ((ret || !logical_len) &&
3132		    clear_reserved_extent &&
3133		    !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3134		    !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3135			/*
3136			 * Discard the range before returning it back to the
3137			 * free space pool
3138			 */
3139			if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
3140				btrfs_discard_extent(fs_info,
3141						ordered_extent->disk_bytenr,
3142						ordered_extent->disk_num_bytes,
3143						NULL);
3144			btrfs_free_reserved_extent(fs_info,
3145					ordered_extent->disk_bytenr,
3146					ordered_extent->disk_num_bytes, 1);
3147		}
3148	}
3149
3150	/*
3151	 * This needs to be done to make sure anybody waiting knows we are done
3152	 * updating everything for this ordered extent.
3153	 */
3154	btrfs_remove_ordered_extent(inode, ordered_extent);
3155
3156	/* once for us */
3157	btrfs_put_ordered_extent(ordered_extent);
3158	/* once for the tree */
3159	btrfs_put_ordered_extent(ordered_extent);
3160
3161	return ret;
3162}
3163
3164static void finish_ordered_fn(struct btrfs_work *work)
3165{
3166	struct btrfs_ordered_extent *ordered_extent;
3167	ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3168	btrfs_finish_ordered_io(ordered_extent);
3169}
3170
3171void btrfs_writepage_endio_finish_ordered(struct btrfs_inode *inode,
3172					  struct page *page, u64 start,
3173					  u64 end, int uptodate)
3174{
3175	trace_btrfs_writepage_end_io_hook(inode, start, end, uptodate);
3176
3177	btrfs_mark_ordered_io_finished(inode, page, start, end + 1 - start,
3178				       finish_ordered_fn, uptodate);
3179}
3180
3181/*
3182 * check_data_csum - verify checksum of one sector of uncompressed data
3183 * @inode:	inode
3184 * @io_bio:	btrfs_io_bio which contains the csum
3185 * @bio_offset:	offset to the beginning of the bio (in bytes)
3186 * @page:	page where is the data to be verified
3187 * @pgoff:	offset inside the page
3188 * @start:	logical offset in the file
3189 *
3190 * The length of such check is always one sector size.
3191 */
3192static int check_data_csum(struct inode *inode, struct btrfs_io_bio *io_bio,
3193			   u32 bio_offset, struct page *page, u32 pgoff,
3194			   u64 start)
3195{
3196	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3197	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3198	char *kaddr;
3199	u32 len = fs_info->sectorsize;
3200	const u32 csum_size = fs_info->csum_size;
3201	unsigned int offset_sectors;
3202	u8 *csum_expected;
3203	u8 csum[BTRFS_CSUM_SIZE];
3204
3205	ASSERT(pgoff + len <= PAGE_SIZE);
3206
3207	offset_sectors = bio_offset >> fs_info->sectorsize_bits;
3208	csum_expected = ((u8 *)io_bio->csum) + offset_sectors * csum_size;
3209
3210	kaddr = kmap_atomic(page);
3211	shash->tfm = fs_info->csum_shash;
3212
3213	crypto_shash_digest(shash, kaddr + pgoff, len, csum);
3214
3215	if (memcmp(csum, csum_expected, csum_size))
3216		goto zeroit;
3217
3218	kunmap_atomic(kaddr);
3219	return 0;
3220zeroit:
3221	btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3222				    io_bio->mirror_num);
3223	if (io_bio->device)
3224		btrfs_dev_stat_inc_and_print(io_bio->device,
3225					     BTRFS_DEV_STAT_CORRUPTION_ERRS);
3226	memset(kaddr + pgoff, 1, len);
3227	flush_dcache_page(page);
3228	kunmap_atomic(kaddr);
3229	return -EIO;
3230}
3231
3232/*
3233 * When reads are done, we need to check csums to verify the data is correct.
3234 * if there's a match, we allow the bio to finish.  If not, the code in
3235 * extent_io.c will try to find good copies for us.
3236 *
3237 * @bio_offset:	offset to the beginning of the bio (in bytes)
3238 * @start:	file offset of the range start
3239 * @end:	file offset of the range end (inclusive)
3240 *
3241 * Return a bitmap where bit set means a csum mismatch, and bit not set means
3242 * csum match.
3243 */
3244unsigned int btrfs_verify_data_csum(struct btrfs_io_bio *io_bio, u32 bio_offset,
3245				    struct page *page, u64 start, u64 end)
3246{
3247	struct inode *inode = page->mapping->host;
3248	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3249	struct btrfs_root *root = BTRFS_I(inode)->root;
3250	const u32 sectorsize = root->fs_info->sectorsize;
3251	u32 pg_off;
3252	unsigned int result = 0;
3253
3254	if (PageChecked(page)) {
3255		ClearPageChecked(page);
3256		return 0;
3257	}
3258
3259	if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3260		return 0;
3261
3262	if (!root->fs_info->csum_root)
3263		return 0;
3264
3265	if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3266	    test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3267		clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3268		return 0;
3269	}
3270
3271	ASSERT(page_offset(page) <= start &&
3272	       end <= page_offset(page) + PAGE_SIZE - 1);
3273	for (pg_off = offset_in_page(start);
3274	     pg_off < offset_in_page(end);
3275	     pg_off += sectorsize, bio_offset += sectorsize) {
3276		int ret;
3277
3278		ret = check_data_csum(inode, io_bio, bio_offset, page, pg_off,
3279				      page_offset(page) + pg_off);
3280		if (ret < 0) {
3281			const int nr_bit = (pg_off - offset_in_page(start)) >>
3282				     root->fs_info->sectorsize_bits;
3283
3284			result |= (1U << nr_bit);
3285		}
3286	}
3287	return result;
3288}
3289
3290/*
3291 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3292 *
3293 * @inode: The inode we want to perform iput on
3294 *
3295 * This function uses the generic vfs_inode::i_count to track whether we should
3296 * just decrement it (in case it's > 1) or if this is the last iput then link
3297 * the inode to the delayed iput machinery. Delayed iputs are processed at
3298 * transaction commit time/superblock commit/cleaner kthread.
3299 */
3300void btrfs_add_delayed_iput(struct inode *inode)
3301{
3302	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3303	struct btrfs_inode *binode = BTRFS_I(inode);
3304
3305	if (atomic_add_unless(&inode->i_count, -1, 1))
3306		return;
3307
3308	atomic_inc(&fs_info->nr_delayed_iputs);
3309	spin_lock(&fs_info->delayed_iput_lock);
3310	ASSERT(list_empty(&binode->delayed_iput));
3311	list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3312	spin_unlock(&fs_info->delayed_iput_lock);
3313	if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3314		wake_up_process(fs_info->cleaner_kthread);
3315}
3316
3317static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
3318				    struct btrfs_inode *inode)
3319{
3320	list_del_init(&inode->delayed_iput);
3321	spin_unlock(&fs_info->delayed_iput_lock);
3322	iput(&inode->vfs_inode);
3323	if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3324		wake_up(&fs_info->delayed_iputs_wait);
3325	spin_lock(&fs_info->delayed_iput_lock);
3326}
3327
3328static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
3329				   struct btrfs_inode *inode)
3330{
3331	if (!list_empty(&inode->delayed_iput)) {
3332		spin_lock(&fs_info->delayed_iput_lock);
3333		if (!list_empty(&inode->delayed_iput))
3334			run_delayed_iput_locked(fs_info, inode);
3335		spin_unlock(&fs_info->delayed_iput_lock);
3336	}
3337}
3338
3339void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3340{
3341
3342	spin_lock(&fs_info->delayed_iput_lock);
3343	while (!list_empty(&fs_info->delayed_iputs)) {
3344		struct btrfs_inode *inode;
3345
3346		inode = list_first_entry(&fs_info->delayed_iputs,
3347				struct btrfs_inode, delayed_iput);
3348		run_delayed_iput_locked(fs_info, inode);
3349		cond_resched_lock(&fs_info->delayed_iput_lock);
3350	}
3351	spin_unlock(&fs_info->delayed_iput_lock);
3352}
3353
3354/**
3355 * Wait for flushing all delayed iputs
3356 *
3357 * @fs_info:  the filesystem
3358 *
3359 * This will wait on any delayed iputs that are currently running with KILLABLE
3360 * set.  Once they are all done running we will return, unless we are killed in
3361 * which case we return EINTR. This helps in user operations like fallocate etc
3362 * that might get blocked on the iputs.
3363 *
3364 * Return EINTR if we were killed, 0 if nothing's pending
3365 */
3366int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3367{
3368	int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3369			atomic_read(&fs_info->nr_delayed_iputs) == 0);
3370	if (ret)
3371		return -EINTR;
3372	return 0;
3373}
3374
3375/*
3376 * This creates an orphan entry for the given inode in case something goes wrong
3377 * in the middle of an unlink.
3378 */
3379int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3380		     struct btrfs_inode *inode)
3381{
3382	int ret;
3383
3384	ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3385	if (ret && ret != -EEXIST) {
3386		btrfs_abort_transaction(trans, ret);
3387		return ret;
3388	}
3389
3390	return 0;
3391}
3392
3393/*
3394 * We have done the delete so we can go ahead and remove the orphan item for
3395 * this particular inode.
3396 */
3397static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3398			    struct btrfs_inode *inode)
3399{
3400	return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3401}
3402
3403/*
3404 * this cleans up any orphans that may be left on the list from the last use
3405 * of this root.
3406 */
3407int btrfs_orphan_cleanup(struct btrfs_root *root)
3408{
3409	struct btrfs_fs_info *fs_info = root->fs_info;
3410	struct btrfs_path *path;
3411	struct extent_buffer *leaf;
3412	struct btrfs_key key, found_key;
3413	struct btrfs_trans_handle *trans;
3414	struct inode *inode;
3415	u64 last_objectid = 0;
3416	int ret = 0, nr_unlink = 0;
3417
3418	if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3419		return 0;
3420
3421	path = btrfs_alloc_path();
3422	if (!path) {
3423		ret = -ENOMEM;
3424		goto out;
3425	}
3426	path->reada = READA_BACK;
3427
3428	key.objectid = BTRFS_ORPHAN_OBJECTID;
3429	key.type = BTRFS_ORPHAN_ITEM_KEY;
3430	key.offset = (u64)-1;
3431
3432	while (1) {
3433		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3434		if (ret < 0)
3435			goto out;
3436
3437		/*
3438		 * if ret == 0 means we found what we were searching for, which
3439		 * is weird, but possible, so only screw with path if we didn't
3440		 * find the key and see if we have stuff that matches
3441		 */
3442		if (ret > 0) {
3443			ret = 0;
3444			if (path->slots[0] == 0)
3445				break;
3446			path->slots[0]--;
3447		}
3448
3449		/* pull out the item */
3450		leaf = path->nodes[0];
3451		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3452
3453		/* make sure the item matches what we want */
3454		if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3455			break;
3456		if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3457			break;
3458
3459		/* release the path since we're done with it */
3460		btrfs_release_path(path);
3461
3462		/*
3463		 * this is where we are basically btrfs_lookup, without the
3464		 * crossing root thing.  we store the inode number in the
3465		 * offset of the orphan item.
3466		 */
3467
3468		if (found_key.offset == last_objectid) {
3469			btrfs_err(fs_info,
3470				  "Error removing orphan entry, stopping orphan cleanup");
3471			ret = -EINVAL;
3472			goto out;
3473		}
3474
3475		last_objectid = found_key.offset;
3476
3477		found_key.objectid = found_key.offset;
3478		found_key.type = BTRFS_INODE_ITEM_KEY;
3479		found_key.offset = 0;
3480		inode = btrfs_iget(fs_info->sb, last_objectid, root);
3481		ret = PTR_ERR_OR_ZERO(inode);
3482		if (ret && ret != -ENOENT)
3483			goto out;
3484
3485		if (ret == -ENOENT && root == fs_info->tree_root) {
3486			struct btrfs_root *dead_root;
3487			int is_dead_root = 0;
3488
3489			/*
3490			 * This is an orphan in the tree root. Currently these
3491			 * could come from 2 sources:
3492			 *  a) a root (snapshot/subvolume) deletion in progress
3493			 *  b) a free space cache inode
3494			 * We need to distinguish those two, as the orphan item
3495			 * for a root must not get deleted before the deletion
3496			 * of the snapshot/subvolume's tree completes.
3497			 *
3498			 * btrfs_find_orphan_roots() ran before us, which has
3499			 * found all deleted roots and loaded them into
3500			 * fs_info->fs_roots_radix. So here we can find if an
3501			 * orphan item corresponds to a deleted root by looking
3502			 * up the root from that radix tree.
3503			 */
3504
3505			spin_lock(&fs_info->fs_roots_radix_lock);
3506			dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
3507							 (unsigned long)found_key.objectid);
3508			if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
3509				is_dead_root = 1;
3510			spin_unlock(&fs_info->fs_roots_radix_lock);
3511
3512			if (is_dead_root) {
3513				/* prevent this orphan from being found again */
3514				key.offset = found_key.objectid - 1;
3515				continue;
3516			}
3517
3518		}
3519
3520		/*
3521		 * If we have an inode with links, there are a couple of
3522		 * possibilities. Old kernels (before v3.12) used to create an
3523		 * orphan item for truncate indicating that there were possibly
3524		 * extent items past i_size that needed to be deleted. In v3.12,
3525		 * truncate was changed to update i_size in sync with the extent
3526		 * items, but the (useless) orphan item was still created. Since
3527		 * v4.18, we don't create the orphan item for truncate at all.
3528		 *
3529		 * So, this item could mean that we need to do a truncate, but
3530		 * only if this filesystem was last used on a pre-v3.12 kernel
3531		 * and was not cleanly unmounted. The odds of that are quite
3532		 * slim, and it's a pain to do the truncate now, so just delete
3533		 * the orphan item.
3534		 *
3535		 * It's also possible that this orphan item was supposed to be
3536		 * deleted but wasn't. The inode number may have been reused,
3537		 * but either way, we can delete the orphan item.
3538		 */
3539		if (ret == -ENOENT || inode->i_nlink) {
3540			if (!ret)
3541				iput(inode);
3542			trans = btrfs_start_transaction(root, 1);
3543			if (IS_ERR(trans)) {
3544				ret = PTR_ERR(trans);
3545				goto out;
3546			}
3547			btrfs_debug(fs_info, "auto deleting %Lu",
3548				    found_key.objectid);
3549			ret = btrfs_del_orphan_item(trans, root,
3550						    found_key.objectid);
3551			btrfs_end_transaction(trans);
3552			if (ret)
3553				goto out;
3554			continue;
3555		}
3556
3557		nr_unlink++;
3558
3559		/* this will do delete_inode and everything for us */
3560		iput(inode);
3561	}
3562	/* release the path since we're done with it */
3563	btrfs_release_path(path);
3564
3565	root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3566
3567	if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3568		trans = btrfs_join_transaction(root);
3569		if (!IS_ERR(trans))
3570			btrfs_end_transaction(trans);
3571	}
3572
3573	if (nr_unlink)
3574		btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3575
3576out:
3577	if (ret)
3578		btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3579	btrfs_free_path(path);
3580	return ret;
3581}
3582
3583/*
3584 * very simple check to peek ahead in the leaf looking for xattrs.  If we
3585 * don't find any xattrs, we know there can't be any acls.
3586 *
3587 * slot is the slot the inode is in, objectid is the objectid of the inode
3588 */
3589static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3590					  int slot, u64 objectid,
3591					  int *first_xattr_slot)
3592{
3593	u32 nritems = btrfs_header_nritems(leaf);
3594	struct btrfs_key found_key;
3595	static u64 xattr_access = 0;
3596	static u64 xattr_default = 0;
3597	int scanned = 0;
3598
3599	if (!xattr_access) {
3600		xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3601					strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3602		xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3603					strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3604	}
3605
3606	slot++;
3607	*first_xattr_slot = -1;
3608	while (slot < nritems) {
3609		btrfs_item_key_to_cpu(leaf, &found_key, slot);
3610
3611		/* we found a different objectid, there must not be acls */
3612		if (found_key.objectid != objectid)
3613			return 0;
3614
3615		/* we found an xattr, assume we've got an acl */
3616		if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3617			if (*first_xattr_slot == -1)
3618				*first_xattr_slot = slot;
3619			if (found_key.offset == xattr_access ||
3620			    found_key.offset == xattr_default)
3621				return 1;
3622		}
3623
3624		/*
3625		 * we found a key greater than an xattr key, there can't
3626		 * be any acls later on
3627		 */
3628		if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3629			return 0;
3630
3631		slot++;
3632		scanned++;
3633
3634		/*
3635		 * it goes inode, inode backrefs, xattrs, extents,
3636		 * so if there are a ton of hard links to an inode there can
3637		 * be a lot of backrefs.  Don't waste time searching too hard,
3638		 * this is just an optimization
3639		 */
3640		if (scanned >= 8)
3641			break;
3642	}
3643	/* we hit the end of the leaf before we found an xattr or
3644	 * something larger than an xattr.  We have to assume the inode
3645	 * has acls
3646	 */
3647	if (*first_xattr_slot == -1)
3648		*first_xattr_slot = slot;
3649	return 1;
3650}
3651
3652/*
3653 * read an inode from the btree into the in-memory inode
3654 */
3655static int btrfs_read_locked_inode(struct inode *inode,
3656				   struct btrfs_path *in_path)
3657{
3658	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3659	struct btrfs_path *path = in_path;
3660	struct extent_buffer *leaf;
3661	struct btrfs_inode_item *inode_item;
3662	struct btrfs_root *root = BTRFS_I(inode)->root;
3663	struct btrfs_key location;
3664	unsigned long ptr;
3665	int maybe_acls;
3666	u32 rdev;
3667	int ret;
3668	bool filled = false;
3669	int first_xattr_slot;
3670
3671	ret = btrfs_fill_inode(inode, &rdev);
3672	if (!ret)
3673		filled = true;
3674
3675	if (!path) {
3676		path = btrfs_alloc_path();
3677		if (!path)
3678			return -ENOMEM;
3679	}
3680
3681	memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3682
3683	ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3684	if (ret) {
3685		if (path != in_path)
3686			btrfs_free_path(path);
3687		return ret;
3688	}
3689
3690	leaf = path->nodes[0];
3691
3692	if (filled)
3693		goto cache_index;
3694
3695	inode_item = btrfs_item_ptr(leaf, path->slots[0],
3696				    struct btrfs_inode_item);
3697	inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3698	set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3699	i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3700	i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3701	btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3702	btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
3703			round_up(i_size_read(inode), fs_info->sectorsize));
3704
3705	inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3706	inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3707
3708	inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3709	inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3710
3711	inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3712	inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3713
3714	BTRFS_I(inode)->i_otime.tv_sec =
3715		btrfs_timespec_sec(leaf, &inode_item->otime);
3716	BTRFS_I(inode)->i_otime.tv_nsec =
3717		btrfs_timespec_nsec(leaf, &inode_item->otime);
3718
3719	inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3720	BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3721	BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3722
3723	inode_set_iversion_queried(inode,
3724				   btrfs_inode_sequence(leaf, inode_item));
3725	inode->i_generation = BTRFS_I(inode)->generation;
3726	inode->i_rdev = 0;
3727	rdev = btrfs_inode_rdev(leaf, inode_item);
3728
3729	BTRFS_I(inode)->index_cnt = (u64)-1;
3730	BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3731
3732cache_index:
3733	/*
3734	 * If we were modified in the current generation and evicted from memory
3735	 * and then re-read we need to do a full sync since we don't have any
3736	 * idea about which extents were modified before we were evicted from
3737	 * cache.
3738	 *
3739	 * This is required for both inode re-read from disk and delayed inode
3740	 * in delayed_nodes_tree.
3741	 */
3742	if (BTRFS_I(inode)->last_trans == fs_info->generation)
3743		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3744			&BTRFS_I(inode)->runtime_flags);
3745
3746	/*
3747	 * We don't persist the id of the transaction where an unlink operation
3748	 * against the inode was last made. So here we assume the inode might
3749	 * have been evicted, and therefore the exact value of last_unlink_trans
3750	 * lost, and set it to last_trans to avoid metadata inconsistencies
3751	 * between the inode and its parent if the inode is fsync'ed and the log
3752	 * replayed. For example, in the scenario:
3753	 *
3754	 * touch mydir/foo
3755	 * ln mydir/foo mydir/bar
3756	 * sync
3757	 * unlink mydir/bar
3758	 * echo 2 > /proc/sys/vm/drop_caches   # evicts inode
3759	 * xfs_io -c fsync mydir/foo
3760	 * <power failure>
3761	 * mount fs, triggers fsync log replay
3762	 *
3763	 * We must make sure that when we fsync our inode foo we also log its
3764	 * parent inode, otherwise after log replay the parent still has the
3765	 * dentry with the "bar" name but our inode foo has a link count of 1
3766	 * and doesn't have an inode ref with the name "bar" anymore.
3767	 *
3768	 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3769	 * but it guarantees correctness at the expense of occasional full
3770	 * transaction commits on fsync if our inode is a directory, or if our
3771	 * inode is not a directory, logging its parent unnecessarily.
3772	 */
3773	BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3774
3775	/*
3776	 * Same logic as for last_unlink_trans. We don't persist the generation
3777	 * of the last transaction where this inode was used for a reflink
3778	 * operation, so after eviction and reloading the inode we must be
3779	 * pessimistic and assume the last transaction that modified the inode.
3780	 */
3781	BTRFS_I(inode)->last_reflink_trans = BTRFS_I(inode)->last_trans;
3782
3783	path->slots[0]++;
3784	if (inode->i_nlink != 1 ||
3785	    path->slots[0] >= btrfs_header_nritems(leaf))
3786		goto cache_acl;
3787
3788	btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3789	if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3790		goto cache_acl;
3791
3792	ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3793	if (location.type == BTRFS_INODE_REF_KEY) {
3794		struct btrfs_inode_ref *ref;
3795
3796		ref = (struct btrfs_inode_ref *)ptr;
3797		BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3798	} else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3799		struct btrfs_inode_extref *extref;
3800
3801		extref = (struct btrfs_inode_extref *)ptr;
3802		BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3803								     extref);
3804	}
3805cache_acl:
3806	/*
3807	 * try to precache a NULL acl entry for files that don't have
3808	 * any xattrs or acls
3809	 */
3810	maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3811			btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3812	if (first_xattr_slot != -1) {
3813		path->slots[0] = first_xattr_slot;
3814		ret = btrfs_load_inode_props(inode, path);
3815		if (ret)
3816			btrfs_err(fs_info,
3817				  "error loading props for ino %llu (root %llu): %d",
3818				  btrfs_ino(BTRFS_I(inode)),
3819				  root->root_key.objectid, ret);
3820	}
3821	if (path != in_path)
3822		btrfs_free_path(path);
3823
3824	if (!maybe_acls)
3825		cache_no_acl(inode);
3826
3827	switch (inode->i_mode & S_IFMT) {
3828	case S_IFREG:
3829		inode->i_mapping->a_ops = &btrfs_aops;
3830		inode->i_fop = &btrfs_file_operations;
3831		inode->i_op = &btrfs_file_inode_operations;
3832		break;
3833	case S_IFDIR:
3834		inode->i_fop = &btrfs_dir_file_operations;
3835		inode->i_op = &btrfs_dir_inode_operations;
3836		break;
3837	case S_IFLNK:
3838		inode->i_op = &btrfs_symlink_inode_operations;
3839		inode_nohighmem(inode);
3840		inode->i_mapping->a_ops = &btrfs_aops;
3841		break;
3842	default:
3843		inode->i_op = &btrfs_special_inode_operations;
3844		init_special_inode(inode, inode->i_mode, rdev);
3845		break;
3846	}
3847
3848	btrfs_sync_inode_flags_to_i_flags(inode);
3849	return 0;
3850}
3851
3852/*
3853 * given a leaf and an inode, copy the inode fields into the leaf
3854 */
3855static void fill_inode_item(struct btrfs_trans_handle *trans,
3856			    struct extent_buffer *leaf,
3857			    struct btrfs_inode_item *item,
3858			    struct inode *inode)
3859{
3860	struct btrfs_map_token token;
3861
3862	btrfs_init_map_token(&token, leaf);
3863
3864	btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
3865	btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
3866	btrfs_set_token_inode_size(&token, item, BTRFS_I(inode)->disk_i_size);
3867	btrfs_set_token_inode_mode(&token, item, inode->i_mode);
3868	btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
3869
3870	btrfs_set_token_timespec_sec(&token, &item->atime,
3871				     inode->i_atime.tv_sec);
3872	btrfs_set_token_timespec_nsec(&token, &item->atime,
3873				      inode->i_atime.tv_nsec);
3874
3875	btrfs_set_token_timespec_sec(&token, &item->mtime,
3876				     inode->i_mtime.tv_sec);
3877	btrfs_set_token_timespec_nsec(&token, &item->mtime,
3878				      inode->i_mtime.tv_nsec);
3879
3880	btrfs_set_token_timespec_sec(&token, &item->ctime,
3881				     inode->i_ctime.tv_sec);
3882	btrfs_set_token_timespec_nsec(&token, &item->ctime,
3883				      inode->i_ctime.tv_nsec);
3884
3885	btrfs_set_token_timespec_sec(&token, &item->otime,
3886				     BTRFS_I(inode)->i_otime.tv_sec);
3887	btrfs_set_token_timespec_nsec(&token, &item->otime,
3888				      BTRFS_I(inode)->i_otime.tv_nsec);
3889
3890	btrfs_set_token_inode_nbytes(&token, item, inode_get_bytes(inode));
3891	btrfs_set_token_inode_generation(&token, item,
3892					 BTRFS_I(inode)->generation);
3893	btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
3894	btrfs_set_token_inode_transid(&token, item, trans->transid);
3895	btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
3896	btrfs_set_token_inode_flags(&token, item, BTRFS_I(inode)->flags);
3897	btrfs_set_token_inode_block_group(&token, item, 0);
3898}
3899
3900/*
3901 * copy everything in the in-memory inode into the btree.
3902 */
3903static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3904				struct btrfs_root *root,
3905				struct btrfs_inode *inode)
3906{
3907	struct btrfs_inode_item *inode_item;
3908	struct btrfs_path *path;
3909	struct extent_buffer *leaf;
3910	int ret;
3911
3912	path = btrfs_alloc_path();
3913	if (!path)
3914		return -ENOMEM;
3915
3916	ret = btrfs_lookup_inode(trans, root, path, &inode->location, 1);
3917	if (ret) {
3918		if (ret > 0)
3919			ret = -ENOENT;
3920		goto failed;
3921	}
3922
3923	leaf = path->nodes[0];
3924	inode_item = btrfs_item_ptr(leaf, path->slots[0],
3925				    struct btrfs_inode_item);
3926
3927	fill_inode_item(trans, leaf, inode_item, &inode->vfs_inode);
3928	btrfs_mark_buffer_dirty(leaf);
3929	btrfs_set_inode_last_trans(trans, inode);
3930	ret = 0;
3931failed:
3932	btrfs_free_path(path);
3933	return ret;
3934}
3935
3936/*
3937 * copy everything in the in-memory inode into the btree.
3938 */
3939noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3940				struct btrfs_root *root,
3941				struct btrfs_inode *inode)
3942{
3943	struct btrfs_fs_info *fs_info = root->fs_info;
3944	int ret;
3945
3946	/*
3947	 * If the inode is a free space inode, we can deadlock during commit
3948	 * if we put it into the delayed code.
3949	 *
3950	 * The data relocation inode should also be directly updated
3951	 * without delay
3952	 */
3953	if (!btrfs_is_free_space_inode(inode)
3954	    && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3955	    && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3956		btrfs_update_root_times(trans, root);
3957
3958		ret = btrfs_delayed_update_inode(trans, root, inode);
3959		if (!ret)
3960			btrfs_set_inode_last_trans(trans, inode);
3961		return ret;
3962	}
3963
3964	return btrfs_update_inode_item(trans, root, inode);
3965}
3966
3967int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3968				struct btrfs_root *root, struct btrfs_inode *inode)
3969{
3970	int ret;
3971
3972	ret = btrfs_update_inode(trans, root, inode);
3973	if (ret == -ENOSPC)
3974		return btrfs_update_inode_item(trans, root, inode);
3975	return ret;
3976}
3977
3978/*
3979 * unlink helper that gets used here in inode.c and in the tree logging
3980 * recovery code.  It remove a link in a directory with a given name, and
3981 * also drops the back refs in the inode to the directory
3982 */
3983static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3984				struct btrfs_root *root,
3985				struct btrfs_inode *dir,
3986				struct btrfs_inode *inode,
3987				const char *name, int name_len)
3988{
3989	struct btrfs_fs_info *fs_info = root->fs_info;
3990	struct btrfs_path *path;
3991	int ret = 0;
3992	struct btrfs_dir_item *di;
3993	u64 index;
3994	u64 ino = btrfs_ino(inode);
3995	u64 dir_ino = btrfs_ino(dir);
3996
3997	path = btrfs_alloc_path();
3998	if (!path) {
3999		ret = -ENOMEM;
4000		goto out;
4001	}
4002
4003	di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4004				    name, name_len, -1);
4005	if (IS_ERR_OR_NULL(di)) {
4006		ret = di ? PTR_ERR(di) : -ENOENT;
4007		goto err;
4008	}
4009	ret = btrfs_delete_one_dir_name(trans, root, path, di);
4010	if (ret)
4011		goto err;
4012	btrfs_release_path(path);
4013
4014	/*
4015	 * If we don't have dir index, we have to get it by looking up
4016	 * the inode ref, since we get the inode ref, remove it directly,
4017	 * it is unnecessary to do delayed deletion.
4018	 *
4019	 * But if we have dir index, needn't search inode ref to get it.
4020	 * Since the inode ref is close to the inode item, it is better
4021	 * that we delay to delete it, and just do this deletion when
4022	 * we update the inode item.
4023	 */
4024	if (inode->dir_index) {
4025		ret = btrfs_delayed_delete_inode_ref(inode);
4026		if (!ret) {
4027			index = inode->dir_index;
4028			goto skip_backref;
4029		}
4030	}
4031
4032	ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4033				  dir_ino, &index);
4034	if (ret) {
4035		btrfs_info(fs_info,
4036			"failed to delete reference to %.*s, inode %llu parent %llu",
4037			name_len, name, ino, dir_ino);
4038		btrfs_abort_transaction(trans, ret);
4039		goto err;
4040	}
4041skip_backref:
4042	ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4043	if (ret) {
4044		btrfs_abort_transaction(trans, ret);
4045		goto err;
4046	}
4047
4048	ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4049			dir_ino);
4050	if (ret != 0 && ret != -ENOENT) {
4051		btrfs_abort_transaction(trans, ret);
4052		goto err;
4053	}
4054
4055	ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4056			index);
4057	if (ret == -ENOENT)
4058		ret = 0;
4059	else if (ret)
4060		btrfs_abort_transaction(trans, ret);
4061
4062	/*
4063	 * If we have a pending delayed iput we could end up with the final iput
4064	 * being run in btrfs-cleaner context.  If we have enough of these built
4065	 * up we can end up burning a lot of time in btrfs-cleaner without any
4066	 * way to throttle the unlinks.  Since we're currently holding a ref on
4067	 * the inode we can run the delayed iput here without any issues as the
4068	 * final iput won't be done until after we drop the ref we're currently
4069	 * holding.
4070	 */
4071	btrfs_run_delayed_iput(fs_info, inode);
4072err:
4073	btrfs_free_path(path);
4074	if (ret)
4075		goto out;
4076
4077	btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4078	inode_inc_iversion(&inode->vfs_inode);
4079	inode_inc_iversion(&dir->vfs_inode);
4080	inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4081		dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4082	ret = btrfs_update_inode(trans, root, dir);
4083out:
4084	return ret;
4085}
4086
4087int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4088		       struct btrfs_root *root,
4089		       struct btrfs_inode *dir, struct btrfs_inode *inode,
4090		       const char *name, int name_len)
4091{
4092	int ret;
4093	ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4094	if (!ret) {
4095		drop_nlink(&inode->vfs_inode);
4096		ret = btrfs_update_inode(trans, root, inode);
4097	}
4098	return ret;
4099}
4100
4101/*
4102 * helper to start transaction for unlink and rmdir.
4103 *
4104 * unlink and rmdir are special in btrfs, they do not always free space, so
4105 * if we cannot make our reservations the normal way try and see if there is
4106 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4107 * allow the unlink to occur.
4108 */
4109static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4110{
4111	struct btrfs_root *root = BTRFS_I(dir)->root;
4112
4113	/*
4114	 * 1 for the possible orphan item
4115	 * 1 for the dir item
4116	 * 1 for the dir index
4117	 * 1 for the inode ref
4118	 * 1 for the inode
4119	 */
4120	return btrfs_start_transaction_fallback_global_rsv(root, 5);
4121}
4122
4123static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4124{
4125	struct btrfs_root *root = BTRFS_I(dir)->root;
4126	struct btrfs_trans_handle *trans;
4127	struct inode *inode = d_inode(dentry);
4128	int ret;
4129
4130	trans = __unlink_start_trans(dir);
4131	if (IS_ERR(trans))
4132		return PTR_ERR(trans);
4133
4134	btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4135			0);
4136
4137	ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4138			BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4139			dentry->d_name.len);
4140	if (ret)
4141		goto out;
4142
4143	if (inode->i_nlink == 0) {
4144		ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4145		if (ret)
4146			goto out;
4147	}
4148
4149out:
4150	btrfs_end_transaction(trans);
4151	btrfs_btree_balance_dirty(root->fs_info);
4152	return ret;
4153}
4154
4155static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4156			       struct inode *dir, struct dentry *dentry)
4157{
4158	struct btrfs_root *root = BTRFS_I(dir)->root;
4159	struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
4160	struct btrfs_path *path;
4161	struct extent_buffer *leaf;
4162	struct btrfs_dir_item *di;
4163	struct btrfs_key key;
4164	const char *name = dentry->d_name.name;
4165	int name_len = dentry->d_name.len;
4166	u64 index;
4167	int ret;
4168	u64 objectid;
4169	u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4170
4171	if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
4172		objectid = inode->root->root_key.objectid;
4173	} else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4174		objectid = inode->location.objectid;
4175	} else {
4176		WARN_ON(1);
4177		return -EINVAL;
4178	}
4179
4180	path = btrfs_alloc_path();
4181	if (!path)
4182		return -ENOMEM;
4183
4184	di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4185				   name, name_len, -1);
4186	if (IS_ERR_OR_NULL(di)) {
4187		ret = di ? PTR_ERR(di) : -ENOENT;
4188		goto out;
4189	}
4190
4191	leaf = path->nodes[0];
4192	btrfs_dir_item_key_to_cpu(leaf, di, &key);
4193	WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4194	ret = btrfs_delete_one_dir_name(trans, root, path, di);
4195	if (ret) {
4196		btrfs_abort_transaction(trans, ret);
4197		goto out;
4198	}
4199	btrfs_release_path(path);
4200
4201	/*
4202	 * This is a placeholder inode for a subvolume we didn't have a
4203	 * reference to at the time of the snapshot creation.  In the meantime
4204	 * we could have renamed the real subvol link into our snapshot, so
4205	 * depending on btrfs_del_root_ref to return -ENOENT here is incorrect.
4206	 * Instead simply lookup the dir_index_item for this entry so we can
4207	 * remove it.  Otherwise we know we have a ref to the root and we can
4208	 * call btrfs_del_root_ref, and it _shouldn't_ fail.
4209	 */
4210	if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4211		di = btrfs_search_dir_index_item(root, path, dir_ino,
4212						 name, name_len);
4213		if (IS_ERR_OR_NULL(di)) {
4214			if (!di)
4215				ret = -ENOENT;
4216			else
4217				ret = PTR_ERR(di);
4218			btrfs_abort_transaction(trans, ret);
4219			goto out;
4220		}
4221
4222		leaf = path->nodes[0];
4223		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4224		index = key.offset;
4225		btrfs_release_path(path);
4226	} else {
4227		ret = btrfs_del_root_ref(trans, objectid,
4228					 root->root_key.objectid, dir_ino,
4229					 &index, name, name_len);
4230		if (ret) {
4231			btrfs_abort_transaction(trans, ret);
4232			goto out;
4233		}
4234	}
4235
4236	ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
4237	if (ret) {
4238		btrfs_abort_transaction(trans, ret);
4239		goto out;
4240	}
4241
4242	btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4243	inode_inc_iversion(dir);
4244	dir->i_mtime = dir->i_ctime = current_time(dir);
4245	ret = btrfs_update_inode_fallback(trans, root, BTRFS_I(dir));
4246	if (ret)
4247		btrfs_abort_transaction(trans, ret);
4248out:
4249	btrfs_free_path(path);
4250	return ret;
4251}
4252
4253/*
4254 * Helper to check if the subvolume references other subvolumes or if it's
4255 * default.
4256 */
4257static noinline int may_destroy_subvol(struct btrfs_root *root)
4258{
4259	struct btrfs_fs_info *fs_info = root->fs_info;
4260	struct btrfs_path *path;
4261	struct btrfs_dir_item *di;
4262	struct btrfs_key key;
4263	u64 dir_id;
4264	int ret;
4265
4266	path = btrfs_alloc_path();
4267	if (!path)
4268		return -ENOMEM;
4269
4270	/* Make sure this root isn't set as the default subvol */
4271	dir_id = btrfs_super_root_dir(fs_info->super_copy);
4272	di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4273				   dir_id, "default", 7, 0);
4274	if (di && !IS_ERR(di)) {
4275		btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4276		if (key.objectid == root->root_key.objectid) {
4277			ret = -EPERM;
4278			btrfs_err(fs_info,
4279				  "deleting default subvolume %llu is not allowed",
4280				  key.objectid);
4281			goto out;
4282		}
4283		btrfs_release_path(path);
4284	}
4285
4286	key.objectid = root->root_key.objectid;
4287	key.type = BTRFS_ROOT_REF_KEY;
4288	key.offset = (u64)-1;
4289
4290	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4291	if (ret < 0)
4292		goto out;
4293	BUG_ON(ret == 0);
4294
4295	ret = 0;
4296	if (path->slots[0] > 0) {
4297		path->slots[0]--;
4298		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4299		if (key.objectid == root->root_key.objectid &&
4300		    key.type == BTRFS_ROOT_REF_KEY)
4301			ret = -ENOTEMPTY;
4302	}
4303out:
4304	btrfs_free_path(path);
4305	return ret;
4306}
4307
4308/* Delete all dentries for inodes belonging to the root */
4309static void btrfs_prune_dentries(struct btrfs_root *root)
4310{
4311	struct btrfs_fs_info *fs_info = root->fs_info;
4312	struct rb_node *node;
4313	struct rb_node *prev;
4314	struct btrfs_inode *entry;
4315	struct inode *inode;
4316	u64 objectid = 0;
4317
4318	if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
4319		WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4320
4321	spin_lock(&root->inode_lock);
4322again:
4323	node = root->inode_tree.rb_node;
4324	prev = NULL;
4325	while (node) {
4326		prev = node;
4327		entry = rb_entry(node, struct btrfs_inode, rb_node);
4328
4329		if (objectid < btrfs_ino(entry))
4330			node = node->rb_left;
4331		else if (objectid > btrfs_ino(entry))
4332			node = node->rb_right;
4333		else
4334			break;
4335	}
4336	if (!node) {
4337		while (prev) {
4338			entry = rb_entry(prev, struct btrfs_inode, rb_node);
4339			if (objectid <= btrfs_ino(entry)) {
4340				node = prev;
4341				break;
4342			}
4343			prev = rb_next(prev);
4344		}
4345	}
4346	while (node) {
4347		entry = rb_entry(node, struct btrfs_inode, rb_node);
4348		objectid = btrfs_ino(entry) + 1;
4349		inode = igrab(&entry->vfs_inode);
4350		if (inode) {
4351			spin_unlock(&root->inode_lock);
4352			if (atomic_read(&inode->i_count) > 1)
4353				d_prune_aliases(inode);
4354			/*
4355			 * btrfs_drop_inode will have it removed from the inode
4356			 * cache when its usage count hits zero.
4357			 */
4358			iput(inode);
4359			cond_resched();
4360			spin_lock(&root->inode_lock);
4361			goto again;
4362		}
4363
4364		if (cond_resched_lock(&root->inode_lock))
4365			goto again;
4366
4367		node = rb_next(node);
4368	}
4369	spin_unlock(&root->inode_lock);
4370}
4371
4372int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4373{
4374	struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4375	struct btrfs_root *root = BTRFS_I(dir)->root;
4376	struct inode *inode = d_inode(dentry);
4377	struct btrfs_root *dest = BTRFS_I(inode)->root;
4378	struct btrfs_trans_handle *trans;
4379	struct btrfs_block_rsv block_rsv;
4380	u64 root_flags;
4381	int ret;
4382
4383	/*
4384	 * Don't allow to delete a subvolume with send in progress. This is
4385	 * inside the inode lock so the error handling that has to drop the bit
4386	 * again is not run concurrently.
4387	 */
4388	spin_lock(&dest->root_item_lock);
4389	if (dest->send_in_progress) {
4390		spin_unlock(&dest->root_item_lock);
4391		btrfs_warn(fs_info,
4392			   "attempt to delete subvolume %llu during send",
4393			   dest->root_key.objectid);
4394		return -EPERM;
4395	}
4396	root_flags = btrfs_root_flags(&dest->root_item);
4397	btrfs_set_root_flags(&dest->root_item,
4398			     root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4399	spin_unlock(&dest->root_item_lock);
4400
4401	down_write(&fs_info->subvol_sem);
4402
4403	ret = may_destroy_subvol(dest);
4404	if (ret)
4405		goto out_up_write;
4406
4407	btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4408	/*
4409	 * One for dir inode,
4410	 * two for dir entries,
4411	 * two for root ref/backref.
4412	 */
4413	ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4414	if (ret)
4415		goto out_up_write;
4416
4417	trans = btrfs_start_transaction(root, 0);
4418	if (IS_ERR(trans)) {
4419		ret = PTR_ERR(trans);
4420		goto out_release;
4421	}
4422	trans->block_rsv = &block_rsv;
4423	trans->bytes_reserved = block_rsv.size;
4424
4425	btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4426
4427	ret = btrfs_unlink_subvol(trans, dir, dentry);
4428	if (ret) {
4429		btrfs_abort_transaction(trans, ret);
4430		goto out_end_trans;
4431	}
4432
4433	ret = btrfs_record_root_in_trans(trans, dest);
4434	if (ret) {
4435		btrfs_abort_transaction(trans, ret);
4436		goto out_end_trans;
4437	}
4438
4439	memset(&dest->root_item.drop_progress, 0,
4440		sizeof(dest->root_item.drop_progress));
4441	btrfs_set_root_drop_level(&dest->root_item, 0);
4442	btrfs_set_root_refs(&dest->root_item, 0);
4443
4444	if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4445		ret = btrfs_insert_orphan_item(trans,
4446					fs_info->tree_root,
4447					dest->root_key.objectid);
4448		if (ret) {
4449			btrfs_abort_transaction(trans, ret);
4450			goto out_end_trans;
4451		}
4452	}
4453
4454	ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4455				  BTRFS_UUID_KEY_SUBVOL,
4456				  dest->root_key.objectid);
4457	if (ret && ret != -ENOENT) {
4458		btrfs_abort_transaction(trans, ret);
4459		goto out_end_trans;
4460	}
4461	if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4462		ret = btrfs_uuid_tree_remove(trans,
4463					  dest->root_item.received_uuid,
4464					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4465					  dest->root_key.objectid);
4466		if (ret && ret != -ENOENT) {
4467			btrfs_abort_transaction(trans, ret);
4468			goto out_end_trans;
4469		}
4470	}
4471
4472	free_anon_bdev(dest->anon_dev);
4473	dest->anon_dev = 0;
4474out_end_trans:
4475	trans->block_rsv = NULL;
4476	trans->bytes_reserved = 0;
4477	ret = btrfs_end_transaction(trans);
4478	inode->i_flags |= S_DEAD;
4479out_release:
4480	btrfs_subvolume_release_metadata(root, &block_rsv);
4481out_up_write:
4482	up_write(&fs_info->subvol_sem);
4483	if (ret) {
4484		spin_lock(&dest->root_item_lock);
4485		root_flags = btrfs_root_flags(&dest->root_item);
4486		btrfs_set_root_flags(&dest->root_item,
4487				root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4488		spin_unlock(&dest->root_item_lock);
4489	} else {
4490		d_invalidate(dentry);
4491		btrfs_prune_dentries(dest);
4492		ASSERT(dest->send_in_progress == 0);
4493	}
4494
4495	return ret;
4496}
4497
4498static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4499{
4500	struct inode *inode = d_inode(dentry);
4501	int err = 0;
4502	struct btrfs_root *root = BTRFS_I(dir)->root;
4503	struct btrfs_trans_handle *trans;
4504	u64 last_unlink_trans;
4505
4506	if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4507		return -ENOTEMPTY;
4508	if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4509		return btrfs_delete_subvolume(dir, dentry);
4510
4511	trans = __unlink_start_trans(dir);
4512	if (IS_ERR(trans))
4513		return PTR_ERR(trans);
4514
4515	if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4516		err = btrfs_unlink_subvol(trans, dir, dentry);
4517		goto out;
4518	}
4519
4520	err = btrfs_orphan_add(trans, BTRFS_I(inode));
4521	if (err)
4522		goto out;
4523
4524	last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4525
4526	/* now the directory is empty */
4527	err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4528			BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4529			dentry->d_name.len);
4530	if (!err) {
4531		btrfs_i_size_write(BTRFS_I(inode), 0);
4532		/*
4533		 * Propagate the last_unlink_trans value of the deleted dir to
4534		 * its parent directory. This is to prevent an unrecoverable
4535		 * log tree in the case we do something like this:
4536		 * 1) create dir foo
4537		 * 2) create snapshot under dir foo
4538		 * 3) delete the snapshot
4539		 * 4) rmdir foo
4540		 * 5) mkdir foo
4541		 * 6) fsync foo or some file inside foo
4542		 */
4543		if (last_unlink_trans >= trans->transid)
4544			BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4545	}
4546out:
4547	btrfs_end_transaction(trans);
4548	btrfs_btree_balance_dirty(root->fs_info);
4549
4550	return err;
4551}
4552
4553/*
4554 * Return this if we need to call truncate_block for the last bit of the
4555 * truncate.
4556 */
4557#define NEED_TRUNCATE_BLOCK 1
4558
4559/*
4560 * Remove inode items from a given root.
4561 *
4562 * @trans:		A transaction handle.
4563 * @root:		The root from which to remove items.
4564 * @inode:		The inode whose items we want to remove.
4565 * @new_size:		The new i_size for the inode. This is only applicable when
4566 *			@min_type is BTRFS_EXTENT_DATA_KEY, must be 0 otherwise.
4567 * @min_type:		The minimum key type to remove. All keys with a type
4568 *			greater than this value are removed and all keys with
4569 *			this type are removed only if their offset is >= @new_size.
4570 * @extents_found:	Output parameter that will contain the number of file
4571 *			extent items that were removed or adjusted to the new
4572 *			inode i_size. The caller is responsible for initializing
4573 *			the counter. Also, it can be NULL if the caller does not
4574 *			need this counter.
4575 *
4576 * Remove all keys associated with the inode from the given root that have a key
4577 * with a type greater than or equals to @min_type. When @min_type has a value of
4578 * BTRFS_EXTENT_DATA_KEY, only remove file extent items that have an offset value
4579 * greater than or equals to @new_size. If a file extent item that starts before
4580 * @new_size and ends after it is found, its length is adjusted.
4581 *
4582 * Returns: 0 on success, < 0 on error and NEED_TRUNCATE_BLOCK when @min_type is
4583 * BTRFS_EXTENT_DATA_KEY and the caller must truncate the last block.
4584 */
4585int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4586			       struct btrfs_root *root,
4587			       struct btrfs_inode *inode,
4588			       u64 new_size, u32 min_type,
4589			       u64 *extents_found)
4590{
4591	struct btrfs_fs_info *fs_info = root->fs_info;
4592	struct btrfs_path *path;
4593	struct extent_buffer *leaf;
4594	struct btrfs_file_extent_item *fi;
4595	struct btrfs_key key;
4596	struct btrfs_key found_key;
4597	u64 extent_start = 0;
4598	u64 extent_num_bytes = 0;
4599	u64 extent_offset = 0;
4600	u64 item_end = 0;
4601	u64 last_size = new_size;
4602	u32 found_type = (u8)-1;
4603	int found_extent;
4604	int del_item;
4605	int pending_del_nr = 0;
4606	int pending_del_slot = 0;
4607	int extent_type = -1;
4608	int ret;
4609	u64 ino = btrfs_ino(inode);
4610	u64 bytes_deleted = 0;
4611	bool be_nice = false;
4612	bool should_throttle = false;
4613	const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
4614	struct extent_state *cached_state = NULL;
4615
4616	BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4617
4618	/*
4619	 * For non-free space inodes and non-shareable roots, we want to back
4620	 * off from time to time.  This means all inodes in subvolume roots,
4621	 * reloc roots, and data reloc roots.
4622	 */
4623	if (!btrfs_is_free_space_inode(inode) &&
4624	    test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4625		be_nice = true;
4626
4627	path = btrfs_alloc_path();
4628	if (!path)
4629		return -ENOMEM;
4630	path->reada = READA_BACK;
4631
4632	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4633		lock_extent_bits(&inode->io_tree, lock_start, (u64)-1,
4634				 &cached_state);
4635
4636		/*
4637		 * We want to drop from the next block forward in case this
4638		 * new size is not block aligned since we will be keeping the
4639		 * last block of the extent just the way it is.
4640		 */
4641		btrfs_drop_extent_cache(inode, ALIGN(new_size,
4642					fs_info->sectorsize),
4643					(u64)-1, 0);
4644	}
4645
4646	/*
4647	 * This function is also used to drop the items in the log tree before
4648	 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4649	 * it is used to drop the logged items. So we shouldn't kill the delayed
4650	 * items.
4651	 */
4652	if (min_type == 0 && root == inode->root)
4653		btrfs_kill_delayed_inode_items(inode);
4654
4655	key.objectid = ino;
4656	key.offset = (u64)-1;
4657	key.type = (u8)-1;
4658
4659search_again:
4660	/*
4661	 * with a 16K leaf size and 128MB extents, you can actually queue
4662	 * up a huge file in a single leaf.  Most of the time that
4663	 * bytes_deleted is > 0, it will be huge by the time we get here
4664	 */
4665	if (be_nice && bytes_deleted > SZ_32M &&
4666	    btrfs_should_end_transaction(trans)) {
4667		ret = -EAGAIN;
4668		goto out;
4669	}
4670
4671	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4672	if (ret < 0)
4673		goto out;
4674
4675	if (ret > 0) {
4676		ret = 0;
4677		/* there are no items in the tree for us to truncate, we're
4678		 * done
4679		 */
4680		if (path->slots[0] == 0)
4681			goto out;
4682		path->slots[0]--;
4683	}
4684
4685	while (1) {
4686		u64 clear_start = 0, clear_len = 0;
4687
4688		fi = NULL;
4689		leaf = path->nodes[0];
4690		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4691		found_type = found_key.type;
4692
4693		if (found_key.objectid != ino)
4694			break;
4695
4696		if (found_type < min_type)
4697			break;
4698
4699		item_end = found_key.offset;
4700		if (found_type == BTRFS_EXTENT_DATA_KEY) {
4701			fi = btrfs_item_ptr(leaf, path->slots[0],
4702					    struct btrfs_file_extent_item);
4703			extent_type = btrfs_file_extent_type(leaf, fi);
4704			if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4705				item_end +=
4706				    btrfs_file_extent_num_bytes(leaf, fi);
4707
4708				trace_btrfs_truncate_show_fi_regular(
4709					inode, leaf, fi, found_key.offset);
4710			} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4711				item_end += btrfs_file_extent_ram_bytes(leaf,
4712									fi);
4713
4714				trace_btrfs_truncate_show_fi_inline(
4715					inode, leaf, fi, path->slots[0],
4716					found_key.offset);
4717			}
4718			item_end--;
4719		}
4720		if (found_type > min_type) {
4721			del_item = 1;
4722		} else {
4723			if (item_end < new_size)
4724				break;
4725			if (found_key.offset >= new_size)
4726				del_item = 1;
4727			else
4728				del_item = 0;
4729		}
4730		found_extent = 0;
4731		/* FIXME, shrink the extent if the ref count is only 1 */
4732		if (found_type != BTRFS_EXTENT_DATA_KEY)
4733			goto delete;
4734
4735		if (extents_found != NULL)
4736			(*extents_found)++;
4737
4738		if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4739			u64 num_dec;
4740
4741			clear_start = found_key.offset;
4742			extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4743			if (!del_item) {
4744				u64 orig_num_bytes =
4745					btrfs_file_extent_num_bytes(leaf, fi);
4746				extent_num_bytes = ALIGN(new_size -
4747						found_key.offset,
4748						fs_info->sectorsize);
4749				clear_start = ALIGN(new_size, fs_info->sectorsize);
4750				btrfs_set_file_extent_num_bytes(leaf, fi,
4751							 extent_num_bytes);
4752				num_dec = (orig_num_bytes -
4753					   extent_num_bytes);
4754				if (test_bit(BTRFS_ROOT_SHAREABLE,
4755					     &root->state) &&
4756				    extent_start != 0)
4757					inode_sub_bytes(&inode->vfs_inode,
4758							num_dec);
4759				btrfs_mark_buffer_dirty(leaf);
4760			} else {
4761				extent_num_bytes =
4762					btrfs_file_extent_disk_num_bytes(leaf,
4763									 fi);
4764				extent_offset = found_key.offset -
4765					btrfs_file_extent_offset(leaf, fi);
4766
4767				/* FIXME blocksize != 4096 */
4768				num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4769				if (extent_start != 0) {
4770					found_extent = 1;
4771					if (test_bit(BTRFS_ROOT_SHAREABLE,
4772						     &root->state))
4773						inode_sub_bytes(&inode->vfs_inode,
4774								num_dec);
4775				}
4776			}
4777			clear_len = num_dec;
4778		} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4779			/*
4780			 * we can't truncate inline items that have had
4781			 * special encodings
4782			 */
4783			if (!del_item &&
4784			    btrfs_file_extent_encryption(leaf, fi) == 0 &&
4785			    btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4786			    btrfs_file_extent_compression(leaf, fi) == 0) {
4787				u32 size = (u32)(new_size - found_key.offset);
4788
4789				btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4790				size = btrfs_file_extent_calc_inline_size(size);
4791				btrfs_truncate_item(path, size, 1);
4792			} else if (!del_item) {
4793				/*
4794				 * We have to bail so the last_size is set to
4795				 * just before this extent.
4796				 */
4797				ret = NEED_TRUNCATE_BLOCK;
4798				break;
4799			} else {
4800				/*
4801				 * Inline extents are special, we just treat
4802				 * them as a full sector worth in the file
4803				 * extent tree just for simplicity sake.
4804				 */
4805				clear_len = fs_info->sectorsize;
4806			}
4807
4808			if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4809				inode_sub_bytes(&inode->vfs_inode,
4810						item_end + 1 - new_size);
4811		}
4812delete:
4813		/*
4814		 * We use btrfs_truncate_inode_items() to clean up log trees for
4815		 * multiple fsyncs, and in this case we don't want to clear the
4816		 * file extent range because it's just the log.
4817		 */
4818		if (root == inode->root) {
4819			ret = btrfs_inode_clear_file_extent_range(inode,
4820						  clear_start, clear_len);
4821			if (ret) {
4822				btrfs_abort_transaction(trans, ret);
4823				break;
4824			}
4825		}
4826
4827		if (del_item)
4828			last_size = found_key.offset;
4829		else
4830			last_size = new_size;
4831		if (del_item) {
4832			if (!pending_del_nr) {
4833				/* no pending yet, add ourselves */
4834				pending_del_slot = path->slots[0];
4835				pending_del_nr = 1;
4836			} else if (pending_del_nr &&
4837				   path->slots[0] + 1 == pending_del_slot) {
4838				/* hop on the pending chunk */
4839				pending_del_nr++;
4840				pending_del_slot = path->slots[0];
4841			} else {
4842				BUG();
4843			}
4844		} else {
4845			break;
4846		}
4847		should_throttle = false;
4848
4849		if (found_extent &&
4850		    root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4851			struct btrfs_ref ref = { 0 };
4852
4853			bytes_deleted += extent_num_bytes;
4854
4855			btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4856					extent_start, extent_num_bytes, 0);
4857			ref.real_root = root->root_key.objectid;
4858			btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4859					ino, extent_offset);
4860			ret = btrfs_free_extent(trans, &ref);
4861			if (ret) {
4862				btrfs_abort_transaction(trans, ret);
4863				break;
4864			}
4865			if (be_nice) {
4866				if (btrfs_should_throttle_delayed_refs(trans))
4867					should_throttle = true;
4868			}
4869		}
4870
4871		if (found_type == BTRFS_INODE_ITEM_KEY)
4872			break;
4873
4874		if (path->slots[0] == 0 ||
4875		    path->slots[0] != pending_del_slot ||
4876		    should_throttle) {
4877			if (pending_del_nr) {
4878				ret = btrfs_del_items(trans, root, path,
4879						pending_del_slot,
4880						pending_del_nr);
4881				if (ret) {
4882					btrfs_abort_transaction(trans, ret);
4883					break;
4884				}
4885				pending_del_nr = 0;
4886			}
4887			btrfs_release_path(path);
4888
4889			/*
4890			 * We can generate a lot of delayed refs, so we need to
4891			 * throttle every once and a while and make sure we're
4892			 * adding enough space to keep up with the work we are
4893			 * generating.  Since we hold a transaction here we
4894			 * can't flush, and we don't want to FLUSH_LIMIT because
4895			 * we could have generated too many delayed refs to
4896			 * actually allocate, so just bail if we're short and
4897			 * let the normal reservation dance happen higher up.
4898			 */
4899			if (should_throttle) {
4900				ret = btrfs_delayed_refs_rsv_refill(fs_info,
4901							BTRFS_RESERVE_NO_FLUSH);
4902				if (ret) {
4903					ret = -EAGAIN;
4904					break;
4905				}
4906			}
4907			goto search_again;
4908		} else {
4909			path->slots[0]--;
4910		}
4911	}
4912out:
4913	if (ret >= 0 && pending_del_nr) {
4914		int err;
4915
4916		err = btrfs_del_items(trans, root, path, pending_del_slot,
4917				      pending_del_nr);
4918		if (err) {
4919			btrfs_abort_transaction(trans, err);
4920			ret = err;
4921		}
4922	}
4923	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4924		ASSERT(last_size >= new_size);
4925		if (!ret && last_size > new_size)
4926			last_size = new_size;
4927		btrfs_inode_safe_disk_i_size_write(inode, last_size);
4928		unlock_extent_cached(&inode->io_tree, lock_start, (u64)-1,
4929				     &cached_state);
4930	}
4931
4932	btrfs_free_path(path);
4933	return ret;
4934}
4935
4936/*
4937 * btrfs_truncate_block - read, zero a chunk and write a block
4938 * @inode - inode that we're zeroing
4939 * @from - the offset to start zeroing
4940 * @len - the length to zero, 0 to zero the entire range respective to the
4941 *	offset
4942 * @front - zero up to the offset instead of from the offset on
4943 *
4944 * This will find the block for the "from" offset and cow the block and zero the
4945 * part we want to zero.  This is used with truncate and hole punching.
4946 */
4947int btrfs_truncate_block(struct btrfs_inode *inode, loff_t from, loff_t len,
4948			 int front)
4949{
4950	struct btrfs_fs_info *fs_info = inode->root->fs_info;
4951	struct address_space *mapping = inode->vfs_inode.i_mapping;
4952	struct extent_io_tree *io_tree = &inode->io_tree;
4953	struct btrfs_ordered_extent *ordered;
4954	struct extent_state *cached_state = NULL;
4955	struct extent_changeset *data_reserved = NULL;
4956	bool only_release_metadata = false;
4957	u32 blocksize = fs_info->sectorsize;
4958	pgoff_t index = from >> PAGE_SHIFT;
4959	unsigned offset = from & (blocksize - 1);
4960	struct page *page;
4961	gfp_t mask = btrfs_alloc_write_mask(mapping);
4962	size_t write_bytes = blocksize;
4963	int ret = 0;
4964	u64 block_start;
4965	u64 block_end;
4966
4967	if (IS_ALIGNED(offset, blocksize) &&
4968	    (!len || IS_ALIGNED(len, blocksize)))
4969		goto out;
4970
4971	block_start = round_down(from, blocksize);
4972	block_end = block_start + blocksize - 1;
4973
4974	ret = btrfs_check_data_free_space(inode, &data_reserved, block_start,
4975					  blocksize);
4976	if (ret < 0) {
4977		if (btrfs_check_nocow_lock(inode, block_start, &write_bytes) > 0) {
4978			/* For nocow case, no need to reserve data space */
4979			only_release_metadata = true;
4980		} else {
4981			goto out;
4982		}
4983	}
4984	ret = btrfs_delalloc_reserve_metadata(inode, blocksize);
4985	if (ret < 0) {
4986		if (!only_release_metadata)
4987			btrfs_free_reserved_data_space(inode, data_reserved,
4988						       block_start, blocksize);
4989		goto out;
4990	}
4991again:
4992	page = find_or_create_page(mapping, index, mask);
4993	if (!page) {
4994		btrfs_delalloc_release_space(inode, data_reserved, block_start,
4995					     blocksize, true);
4996		btrfs_delalloc_release_extents(inode, blocksize);
4997		ret = -ENOMEM;
4998		goto out;
4999	}
5000	ret = set_page_extent_mapped(page);
5001	if (ret < 0)
5002		goto out_unlock;
5003
5004	if (!PageUptodate(page)) {
5005		ret = btrfs_readpage(NULL, page);
5006		lock_page(page);
5007		if (page->mapping != mapping) {
5008			unlock_page(page);
5009			put_page(page);
5010			goto again;
5011		}
5012		if (!PageUptodate(page)) {
5013			ret = -EIO;
5014			goto out_unlock;
5015		}
5016	}
5017	wait_on_page_writeback(page);
5018
5019	lock_extent_bits(io_tree, block_start, block_end, &cached_state);
5020
5021	ordered = btrfs_lookup_ordered_extent(inode, block_start);
5022	if (ordered) {
5023		unlock_extent_cached(io_tree, block_start, block_end,
5024				     &cached_state);
5025		unlock_page(page);
5026		put_page(page);
5027		btrfs_start_ordered_extent(ordered, 1);
5028		btrfs_put_ordered_extent(ordered);
5029		goto again;
5030	}
5031
5032	clear_extent_bit(&inode->io_tree, block_start, block_end,
5033			 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
5034			 0, 0, &cached_state);
5035
5036	ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
5037					&cached_state);
5038	if (ret) {
5039		unlock_extent_cached(io_tree, block_start, block_end,
5040				     &cached_state);
5041		goto out_unlock;
5042	}
5043
5044	if (offset != blocksize) {
5045		if (!len)
5046			len = blocksize - offset;
5047		if (front)
5048			memzero_page(page, (block_start - page_offset(page)),
5049				     offset);
5050		else
5051			memzero_page(page, (block_start - page_offset(page)) + offset,
5052				     len);
5053		flush_dcache_page(page);
5054	}
5055	ClearPageChecked(page);
5056	btrfs_page_set_dirty(fs_info, page, block_start, block_end + 1 - block_start);
5057	unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
5058
5059	if (only_release_metadata)
5060		set_extent_bit(&inode->io_tree, block_start, block_end,
5061			       EXTENT_NORESERVE, 0, NULL, NULL, GFP_NOFS, NULL);
5062
5063out_unlock:
5064	if (ret) {
5065		if (only_release_metadata)
5066			btrfs_delalloc_release_metadata(inode, blocksize, true);
5067		else
5068			btrfs_delalloc_release_space(inode, data_reserved,
5069					block_start, blocksize, true);
5070	}
5071	btrfs_delalloc_release_extents(inode, blocksize);
5072	unlock_page(page);
5073	put_page(page);
5074out:
5075	if (only_release_metadata)
5076		btrfs_check_nocow_unlock(inode);
5077	extent_changeset_free(data_reserved);
5078	return ret;
5079}
5080
5081static int maybe_insert_hole(struct btrfs_root *root, struct btrfs_inode *inode,
5082			     u64 offset, u64 len)
5083{
5084	struct btrfs_fs_info *fs_info = root->fs_info;
5085	struct btrfs_trans_handle *trans;
5086	struct btrfs_drop_extents_args drop_args = { 0 };
5087	int ret;
5088
5089	/*
5090	 * If NO_HOLES is enabled, we don't need to do anything.
5091	 * Later, up in the call chain, either btrfs_set_inode_last_sub_trans()
5092	 * or btrfs_update_inode() will be called, which guarantee that the next
5093	 * fsync will know this inode was changed and needs to be logged.
5094	 */
5095	if (btrfs_fs_incompat(fs_info, NO_HOLES))
5096		return 0;
5097
5098	/*
5099	 * 1 - for the one we're dropping
5100	 * 1 - for the one we're adding
5101	 * 1 - for updating the inode.
5102	 */
5103	trans = btrfs_start_transaction(root, 3);
5104	if (IS_ERR(trans))
5105		return PTR_ERR(trans);
5106
5107	drop_args.start = offset;
5108	drop_args.end = offset + len;
5109	drop_args.drop_cache = true;
5110
5111	ret = btrfs_drop_extents(trans, root, inode, &drop_args);
5112	if (ret) {
5113		btrfs_abort_transaction(trans, ret);
5114		btrfs_end_transaction(trans);
5115		return ret;
5116	}
5117
5118	ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode),
5119			offset, 0, 0, len, 0, len, 0, 0, 0);
5120	if (ret) {
5121		btrfs_abort_transaction(trans, ret);
5122	} else {
5123		btrfs_update_inode_bytes(inode, 0, drop_args.bytes_found);
5124		btrfs_update_inode(trans, root, inode);
5125	}
5126	btrfs_end_transaction(trans);
5127	return ret;
5128}
5129
5130/*
5131 * This function puts in dummy file extents for the area we're creating a hole
5132 * for.  So if we are truncating this file to a larger size we need to insert
5133 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5134 * the range between oldsize and size
5135 */
5136int btrfs_cont_expand(struct btrfs_inode *inode, loff_t oldsize, loff_t size)
5137{
5138	struct btrfs_root *root = inode->root;
5139	struct btrfs_fs_info *fs_info = root->fs_info;
5140	struct extent_io_tree *io_tree = &inode->io_tree;
5141	struct extent_map *em = NULL;
5142	struct extent_state *cached_state = NULL;
5143	struct extent_map_tree *em_tree = &inode->extent_tree;
5144	u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5145	u64 block_end = ALIGN(size, fs_info->sectorsize);
5146	u64 last_byte;
5147	u64 cur_offset;
5148	u64 hole_size;
5149	int err = 0;
5150
5151	/*
5152	 * If our size started in the middle of a block we need to zero out the
5153	 * rest of the block before we expand the i_size, otherwise we could
5154	 * expose stale data.
5155	 */
5156	err = btrfs_truncate_block(inode, oldsize, 0, 0);
5157	if (err)
5158		return err;
5159
5160	if (size <= hole_start)
5161		return 0;
5162
5163	btrfs_lock_and_flush_ordered_range(inode, hole_start, block_end - 1,
5164					   &cached_state);
5165	cur_offset = hole_start;
5166	while (1) {
5167		em = btrfs_get_extent(inode, NULL, 0, cur_offset,
5168				      block_end - cur_offset);
5169		if (IS_ERR(em)) {
5170			err = PTR_ERR(em);
5171			em = NULL;
5172			break;
5173		}
5174		last_byte = min(extent_map_end(em), block_end);
5175		last_byte = ALIGN(last_byte, fs_info->sectorsize);
5176		hole_size = last_byte - cur_offset;
5177
5178		if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5179			struct extent_map *hole_em;
5180
5181			err = maybe_insert_hole(root, inode, cur_offset,
5182						hole_size);
5183			if (err)
5184				break;
5185
5186			err = btrfs_inode_set_file_extent_range(inode,
5187							cur_offset, hole_size);
5188			if (err)
5189				break;
5190
5191			btrfs_drop_extent_cache(inode, cur_offset,
5192						cur_offset + hole_size - 1, 0);
5193			hole_em = alloc_extent_map();
5194			if (!hole_em) {
5195				set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5196					&inode->runtime_flags);
5197				goto next;
5198			}
5199			hole_em->start = cur_offset;
5200			hole_em->len = hole_size;
5201			hole_em->orig_start = cur_offset;
5202
5203			hole_em->block_start = EXTENT_MAP_HOLE;
5204			hole_em->block_len = 0;
5205			hole_em->orig_block_len = 0;
5206			hole_em->ram_bytes = hole_size;
5207			hole_em->compress_type = BTRFS_COMPRESS_NONE;
5208			hole_em->generation = fs_info->generation;
5209
5210			while (1) {
5211				write_lock(&em_tree->lock);
5212				err = add_extent_mapping(em_tree, hole_em, 1);
5213				write_unlock(&em_tree->lock);
5214				if (err != -EEXIST)
5215					break;
5216				btrfs_drop_extent_cache(inode, cur_offset,
5217							cur_offset +
5218							hole_size - 1, 0);
5219			}
5220			free_extent_map(hole_em);
5221		} else {
5222			err = btrfs_inode_set_file_extent_range(inode,
5223							cur_offset, hole_size);
5224			if (err)
5225				break;
5226		}
5227next:
5228		free_extent_map(em);
5229		em = NULL;
5230		cur_offset = last_byte;
5231		if (cur_offset >= block_end)
5232			break;
5233	}
5234	free_extent_map(em);
5235	unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5236	return err;
5237}
5238
5239static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5240{
5241	struct btrfs_root *root = BTRFS_I(inode)->root;
5242	struct btrfs_trans_handle *trans;
5243	loff_t oldsize = i_size_read(inode);
5244	loff_t newsize = attr->ia_size;
5245	int mask = attr->ia_valid;
5246	int ret;
5247
5248	/*
5249	 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5250	 * special case where we need to update the times despite not having
5251	 * these flags set.  For all other operations the VFS set these flags
5252	 * explicitly if it wants a timestamp update.
5253	 */
5254	if (newsize != oldsize) {
5255		inode_inc_iversion(inode);
5256		if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5257			inode->i_ctime = inode->i_mtime =
5258				current_time(inode);
5259	}
5260
5261	if (newsize > oldsize) {
5262		/*
5263		 * Don't do an expanding truncate while snapshotting is ongoing.
5264		 * This is to ensure the snapshot captures a fully consistent
5265		 * state of this file - if the snapshot captures this expanding
5266		 * truncation, it must capture all writes that happened before
5267		 * this truncation.
5268		 */
5269		btrfs_drew_write_lock(&root->snapshot_lock);
5270		ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, newsize);
5271		if (ret) {
5272			btrfs_drew_write_unlock(&root->snapshot_lock);
5273			return ret;
5274		}
5275
5276		trans = btrfs_start_transaction(root, 1);
5277		if (IS_ERR(trans)) {
5278			btrfs_drew_write_unlock(&root->snapshot_lock);
5279			return PTR_ERR(trans);
5280		}
5281
5282		i_size_write(inode, newsize);
5283		btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
5284		pagecache_isize_extended(inode, oldsize, newsize);
5285		ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
5286		btrfs_drew_write_unlock(&root->snapshot_lock);
5287		btrfs_end_transaction(trans);
5288	} else {
5289		struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5290
5291		if (btrfs_is_zoned(fs_info)) {
5292			ret = btrfs_wait_ordered_range(inode,
5293					ALIGN(newsize, fs_info->sectorsize),
5294					(u64)-1);
5295			if (ret)
5296				return ret;
5297		}
5298
5299		/*
5300		 * We're truncating a file that used to have good data down to
5301		 * zero. Make sure any new writes to the file get on disk
5302		 * on close.
5303		 */
5304		if (newsize == 0)
5305			set_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
5306				&BTRFS_I(inode)->runtime_flags);
5307
5308		truncate_setsize(inode, newsize);
5309
5310		inode_dio_wait(inode);
5311
5312		ret = btrfs_truncate(inode, newsize == oldsize);
5313		if (ret && inode->i_nlink) {
5314			int err;
5315
5316			/*
5317			 * Truncate failed, so fix up the in-memory size. We
5318			 * adjusted disk_i_size down as we removed extents, so
5319			 * wait for disk_i_size to be stable and then update the
5320			 * in-memory size to match.
5321			 */
5322			err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5323			if (err)
5324				return err;
5325			i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5326		}
5327	}
5328
5329	return ret;
5330}
5331
5332static int btrfs_setattr(struct user_namespace *mnt_userns, struct dentry *dentry,
5333			 struct iattr *attr)
5334{
5335	struct inode *inode = d_inode(dentry);
5336	struct btrfs_root *root = BTRFS_I(inode)->root;
5337	int err;
5338
5339	if (btrfs_root_readonly(root))
5340		return -EROFS;
5341
5342	err = setattr_prepare(&init_user_ns, dentry, attr);
5343	if (err)
5344		return err;
5345
5346	if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5347		err = btrfs_setsize(inode, attr);
5348		if (err)
5349			return err;
5350	}
5351
5352	if (attr->ia_valid) {
5353		setattr_copy(&init_user_ns, inode, attr);
5354		inode_inc_iversion(inode);
5355		err = btrfs_dirty_inode(inode);
5356
5357		if (!err && attr->ia_valid & ATTR_MODE)
5358			err = posix_acl_chmod(&init_user_ns, inode,
5359					      inode->i_mode);
5360	}
5361
5362	return err;
5363}
5364
5365/*
5366 * While truncating the inode pages during eviction, we get the VFS calling
5367 * btrfs_invalidatepage() against each page of the inode. This is slow because
5368 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5369 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5370 * extent_state structures over and over, wasting lots of time.
5371 *
5372 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5373 * those expensive operations on a per page basis and do only the ordered io
5374 * finishing, while we release here the extent_map and extent_state structures,
5375 * without the excessive merging and splitting.
5376 */
5377static void evict_inode_truncate_pages(struct inode *inode)
5378{
5379	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5380	struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5381	struct rb_node *node;
5382
5383	ASSERT(inode->i_state & I_FREEING);
5384	truncate_inode_pages_final(&inode->i_data);
5385
5386	write_lock(&map_tree->lock);
5387	while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
5388		struct extent_map *em;
5389
5390		node = rb_first_cached(&map_tree->map);
5391		em = rb_entry(node, struct extent_map, rb_node);
5392		clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5393		clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5394		remove_extent_mapping(map_tree, em);
5395		free_extent_map(em);
5396		if (need_resched()) {
5397			write_unlock(&map_tree->lock);
5398			cond_resched();
5399			write_lock(&map_tree->lock);
5400		}
5401	}
5402	write_unlock(&map_tree->lock);
5403
5404	/*
5405	 * Keep looping until we have no more ranges in the io tree.
5406	 * We can have ongoing bios started by readahead that have
5407	 * their endio callback (extent_io.c:end_bio_extent_readpage)
5408	 * still in progress (unlocked the pages in the bio but did not yet
5409	 * unlocked the ranges in the io tree). Therefore this means some
5410	 * ranges can still be locked and eviction started because before
5411	 * submitting those bios, which are executed by a separate task (work
5412	 * queue kthread), inode references (inode->i_count) were not taken
5413	 * (which would be dropped in the end io callback of each bio).
5414	 * Therefore here we effectively end up waiting for those bios and
5415	 * anyone else holding locked ranges without having bumped the inode's
5416	 * reference count - if we don't do it, when they access the inode's
5417	 * io_tree to unlock a range it may be too late, leading to an
5418	 * use-after-free issue.
5419	 */
5420	spin_lock(&io_tree->lock);
5421	while (!RB_EMPTY_ROOT(&io_tree->state)) {
5422		struct extent_state *state;
5423		struct extent_state *cached_state = NULL;
5424		u64 start;
5425		u64 end;
5426		unsigned state_flags;
5427
5428		node = rb_first(&io_tree->state);
5429		state = rb_entry(node, struct extent_state, rb_node);
5430		start = state->start;
5431		end = state->end;
5432		state_flags = state->state;
5433		spin_unlock(&io_tree->lock);
5434
5435		lock_extent_bits(io_tree, start, end, &cached_state);
5436
5437		/*
5438		 * If still has DELALLOC flag, the extent didn't reach disk,
5439		 * and its reserved space won't be freed by delayed_ref.
5440		 * So we need to free its reserved space here.
5441		 * (Refer to comment in btrfs_invalidatepage, case 2)
5442		 *
5443		 * Note, end is the bytenr of last byte, so we need + 1 here.
5444		 */
5445		if (state_flags & EXTENT_DELALLOC)
5446			btrfs_qgroup_free_data(BTRFS_I(inode), NULL, start,
5447					       end - start + 1);
5448
5449		clear_extent_bit(io_tree, start, end,
5450				 EXTENT_LOCKED | EXTENT_DELALLOC |
5451				 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
5452				 &cached_state);
5453
5454		cond_resched();
5455		spin_lock(&io_tree->lock);
5456	}
5457	spin_unlock(&io_tree->lock);
5458}
5459
5460static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5461							struct btrfs_block_rsv *rsv)
5462{
5463	struct btrfs_fs_info *fs_info = root->fs_info;
5464	struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5465	struct btrfs_trans_handle *trans;
5466	u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
5467	int ret;
5468
5469	/*
5470	 * Eviction should be taking place at some place safe because of our
5471	 * delayed iputs.  However the normal flushing code will run delayed
5472	 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5473	 *
5474	 * We reserve the delayed_refs_extra here again because we can't use
5475	 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5476	 * above.  We reserve our extra bit here because we generate a ton of
5477	 * delayed refs activity by truncating.
5478	 *
5479	 * If we cannot make our reservation we'll attempt to steal from the
5480	 * global reserve, because we really want to be able to free up space.
5481	 */
5482	ret = btrfs_block_rsv_refill(root, rsv, rsv->size + delayed_refs_extra,
5483				     BTRFS_RESERVE_FLUSH_EVICT);
5484	if (ret) {
5485		/*
5486		 * Try to steal from the global reserve if there is space for
5487		 * it.
5488		 */
5489		if (btrfs_check_space_for_delayed_refs(fs_info) ||
5490		    btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0)) {
5491			btrfs_warn(fs_info,
5492				   "could not allocate space for delete; will truncate on mount");
5493			return ERR_PTR(-ENOSPC);
5494		}
5495		delayed_refs_extra = 0;
5496	}
5497
5498	trans = btrfs_join_transaction(root);
5499	if (IS_ERR(trans))
5500		return trans;
5501
5502	if (delayed_refs_extra) {
5503		trans->block_rsv = &fs_info->trans_block_rsv;
5504		trans->bytes_reserved = delayed_refs_extra;
5505		btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5506					delayed_refs_extra, 1);
5507	}
5508	return trans;
5509}
5510
5511void btrfs_evict_inode(struct inode *inode)
5512{
5513	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5514	struct btrfs_trans_handle *trans;
5515	struct btrfs_root *root = BTRFS_I(inode)->root;
5516	struct btrfs_block_rsv *rsv;
5517	int ret;
5518
5519	trace_btrfs_inode_evict(inode);
5520
5521	if (!root) {
5522		clear_inode(inode);
5523		return;
5524	}
5525
5526	evict_inode_truncate_pages(inode);
5527
5528	if (inode->i_nlink &&
5529	    ((btrfs_root_refs(&root->root_item) != 0 &&
5530	      root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5531	     btrfs_is_free_space_inode(BTRFS_I(inode))))
5532		goto no_delete;
5533
5534	if (is_bad_inode(inode))
5535		goto no_delete;
5536
5537	btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5538
5539	if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5540		goto no_delete;
5541
5542	if (inode->i_nlink > 0) {
5543		BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5544		       root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5545		goto no_delete;
5546	}
5547
5548	ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5549	if (ret)
5550		goto no_delete;
5551
5552	rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5553	if (!rsv)
5554		goto no_delete;
5555	rsv->size = btrfs_calc_metadata_size(fs_info, 1);
5556	rsv->failfast = 1;
5557
5558	btrfs_i_size_write(BTRFS_I(inode), 0);
5559
5560	while (1) {
5561		trans = evict_refill_and_join(root, rsv);
5562		if (IS_ERR(trans))
5563			goto free_rsv;
5564
5565		trans->block_rsv = rsv;
5566
5567		ret = btrfs_truncate_inode_items(trans, root, BTRFS_I(inode),
5568						 0, 0, NULL);
5569		trans->block_rsv = &fs_info->trans_block_rsv;
5570		btrfs_end_transaction(trans);
5571		btrfs_btree_balance_dirty(fs_info);
5572		if (ret && ret != -ENOSPC && ret != -EAGAIN)
5573			goto free_rsv;
5574		else if (!ret)
5575			break;
5576	}
5577
5578	/*
5579	 * Errors here aren't a big deal, it just means we leave orphan items in
5580	 * the tree. They will be cleaned up on the next mount. If the inode
5581	 * number gets reused, cleanup deletes the orphan item without doing
5582	 * anything, and unlink reuses the existing orphan item.
5583	 *
5584	 * If it turns out that we are dropping too many of these, we might want
5585	 * to add a mechanism for retrying these after a commit.
5586	 */
5587	trans = evict_refill_and_join(root, rsv);
5588	if (!IS_ERR(trans)) {
5589		trans->block_rsv = rsv;
5590		btrfs_orphan_del(trans, BTRFS_I(inode));
5591		trans->block_rsv = &fs_info->trans_block_rsv;
5592		btrfs_end_transaction(trans);
5593	}
5594
5595free_rsv:
5596	btrfs_free_block_rsv(fs_info, rsv);
5597no_delete:
5598	/*
5599	 * If we didn't successfully delete, the orphan item will still be in
5600	 * the tree and we'll retry on the next mount. Again, we might also want
5601	 * to retry these periodically in the future.
5602	 */
5603	btrfs_remove_delayed_node(BTRFS_I(inode));
5604	clear_inode(inode);
5605}
5606
5607/*
5608 * Return the key found in the dir entry in the location pointer, fill @type
5609 * with BTRFS_FT_*, and return 0.
5610 *
5611 * If no dir entries were found, returns -ENOENT.
5612 * If found a corrupted location in dir entry, returns -EUCLEAN.
5613 */
5614static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5615			       struct btrfs_key *location, u8 *type)
5616{
5617	const char *name = dentry->d_name.name;
5618	int namelen = dentry->d_name.len;
5619	struct btrfs_dir_item *di;
5620	struct btrfs_path *path;
5621	struct btrfs_root *root = BTRFS_I(dir)->root;
5622	int ret = 0;
5623
5624	path = btrfs_alloc_path();
5625	if (!path)
5626		return -ENOMEM;
5627
5628	di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5629			name, namelen, 0);
5630	if (IS_ERR_OR_NULL(di)) {
5631		ret = di ? PTR_ERR(di) : -ENOENT;
5632		goto out;
5633	}
5634
5635	btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5636	if (location->type != BTRFS_INODE_ITEM_KEY &&
5637	    location->type != BTRFS_ROOT_ITEM_KEY) {
5638		ret = -EUCLEAN;
5639		btrfs_warn(root->fs_info,
5640"%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5641			   __func__, name, btrfs_ino(BTRFS_I(dir)),
5642			   location->objectid, location->type, location->offset);
5643	}
5644	if (!ret)
5645		*type = btrfs_dir_type(path->nodes[0], di);
5646out:
5647	btrfs_free_path(path);
5648	return ret;
5649}
5650
5651/*
5652 * when we hit a tree root in a directory, the btrfs part of the inode
5653 * needs to be changed to reflect the root directory of the tree root.  This
5654 * is kind of like crossing a mount point.
5655 */
5656static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5657				    struct inode *dir,
5658				    struct dentry *dentry,
5659				    struct btrfs_key *location,
5660				    struct btrfs_root **sub_root)
5661{
5662	struct btrfs_path *path;
5663	struct btrfs_root *new_root;
5664	struct btrfs_root_ref *ref;
5665	struct extent_buffer *leaf;
5666	struct btrfs_key key;
5667	int ret;
5668	int err = 0;
5669
5670	path = btrfs_alloc_path();
5671	if (!path) {
5672		err = -ENOMEM;
5673		goto out;
5674	}
5675
5676	err = -ENOENT;
5677	key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5678	key.type = BTRFS_ROOT_REF_KEY;
5679	key.offset = location->objectid;
5680
5681	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5682	if (ret) {
5683		if (ret < 0)
5684			err = ret;
5685		goto out;
5686	}
5687
5688	leaf = path->nodes[0];
5689	ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5690	if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5691	    btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5692		goto out;
5693
5694	ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5695				   (unsigned long)(ref + 1),
5696				   dentry->d_name.len);
5697	if (ret)
5698		goto out;
5699
5700	btrfs_release_path(path);
5701
5702	new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5703	if (IS_ERR(new_root)) {
5704		err = PTR_ERR(new_root);
5705		goto out;
5706	}
5707
5708	*sub_root = new_root;
5709	location->objectid = btrfs_root_dirid(&new_root->root_item);
5710	location->type = BTRFS_INODE_ITEM_KEY;
5711	location->offset = 0;
5712	err = 0;
5713out:
5714	btrfs_free_path(path);
5715	return err;
5716}
5717
5718static void inode_tree_add(struct inode *inode)
5719{
5720	struct btrfs_root *root = BTRFS_I(inode)->root;
5721	struct btrfs_inode *entry;
5722	struct rb_node **p;
5723	struct rb_node *parent;
5724	struct rb_node *new = &BTRFS_I(inode)->rb_node;
5725	u64 ino = btrfs_ino(BTRFS_I(inode));
5726
5727	if (inode_unhashed(inode))
5728		return;
5729	parent = NULL;
5730	spin_lock(&root->inode_lock);
5731	p = &root->inode_tree.rb_node;
5732	while (*p) {
5733		parent = *p;
5734		entry = rb_entry(parent, struct btrfs_inode, rb_node);
5735
5736		if (ino < btrfs_ino(entry))
5737			p = &parent->rb_left;
5738		else if (ino > btrfs_ino(entry))
5739			p = &parent->rb_right;
5740		else {
5741			WARN_ON(!(entry->vfs_inode.i_state &
5742				  (I_WILL_FREE | I_FREEING)));
5743			rb_replace_node(parent, new, &root->inode_tree);
5744			RB_CLEAR_NODE(parent);
5745			spin_unlock(&root->inode_lock);
5746			return;
5747		}
5748	}
5749	rb_link_node(new, parent, p);
5750	rb_insert_color(new, &root->inode_tree);
5751	spin_unlock(&root->inode_lock);
5752}
5753
5754static void inode_tree_del(struct btrfs_inode *inode)
5755{
5756	struct btrfs_root *root = inode->root;
5757	int empty = 0;
5758
5759	spin_lock(&root->inode_lock);
5760	if (!RB_EMPTY_NODE(&inode->rb_node)) {
5761		rb_erase(&inode->rb_node, &root->inode_tree);
5762		RB_CLEAR_NODE(&inode->rb_node);
5763		empty = RB_EMPTY_ROOT(&root->inode_tree);
5764	}
5765	spin_unlock(&root->inode_lock);
5766
5767	if (empty && btrfs_root_refs(&root->root_item) == 0) {
5768		spin_lock(&root->inode_lock);
5769		empty = RB_EMPTY_ROOT(&root->inode_tree);
5770		spin_unlock(&root->inode_lock);
5771		if (empty)
5772			btrfs_add_dead_root(root);
5773	}
5774}
5775
5776
5777static int btrfs_init_locked_inode(struct inode *inode, void *p)
5778{
5779	struct btrfs_iget_args *args = p;
5780
5781	inode->i_ino = args->ino;
5782	BTRFS_I(inode)->location.objectid = args->ino;
5783	BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
5784	BTRFS_I(inode)->location.offset = 0;
5785	BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5786	BUG_ON(args->root && !BTRFS_I(inode)->root);
5787	return 0;
5788}
5789
5790static int btrfs_find_actor(struct inode *inode, void *opaque)
5791{
5792	struct btrfs_iget_args *args = opaque;
5793
5794	return args->ino == BTRFS_I(inode)->location.objectid &&
5795		args->root == BTRFS_I(inode)->root;
5796}
5797
5798static struct inode *btrfs_iget_locked(struct super_block *s, u64 ino,
5799				       struct btrfs_root *root)
5800{
5801	struct inode *inode;
5802	struct btrfs_iget_args args;
5803	unsigned long hashval = btrfs_inode_hash(ino, root);
5804
5805	args.ino = ino;
5806	args.root = root;
5807
5808	inode = iget5_locked(s, hashval, btrfs_find_actor,
5809			     btrfs_init_locked_inode,
5810			     (void *)&args);
5811	return inode;
5812}
5813
5814/*
5815 * Get an inode object given its inode number and corresponding root.
5816 * Path can be preallocated to prevent recursing back to iget through
5817 * allocator. NULL is also valid but may require an additional allocation
5818 * later.
5819 */
5820struct inode *btrfs_iget_path(struct super_block *s, u64 ino,
5821			      struct btrfs_root *root, struct btrfs_path *path)
5822{
5823	struct inode *inode;
5824
5825	inode = btrfs_iget_locked(s, ino, root);
5826	if (!inode)
5827		return ERR_PTR(-ENOMEM);
5828
5829	if (inode->i_state & I_NEW) {
5830		int ret;
5831
5832		ret = btrfs_read_locked_inode(inode, path);
5833		if (!ret) {
5834			inode_tree_add(inode);
5835			unlock_new_inode(inode);
5836		} else {
5837			iget_failed(inode);
5838			/*
5839			 * ret > 0 can come from btrfs_search_slot called by
5840			 * btrfs_read_locked_inode, this means the inode item
5841			 * was not found.
5842			 */
5843			if (ret > 0)
5844				ret = -ENOENT;
5845			inode = ERR_PTR(ret);
5846		}
5847	}
5848
5849	return inode;
5850}
5851
5852struct inode *btrfs_iget(struct super_block *s, u64 ino, struct btrfs_root *root)
5853{
5854	return btrfs_iget_path(s, ino, root, NULL);
5855}
5856
5857static struct inode *new_simple_dir(struct super_block *s,
5858				    struct btrfs_key *key,
5859				    struct btrfs_root *root)
5860{
5861	struct inode *inode = new_inode(s);
5862
5863	if (!inode)
5864		return ERR_PTR(-ENOMEM);
5865
5866	BTRFS_I(inode)->root = btrfs_grab_root(root);
5867	memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5868	set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5869
5870	inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5871	/*
5872	 * We only need lookup, the rest is read-only and there's no inode
5873	 * associated with the dentry
5874	 */
5875	inode->i_op = &simple_dir_inode_operations;
5876	inode->i_opflags &= ~IOP_XATTR;
5877	inode->i_fop = &simple_dir_operations;
5878	inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5879	inode->i_mtime = current_time(inode);
5880	inode->i_atime = inode->i_mtime;
5881	inode->i_ctime = inode->i_mtime;
5882	BTRFS_I(inode)->i_otime = inode->i_mtime;
5883
5884	return inode;