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