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