1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2007 Oracle.  All rights reserved.
4  */
5 
6 #include <linux/bio.h>
7 #include <linux/slab.h>
8 #include <linux/pagemap.h>
9 #include <linux/highmem.h>
10 #include <linux/sched/mm.h>
11 #include <crypto/hash.h>
12 #include "misc.h"
13 #include "ctree.h"
14 #include "disk-io.h"
15 #include "transaction.h"
16 #include "volumes.h"
17 #include "print-tree.h"
18 #include "compression.h"
19 
20 #define __MAX_CSUM_ITEMS(r, size) ((unsigned long)(((BTRFS_LEAF_DATA_SIZE(r) - \
21 				   sizeof(struct btrfs_item) * 2) / \
22 				  size) - 1))
23 
24 #define MAX_CSUM_ITEMS(r, size) (min_t(u32, __MAX_CSUM_ITEMS(r, size), \
25 				       PAGE_SIZE))
26 
27 /**
28  * Set inode's size according to filesystem options
29  *
30  * @inode:      inode we want to update the disk_i_size for
31  * @new_i_size: i_size we want to set to, 0 if we use i_size
32  *
33  * With NO_HOLES set this simply sets the disk_is_size to whatever i_size_read()
34  * returns as it is perfectly fine with a file that has holes without hole file
35  * extent items.
36  *
37  * However without NO_HOLES we need to only return the area that is contiguous
38  * from the 0 offset of the file.  Otherwise we could end up adjust i_size up
39  * to an extent that has a gap in between.
40  *
41  * Finally new_i_size should only be set in the case of truncate where we're not
42  * ready to use i_size_read() as the limiter yet.
43  */
btrfs_inode_safe_disk_i_size_write(struct btrfs_inode * inode,u64 new_i_size)44 void btrfs_inode_safe_disk_i_size_write(struct btrfs_inode *inode, u64 new_i_size)
45 {
46 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
47 	u64 start, end, i_size;
48 	int ret;
49 
50 	i_size = new_i_size ?: i_size_read(&inode->vfs_inode);
51 	if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
52 		inode->disk_i_size = i_size;
53 		return;
54 	}
55 
56 	spin_lock(&inode->lock);
57 	ret = find_contiguous_extent_bit(&inode->file_extent_tree, 0, &start,
58 					 &end, EXTENT_DIRTY);
59 	if (!ret && start == 0)
60 		i_size = min(i_size, end + 1);
61 	else
62 		i_size = 0;
63 	inode->disk_i_size = i_size;
64 	spin_unlock(&inode->lock);
65 }
66 
67 /**
68  * Mark range within a file as having a new extent inserted
69  *
70  * @inode: inode being modified
71  * @start: start file offset of the file extent we've inserted
72  * @len:   logical length of the file extent item
73  *
74  * Call when we are inserting a new file extent where there was none before.
75  * Does not need to call this in the case where we're replacing an existing file
76  * extent, however if not sure it's fine to call this multiple times.
77  *
78  * The start and len must match the file extent item, so thus must be sectorsize
79  * aligned.
80  */
btrfs_inode_set_file_extent_range(struct btrfs_inode * inode,u64 start,u64 len)81 int btrfs_inode_set_file_extent_range(struct btrfs_inode *inode, u64 start,
82 				      u64 len)
83 {
84 	if (len == 0)
85 		return 0;
86 
87 	ASSERT(IS_ALIGNED(start + len, inode->root->fs_info->sectorsize));
88 
89 	if (btrfs_fs_incompat(inode->root->fs_info, NO_HOLES))
90 		return 0;
91 	return set_extent_bits(&inode->file_extent_tree, start, start + len - 1,
92 			       EXTENT_DIRTY);
93 }
94 
95 /**
96  * Marks an inode range as not having a backing extent
97  *
98  * @inode: inode being modified
99  * @start: start file offset of the file extent we've inserted
100  * @len:   logical length of the file extent item
101  *
102  * Called when we drop a file extent, for example when we truncate.  Doesn't
103  * need to be called for cases where we're replacing a file extent, like when
104  * we've COWed a file extent.
105  *
106  * The start and len must match the file extent item, so thus must be sectorsize
107  * aligned.
108  */
btrfs_inode_clear_file_extent_range(struct btrfs_inode * inode,u64 start,u64 len)109 int btrfs_inode_clear_file_extent_range(struct btrfs_inode *inode, u64 start,
110 					u64 len)
111 {
112 	if (len == 0)
113 		return 0;
114 
115 	ASSERT(IS_ALIGNED(start + len, inode->root->fs_info->sectorsize) ||
116 	       len == (u64)-1);
117 
118 	if (btrfs_fs_incompat(inode->root->fs_info, NO_HOLES))
119 		return 0;
120 	return clear_extent_bit(&inode->file_extent_tree, start,
121 				start + len - 1, EXTENT_DIRTY, NULL);
122 }
123 
max_ordered_sum_bytes(struct btrfs_fs_info * fs_info,u16 csum_size)124 static inline u32 max_ordered_sum_bytes(struct btrfs_fs_info *fs_info,
125 					u16 csum_size)
126 {
127 	u32 ncsums = (PAGE_SIZE - sizeof(struct btrfs_ordered_sum)) / csum_size;
128 
129 	return ncsums * fs_info->sectorsize;
130 }
131 
132 /*
133  * Calculate the total size needed to allocate for an ordered sum structure
134  * spanning @bytes in the file.
135  */
btrfs_ordered_sum_size(struct btrfs_fs_info * fs_info,unsigned long bytes)136 static int btrfs_ordered_sum_size(struct btrfs_fs_info *fs_info, unsigned long bytes)
137 {
138 	int num_sectors = (int)DIV_ROUND_UP(bytes, fs_info->sectorsize);
139 
140 	return sizeof(struct btrfs_ordered_sum) + num_sectors * fs_info->csum_size;
141 }
142 
btrfs_insert_hole_extent(struct btrfs_trans_handle * trans,struct btrfs_root * root,u64 objectid,u64 pos,u64 num_bytes)143 int btrfs_insert_hole_extent(struct btrfs_trans_handle *trans,
144 			     struct btrfs_root *root,
145 			     u64 objectid, u64 pos, u64 num_bytes)
146 {
147 	int ret = 0;
148 	struct btrfs_file_extent_item *item;
149 	struct btrfs_key file_key;
150 	struct btrfs_path *path;
151 	struct extent_buffer *leaf;
152 
153 	path = btrfs_alloc_path();
154 	if (!path)
155 		return -ENOMEM;
156 	file_key.objectid = objectid;
157 	file_key.offset = pos;
158 	file_key.type = BTRFS_EXTENT_DATA_KEY;
159 
160 	ret = btrfs_insert_empty_item(trans, root, path, &file_key,
161 				      sizeof(*item));
162 	if (ret < 0)
163 		goto out;
164 	BUG_ON(ret); /* Can't happen */
165 	leaf = path->nodes[0];
166 	item = btrfs_item_ptr(leaf, path->slots[0],
167 			      struct btrfs_file_extent_item);
168 	btrfs_set_file_extent_disk_bytenr(leaf, item, 0);
169 	btrfs_set_file_extent_disk_num_bytes(leaf, item, 0);
170 	btrfs_set_file_extent_offset(leaf, item, 0);
171 	btrfs_set_file_extent_num_bytes(leaf, item, num_bytes);
172 	btrfs_set_file_extent_ram_bytes(leaf, item, num_bytes);
173 	btrfs_set_file_extent_generation(leaf, item, trans->transid);
174 	btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
175 	btrfs_set_file_extent_compression(leaf, item, 0);
176 	btrfs_set_file_extent_encryption(leaf, item, 0);
177 	btrfs_set_file_extent_other_encoding(leaf, item, 0);
178 
179 	btrfs_mark_buffer_dirty(leaf);
180 out:
181 	btrfs_free_path(path);
182 	return ret;
183 }
184 
185 static struct btrfs_csum_item *
btrfs_lookup_csum(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,u64 bytenr,int cow)186 btrfs_lookup_csum(struct btrfs_trans_handle *trans,
187 		  struct btrfs_root *root,
188 		  struct btrfs_path *path,
189 		  u64 bytenr, int cow)
190 {
191 	struct btrfs_fs_info *fs_info = root->fs_info;
192 	int ret;
193 	struct btrfs_key file_key;
194 	struct btrfs_key found_key;
195 	struct btrfs_csum_item *item;
196 	struct extent_buffer *leaf;
197 	u64 csum_offset = 0;
198 	const u32 csum_size = fs_info->csum_size;
199 	int csums_in_item;
200 
201 	file_key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
202 	file_key.offset = bytenr;
203 	file_key.type = BTRFS_EXTENT_CSUM_KEY;
204 	ret = btrfs_search_slot(trans, root, &file_key, path, 0, cow);
205 	if (ret < 0)
206 		goto fail;
207 	leaf = path->nodes[0];
208 	if (ret > 0) {
209 		ret = 1;
210 		if (path->slots[0] == 0)
211 			goto fail;
212 		path->slots[0]--;
213 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
214 		if (found_key.type != BTRFS_EXTENT_CSUM_KEY)
215 			goto fail;
216 
217 		csum_offset = (bytenr - found_key.offset) >>
218 				fs_info->sectorsize_bits;
219 		csums_in_item = btrfs_item_size(leaf, path->slots[0]);
220 		csums_in_item /= csum_size;
221 
222 		if (csum_offset == csums_in_item) {
223 			ret = -EFBIG;
224 			goto fail;
225 		} else if (csum_offset > csums_in_item) {
226 			goto fail;
227 		}
228 	}
229 	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_csum_item);
230 	item = (struct btrfs_csum_item *)((unsigned char *)item +
231 					  csum_offset * csum_size);
232 	return item;
233 fail:
234 	if (ret > 0)
235 		ret = -ENOENT;
236 	return ERR_PTR(ret);
237 }
238 
btrfs_lookup_file_extent(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,u64 objectid,u64 offset,int mod)239 int btrfs_lookup_file_extent(struct btrfs_trans_handle *trans,
240 			     struct btrfs_root *root,
241 			     struct btrfs_path *path, u64 objectid,
242 			     u64 offset, int mod)
243 {
244 	struct btrfs_key file_key;
245 	int ins_len = mod < 0 ? -1 : 0;
246 	int cow = mod != 0;
247 
248 	file_key.objectid = objectid;
249 	file_key.offset = offset;
250 	file_key.type = BTRFS_EXTENT_DATA_KEY;
251 
252 	return btrfs_search_slot(trans, root, &file_key, path, ins_len, cow);
253 }
254 
255 /*
256  * Find checksums for logical bytenr range [disk_bytenr, disk_bytenr + len) and
257  * estore the result to @dst.
258  *
259  * Return >0 for the number of sectors we found.
260  * Return 0 for the range [disk_bytenr, disk_bytenr + sectorsize) has no csum
261  * for it. Caller may want to try next sector until one range is hit.
262  * Return <0 for fatal error.
263  */
search_csum_tree(struct btrfs_fs_info * fs_info,struct btrfs_path * path,u64 disk_bytenr,u64 len,u8 * dst)264 static int search_csum_tree(struct btrfs_fs_info *fs_info,
265 			    struct btrfs_path *path, u64 disk_bytenr,
266 			    u64 len, u8 *dst)
267 {
268 	struct btrfs_root *csum_root;
269 	struct btrfs_csum_item *item = NULL;
270 	struct btrfs_key key;
271 	const u32 sectorsize = fs_info->sectorsize;
272 	const u32 csum_size = fs_info->csum_size;
273 	u32 itemsize;
274 	int ret;
275 	u64 csum_start;
276 	u64 csum_len;
277 
278 	ASSERT(IS_ALIGNED(disk_bytenr, sectorsize) &&
279 	       IS_ALIGNED(len, sectorsize));
280 
281 	/* Check if the current csum item covers disk_bytenr */
282 	if (path->nodes[0]) {
283 		item = btrfs_item_ptr(path->nodes[0], path->slots[0],
284 				      struct btrfs_csum_item);
285 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
286 		itemsize = btrfs_item_size(path->nodes[0], path->slots[0]);
287 
288 		csum_start = key.offset;
289 		csum_len = (itemsize / csum_size) * sectorsize;
290 
291 		if (in_range(disk_bytenr, csum_start, csum_len))
292 			goto found;
293 	}
294 
295 	/* Current item doesn't contain the desired range, search again */
296 	btrfs_release_path(path);
297 	csum_root = btrfs_csum_root(fs_info, disk_bytenr);
298 	item = btrfs_lookup_csum(NULL, csum_root, path, disk_bytenr, 0);
299 	if (IS_ERR(item)) {
300 		ret = PTR_ERR(item);
301 		goto out;
302 	}
303 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
304 	itemsize = btrfs_item_size(path->nodes[0], path->slots[0]);
305 
306 	csum_start = key.offset;
307 	csum_len = (itemsize / csum_size) * sectorsize;
308 	ASSERT(in_range(disk_bytenr, csum_start, csum_len));
309 
310 found:
311 	ret = (min(csum_start + csum_len, disk_bytenr + len) -
312 		   disk_bytenr) >> fs_info->sectorsize_bits;
313 	read_extent_buffer(path->nodes[0], dst, (unsigned long)item,
314 			ret * csum_size);
315 out:
316 	if (ret == -ENOENT || ret == -EFBIG)
317 		ret = 0;
318 	return ret;
319 }
320 
321 /*
322  * Locate the file_offset of @cur_disk_bytenr of a @bio.
323  *
324  * Bio of btrfs represents read range of
325  * [bi_sector << 9, bi_sector << 9 + bi_size).
326  * Knowing this, we can iterate through each bvec to locate the page belong to
327  * @cur_disk_bytenr and get the file offset.
328  *
329  * @inode is used to determine if the bvec page really belongs to @inode.
330  *
331  * Return 0 if we can't find the file offset
332  * Return >0 if we find the file offset and restore it to @file_offset_ret
333  */
search_file_offset_in_bio(struct bio * bio,struct inode * inode,u64 disk_bytenr,u64 * file_offset_ret)334 static int search_file_offset_in_bio(struct bio *bio, struct inode *inode,
335 				     u64 disk_bytenr, u64 *file_offset_ret)
336 {
337 	struct bvec_iter iter;
338 	struct bio_vec bvec;
339 	u64 cur = bio->bi_iter.bi_sector << SECTOR_SHIFT;
340 	int ret = 0;
341 
342 	bio_for_each_segment(bvec, bio, iter) {
343 		struct page *page = bvec.bv_page;
344 
345 		if (cur > disk_bytenr)
346 			break;
347 		if (cur + bvec.bv_len <= disk_bytenr) {
348 			cur += bvec.bv_len;
349 			continue;
350 		}
351 		ASSERT(in_range(disk_bytenr, cur, bvec.bv_len));
352 		if (page->mapping && page->mapping->host &&
353 		    page->mapping->host == inode) {
354 			ret = 1;
355 			*file_offset_ret = page_offset(page) + bvec.bv_offset +
356 					   disk_bytenr - cur;
357 			break;
358 		}
359 	}
360 	return ret;
361 }
362 
363 /**
364  * Lookup the checksum for the read bio in csum tree.
365  *
366  * @inode: inode that the bio is for.
367  * @bio: bio to look up.
368  * @dst: Buffer of size nblocks * btrfs_super_csum_size() used to return
369  *       checksum (nblocks = bio->bi_iter.bi_size / fs_info->sectorsize). If
370  *       NULL, the checksum buffer is allocated and returned in
371  *       btrfs_bio(bio)->csum instead.
372  *
373  * Return: BLK_STS_RESOURCE if allocating memory fails, BLK_STS_OK otherwise.
374  */
btrfs_lookup_bio_sums(struct inode * inode,struct bio * bio,u8 * dst)375 blk_status_t btrfs_lookup_bio_sums(struct inode *inode, struct bio *bio, u8 *dst)
376 {
377 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
378 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
379 	struct btrfs_bio *bbio = NULL;
380 	struct btrfs_path *path;
381 	const u32 sectorsize = fs_info->sectorsize;
382 	const u32 csum_size = fs_info->csum_size;
383 	u32 orig_len = bio->bi_iter.bi_size;
384 	u64 orig_disk_bytenr = bio->bi_iter.bi_sector << SECTOR_SHIFT;
385 	u64 cur_disk_bytenr;
386 	u8 *csum;
387 	const unsigned int nblocks = orig_len >> fs_info->sectorsize_bits;
388 	int count = 0;
389 	blk_status_t ret = BLK_STS_OK;
390 
391 	if ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM) ||
392 	    test_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state))
393 		return BLK_STS_OK;
394 
395 	/*
396 	 * This function is only called for read bio.
397 	 *
398 	 * This means two things:
399 	 * - All our csums should only be in csum tree
400 	 *   No ordered extents csums, as ordered extents are only for write
401 	 *   path.
402 	 * - No need to bother any other info from bvec
403 	 *   Since we're looking up csums, the only important info is the
404 	 *   disk_bytenr and the length, which can be extracted from bi_iter
405 	 *   directly.
406 	 */
407 	ASSERT(bio_op(bio) == REQ_OP_READ);
408 	path = btrfs_alloc_path();
409 	if (!path)
410 		return BLK_STS_RESOURCE;
411 
412 	if (!dst) {
413 		bbio = btrfs_bio(bio);
414 
415 		if (nblocks * csum_size > BTRFS_BIO_INLINE_CSUM_SIZE) {
416 			bbio->csum = kmalloc_array(nblocks, csum_size, GFP_NOFS);
417 			if (!bbio->csum) {
418 				btrfs_free_path(path);
419 				return BLK_STS_RESOURCE;
420 			}
421 		} else {
422 			bbio->csum = bbio->csum_inline;
423 		}
424 		csum = bbio->csum;
425 	} else {
426 		csum = dst;
427 	}
428 
429 	/*
430 	 * If requested number of sectors is larger than one leaf can contain,
431 	 * kick the readahead for csum tree.
432 	 */
433 	if (nblocks > fs_info->csums_per_leaf)
434 		path->reada = READA_FORWARD;
435 
436 	/*
437 	 * the free space stuff is only read when it hasn't been
438 	 * updated in the current transaction.  So, we can safely
439 	 * read from the commit root and sidestep a nasty deadlock
440 	 * between reading the free space cache and updating the csum tree.
441 	 */
442 	if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
443 		path->search_commit_root = 1;
444 		path->skip_locking = 1;
445 	}
446 
447 	for (cur_disk_bytenr = orig_disk_bytenr;
448 	     cur_disk_bytenr < orig_disk_bytenr + orig_len;
449 	     cur_disk_bytenr += (count * sectorsize)) {
450 		u64 search_len = orig_disk_bytenr + orig_len - cur_disk_bytenr;
451 		unsigned int sector_offset;
452 		u8 *csum_dst;
453 
454 		/*
455 		 * Although both cur_disk_bytenr and orig_disk_bytenr is u64,
456 		 * we're calculating the offset to the bio start.
457 		 *
458 		 * Bio size is limited to UINT_MAX, thus unsigned int is large
459 		 * enough to contain the raw result, not to mention the right
460 		 * shifted result.
461 		 */
462 		ASSERT(cur_disk_bytenr - orig_disk_bytenr < UINT_MAX);
463 		sector_offset = (cur_disk_bytenr - orig_disk_bytenr) >>
464 				fs_info->sectorsize_bits;
465 		csum_dst = csum + sector_offset * csum_size;
466 
467 		count = search_csum_tree(fs_info, path, cur_disk_bytenr,
468 					 search_len, csum_dst);
469 		if (count < 0) {
470 			ret = errno_to_blk_status(count);
471 			if (bbio)
472 				btrfs_bio_free_csum(bbio);
473 			break;
474 		}
475 
476 		/*
477 		 * We didn't find a csum for this range.  We need to make sure
478 		 * we complain loudly about this, because we are not NODATASUM.
479 		 *
480 		 * However for the DATA_RELOC inode we could potentially be
481 		 * relocating data extents for a NODATASUM inode, so the inode
482 		 * itself won't be marked with NODATASUM, but the extent we're
483 		 * copying is in fact NODATASUM.  If we don't find a csum we
484 		 * assume this is the case.
485 		 */
486 		if (count == 0) {
487 			memset(csum_dst, 0, csum_size);
488 			count = 1;
489 
490 			if (BTRFS_I(inode)->root->root_key.objectid ==
491 			    BTRFS_DATA_RELOC_TREE_OBJECTID) {
492 				u64 file_offset;
493 				int ret;
494 
495 				ret = search_file_offset_in_bio(bio, inode,
496 						cur_disk_bytenr, &file_offset);
497 				if (ret)
498 					set_extent_bits(io_tree, file_offset,
499 						file_offset + sectorsize - 1,
500 						EXTENT_NODATASUM);
501 			} else {
502 				btrfs_warn_rl(fs_info,
503 			"csum hole found for disk bytenr range [%llu, %llu)",
504 				cur_disk_bytenr, cur_disk_bytenr + sectorsize);
505 			}
506 		}
507 	}
508 
509 	btrfs_free_path(path);
510 	return ret;
511 }
512 
btrfs_lookup_csums_range(struct btrfs_root * root,u64 start,u64 end,struct list_head * list,int search_commit,bool nowait)513 int btrfs_lookup_csums_range(struct btrfs_root *root, u64 start, u64 end,
514 			     struct list_head *list, int search_commit,
515 			     bool nowait)
516 {
517 	struct btrfs_fs_info *fs_info = root->fs_info;
518 	struct btrfs_key key;
519 	struct btrfs_path *path;
520 	struct extent_buffer *leaf;
521 	struct btrfs_ordered_sum *sums;
522 	struct btrfs_csum_item *item;
523 	LIST_HEAD(tmplist);
524 	unsigned long offset;
525 	int ret;
526 	size_t size;
527 	u64 csum_end;
528 	const u32 csum_size = fs_info->csum_size;
529 
530 	ASSERT(IS_ALIGNED(start, fs_info->sectorsize) &&
531 	       IS_ALIGNED(end + 1, fs_info->sectorsize));
532 
533 	path = btrfs_alloc_path();
534 	if (!path)
535 		return -ENOMEM;
536 
537 	path->nowait = nowait;
538 	if (search_commit) {
539 		path->skip_locking = 1;
540 		path->reada = READA_FORWARD;
541 		path->search_commit_root = 1;
542 	}
543 
544 	key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
545 	key.offset = start;
546 	key.type = BTRFS_EXTENT_CSUM_KEY;
547 
548 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
549 	if (ret < 0)
550 		goto fail;
551 	if (ret > 0 && path->slots[0] > 0) {
552 		leaf = path->nodes[0];
553 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0] - 1);
554 		if (key.objectid == BTRFS_EXTENT_CSUM_OBJECTID &&
555 		    key.type == BTRFS_EXTENT_CSUM_KEY) {
556 			offset = (start - key.offset) >> fs_info->sectorsize_bits;
557 			if (offset * csum_size <
558 			    btrfs_item_size(leaf, path->slots[0] - 1))
559 				path->slots[0]--;
560 		}
561 	}
562 
563 	while (start <= end) {
564 		leaf = path->nodes[0];
565 		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
566 			ret = btrfs_next_leaf(root, path);
567 			if (ret < 0)
568 				goto fail;
569 			if (ret > 0)
570 				break;
571 			leaf = path->nodes[0];
572 		}
573 
574 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
575 		if (key.objectid != BTRFS_EXTENT_CSUM_OBJECTID ||
576 		    key.type != BTRFS_EXTENT_CSUM_KEY ||
577 		    key.offset > end)
578 			break;
579 
580 		if (key.offset > start)
581 			start = key.offset;
582 
583 		size = btrfs_item_size(leaf, path->slots[0]);
584 		csum_end = key.offset + (size / csum_size) * fs_info->sectorsize;
585 		if (csum_end <= start) {
586 			path->slots[0]++;
587 			continue;
588 		}
589 
590 		csum_end = min(csum_end, end + 1);
591 		item = btrfs_item_ptr(path->nodes[0], path->slots[0],
592 				      struct btrfs_csum_item);
593 		while (start < csum_end) {
594 			size = min_t(size_t, csum_end - start,
595 				     max_ordered_sum_bytes(fs_info, csum_size));
596 			sums = kzalloc(btrfs_ordered_sum_size(fs_info, size),
597 				       GFP_NOFS);
598 			if (!sums) {
599 				ret = -ENOMEM;
600 				goto fail;
601 			}
602 
603 			sums->bytenr = start;
604 			sums->len = (int)size;
605 
606 			offset = (start - key.offset) >> fs_info->sectorsize_bits;
607 			offset *= csum_size;
608 			size >>= fs_info->sectorsize_bits;
609 
610 			read_extent_buffer(path->nodes[0],
611 					   sums->sums,
612 					   ((unsigned long)item) + offset,
613 					   csum_size * size);
614 
615 			start += fs_info->sectorsize * size;
616 			list_add_tail(&sums->list, &tmplist);
617 		}
618 		path->slots[0]++;
619 	}
620 	ret = 0;
621 fail:
622 	while (ret < 0 && !list_empty(&tmplist)) {
623 		sums = list_entry(tmplist.next, struct btrfs_ordered_sum, list);
624 		list_del(&sums->list);
625 		kfree(sums);
626 	}
627 	list_splice_tail(&tmplist, list);
628 
629 	btrfs_free_path(path);
630 	return ret;
631 }
632 
633 /**
634  * Calculate checksums of the data contained inside a bio
635  *
636  * @inode:	 Owner of the data inside the bio
637  * @bio:	 Contains the data to be checksummed
638  * @offset:      If (u64)-1, @bio may contain discontiguous bio vecs, so the
639  *               file offsets are determined from the page offsets in the bio.
640  *               Otherwise, this is the starting file offset of the bio vecs in
641  *               @bio, which must be contiguous.
642  * @one_ordered: If true, @bio only refers to one ordered extent.
643  */
btrfs_csum_one_bio(struct btrfs_inode * inode,struct bio * bio,u64 offset,bool one_ordered)644 blk_status_t btrfs_csum_one_bio(struct btrfs_inode *inode, struct bio *bio,
645 				u64 offset, bool one_ordered)
646 {
647 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
648 	SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
649 	struct btrfs_ordered_sum *sums;
650 	struct btrfs_ordered_extent *ordered = NULL;
651 	const bool use_page_offsets = (offset == (u64)-1);
652 	char *data;
653 	struct bvec_iter iter;
654 	struct bio_vec bvec;
655 	int index;
656 	unsigned int blockcount;
657 	unsigned long total_bytes = 0;
658 	unsigned long this_sum_bytes = 0;
659 	int i;
660 	unsigned nofs_flag;
661 
662 	nofs_flag = memalloc_nofs_save();
663 	sums = kvzalloc(btrfs_ordered_sum_size(fs_info, bio->bi_iter.bi_size),
664 		       GFP_KERNEL);
665 	memalloc_nofs_restore(nofs_flag);
666 
667 	if (!sums)
668 		return BLK_STS_RESOURCE;
669 
670 	sums->len = bio->bi_iter.bi_size;
671 	INIT_LIST_HEAD(&sums->list);
672 
673 	sums->bytenr = bio->bi_iter.bi_sector << 9;
674 	index = 0;
675 
676 	shash->tfm = fs_info->csum_shash;
677 
678 	bio_for_each_segment(bvec, bio, iter) {
679 		if (use_page_offsets)
680 			offset = page_offset(bvec.bv_page) + bvec.bv_offset;
681 
682 		if (!ordered) {
683 			ordered = btrfs_lookup_ordered_extent(inode, offset);
684 			/*
685 			 * The bio range is not covered by any ordered extent,
686 			 * must be a code logic error.
687 			 */
688 			if (unlikely(!ordered)) {
689 				WARN(1, KERN_WARNING
690 			"no ordered extent for root %llu ino %llu offset %llu\n",
691 				     inode->root->root_key.objectid,
692 				     btrfs_ino(inode), offset);
693 				kvfree(sums);
694 				return BLK_STS_IOERR;
695 			}
696 		}
697 
698 		blockcount = BTRFS_BYTES_TO_BLKS(fs_info,
699 						 bvec.bv_len + fs_info->sectorsize
700 						 - 1);
701 
702 		for (i = 0; i < blockcount; i++) {
703 			if (!one_ordered &&
704 			    !in_range(offset, ordered->file_offset,
705 				      ordered->num_bytes)) {
706 				unsigned long bytes_left;
707 
708 				sums->len = this_sum_bytes;
709 				this_sum_bytes = 0;
710 				btrfs_add_ordered_sum(ordered, sums);
711 				btrfs_put_ordered_extent(ordered);
712 
713 				bytes_left = bio->bi_iter.bi_size - total_bytes;
714 
715 				nofs_flag = memalloc_nofs_save();
716 				sums = kvzalloc(btrfs_ordered_sum_size(fs_info,
717 						      bytes_left), GFP_KERNEL);
718 				memalloc_nofs_restore(nofs_flag);
719 				BUG_ON(!sums); /* -ENOMEM */
720 				sums->len = bytes_left;
721 				ordered = btrfs_lookup_ordered_extent(inode,
722 								offset);
723 				ASSERT(ordered); /* Logic error */
724 				sums->bytenr = (bio->bi_iter.bi_sector << 9)
725 					+ total_bytes;
726 				index = 0;
727 			}
728 
729 			data = bvec_kmap_local(&bvec);
730 			crypto_shash_digest(shash,
731 					    data + (i * fs_info->sectorsize),
732 					    fs_info->sectorsize,
733 					    sums->sums + index);
734 			kunmap_local(data);
735 			index += fs_info->csum_size;
736 			offset += fs_info->sectorsize;
737 			this_sum_bytes += fs_info->sectorsize;
738 			total_bytes += fs_info->sectorsize;
739 		}
740 
741 	}
742 	this_sum_bytes = 0;
743 	btrfs_add_ordered_sum(ordered, sums);
744 	btrfs_put_ordered_extent(ordered);
745 	return 0;
746 }
747 
748 /*
749  * helper function for csum removal, this expects the
750  * key to describe the csum pointed to by the path, and it expects
751  * the csum to overlap the range [bytenr, len]
752  *
753  * The csum should not be entirely contained in the range and the
754  * range should not be entirely contained in the csum.
755  *
756  * This calls btrfs_truncate_item with the correct args based on the
757  * overlap, and fixes up the key as required.
758  */
truncate_one_csum(struct btrfs_fs_info * fs_info,struct btrfs_path * path,struct btrfs_key * key,u64 bytenr,u64 len)759 static noinline void truncate_one_csum(struct btrfs_fs_info *fs_info,
760 				       struct btrfs_path *path,
761 				       struct btrfs_key *key,
762 				       u64 bytenr, u64 len)
763 {
764 	struct extent_buffer *leaf;
765 	const u32 csum_size = fs_info->csum_size;
766 	u64 csum_end;
767 	u64 end_byte = bytenr + len;
768 	u32 blocksize_bits = fs_info->sectorsize_bits;
769 
770 	leaf = path->nodes[0];
771 	csum_end = btrfs_item_size(leaf, path->slots[0]) / csum_size;
772 	csum_end <<= blocksize_bits;
773 	csum_end += key->offset;
774 
775 	if (key->offset < bytenr && csum_end <= end_byte) {
776 		/*
777 		 *         [ bytenr - len ]
778 		 *         [   ]
779 		 *   [csum     ]
780 		 *   A simple truncate off the end of the item
781 		 */
782 		u32 new_size = (bytenr - key->offset) >> blocksize_bits;
783 		new_size *= csum_size;
784 		btrfs_truncate_item(path, new_size, 1);
785 	} else if (key->offset >= bytenr && csum_end > end_byte &&
786 		   end_byte > key->offset) {
787 		/*
788 		 *         [ bytenr - len ]
789 		 *                 [ ]
790 		 *                 [csum     ]
791 		 * we need to truncate from the beginning of the csum
792 		 */
793 		u32 new_size = (csum_end - end_byte) >> blocksize_bits;
794 		new_size *= csum_size;
795 
796 		btrfs_truncate_item(path, new_size, 0);
797 
798 		key->offset = end_byte;
799 		btrfs_set_item_key_safe(fs_info, path, key);
800 	} else {
801 		BUG();
802 	}
803 }
804 
805 /*
806  * deletes the csum items from the csum tree for a given
807  * range of bytes.
808  */
btrfs_del_csums(struct btrfs_trans_handle * trans,struct btrfs_root * root,u64 bytenr,u64 len)809 int btrfs_del_csums(struct btrfs_trans_handle *trans,
810 		    struct btrfs_root *root, u64 bytenr, u64 len)
811 {
812 	struct btrfs_fs_info *fs_info = trans->fs_info;
813 	struct btrfs_path *path;
814 	struct btrfs_key key;
815 	u64 end_byte = bytenr + len;
816 	u64 csum_end;
817 	struct extent_buffer *leaf;
818 	int ret = 0;
819 	const u32 csum_size = fs_info->csum_size;
820 	u32 blocksize_bits = fs_info->sectorsize_bits;
821 
822 	ASSERT(root->root_key.objectid == BTRFS_CSUM_TREE_OBJECTID ||
823 	       root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
824 
825 	path = btrfs_alloc_path();
826 	if (!path)
827 		return -ENOMEM;
828 
829 	while (1) {
830 		key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
831 		key.offset = end_byte - 1;
832 		key.type = BTRFS_EXTENT_CSUM_KEY;
833 
834 		ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
835 		if (ret > 0) {
836 			ret = 0;
837 			if (path->slots[0] == 0)
838 				break;
839 			path->slots[0]--;
840 		} else if (ret < 0) {
841 			break;
842 		}
843 
844 		leaf = path->nodes[0];
845 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
846 
847 		if (key.objectid != BTRFS_EXTENT_CSUM_OBJECTID ||
848 		    key.type != BTRFS_EXTENT_CSUM_KEY) {
849 			break;
850 		}
851 
852 		if (key.offset >= end_byte)
853 			break;
854 
855 		csum_end = btrfs_item_size(leaf, path->slots[0]) / csum_size;
856 		csum_end <<= blocksize_bits;
857 		csum_end += key.offset;
858 
859 		/* this csum ends before we start, we're done */
860 		if (csum_end <= bytenr)
861 			break;
862 
863 		/* delete the entire item, it is inside our range */
864 		if (key.offset >= bytenr && csum_end <= end_byte) {
865 			int del_nr = 1;
866 
867 			/*
868 			 * Check how many csum items preceding this one in this
869 			 * leaf correspond to our range and then delete them all
870 			 * at once.
871 			 */
872 			if (key.offset > bytenr && path->slots[0] > 0) {
873 				int slot = path->slots[0] - 1;
874 
875 				while (slot >= 0) {
876 					struct btrfs_key pk;
877 
878 					btrfs_item_key_to_cpu(leaf, &pk, slot);
879 					if (pk.offset < bytenr ||
880 					    pk.type != BTRFS_EXTENT_CSUM_KEY ||
881 					    pk.objectid !=
882 					    BTRFS_EXTENT_CSUM_OBJECTID)
883 						break;
884 					path->slots[0] = slot;
885 					del_nr++;
886 					key.offset = pk.offset;
887 					slot--;
888 				}
889 			}
890 			ret = btrfs_del_items(trans, root, path,
891 					      path->slots[0], del_nr);
892 			if (ret)
893 				break;
894 			if (key.offset == bytenr)
895 				break;
896 		} else if (key.offset < bytenr && csum_end > end_byte) {
897 			unsigned long offset;
898 			unsigned long shift_len;
899 			unsigned long item_offset;
900 			/*
901 			 *        [ bytenr - len ]
902 			 *     [csum                ]
903 			 *
904 			 * Our bytes are in the middle of the csum,
905 			 * we need to split this item and insert a new one.
906 			 *
907 			 * But we can't drop the path because the
908 			 * csum could change, get removed, extended etc.
909 			 *
910 			 * The trick here is the max size of a csum item leaves
911 			 * enough room in the tree block for a single
912 			 * item header.  So, we split the item in place,
913 			 * adding a new header pointing to the existing
914 			 * bytes.  Then we loop around again and we have
915 			 * a nicely formed csum item that we can neatly
916 			 * truncate.
917 			 */
918 			offset = (bytenr - key.offset) >> blocksize_bits;
919 			offset *= csum_size;
920 
921 			shift_len = (len >> blocksize_bits) * csum_size;
922 
923 			item_offset = btrfs_item_ptr_offset(leaf,
924 							    path->slots[0]);
925 
926 			memzero_extent_buffer(leaf, item_offset + offset,
927 					     shift_len);
928 			key.offset = bytenr;
929 
930 			/*
931 			 * btrfs_split_item returns -EAGAIN when the
932 			 * item changed size or key
933 			 */
934 			ret = btrfs_split_item(trans, root, path, &key, offset);
935 			if (ret && ret != -EAGAIN) {
936 				btrfs_abort_transaction(trans, ret);
937 				break;
938 			}
939 			ret = 0;
940 
941 			key.offset = end_byte - 1;
942 		} else {
943 			truncate_one_csum(fs_info, path, &key, bytenr, len);
944 			if (key.offset < bytenr)
945 				break;
946 		}
947 		btrfs_release_path(path);
948 	}
949 	btrfs_free_path(path);
950 	return ret;
951 }
952 
find_next_csum_offset(struct btrfs_root * root,struct btrfs_path * path,u64 * next_offset)953 static int find_next_csum_offset(struct btrfs_root *root,
954 				 struct btrfs_path *path,
955 				 u64 *next_offset)
956 {
957 	const u32 nritems = btrfs_header_nritems(path->nodes[0]);
958 	struct btrfs_key found_key;
959 	int slot = path->slots[0] + 1;
960 	int ret;
961 
962 	if (nritems == 0 || slot >= nritems) {
963 		ret = btrfs_next_leaf(root, path);
964 		if (ret < 0) {
965 			return ret;
966 		} else if (ret > 0) {
967 			*next_offset = (u64)-1;
968 			return 0;
969 		}
970 		slot = path->slots[0];
971 	}
972 
973 	btrfs_item_key_to_cpu(path->nodes[0], &found_key, slot);
974 
975 	if (found_key.objectid != BTRFS_EXTENT_CSUM_OBJECTID ||
976 	    found_key.type != BTRFS_EXTENT_CSUM_KEY)
977 		*next_offset = (u64)-1;
978 	else
979 		*next_offset = found_key.offset;
980 
981 	return 0;
982 }
983 
btrfs_csum_file_blocks(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_ordered_sum * sums)984 int btrfs_csum_file_blocks(struct btrfs_trans_handle *trans,
985 			   struct btrfs_root *root,
986 			   struct btrfs_ordered_sum *sums)
987 {
988 	struct btrfs_fs_info *fs_info = root->fs_info;
989 	struct btrfs_key file_key;
990 	struct btrfs_key found_key;
991 	struct btrfs_path *path;
992 	struct btrfs_csum_item *item;
993 	struct btrfs_csum_item *item_end;
994 	struct extent_buffer *leaf = NULL;
995 	u64 next_offset;
996 	u64 total_bytes = 0;
997 	u64 csum_offset;
998 	u64 bytenr;
999 	u32 ins_size;
1000 	int index = 0;
1001 	int found_next;
1002 	int ret;
1003 	const u32 csum_size = fs_info->csum_size;
1004 
1005 	path = btrfs_alloc_path();
1006 	if (!path)
1007 		return -ENOMEM;
1008 again:
1009 	next_offset = (u64)-1;
1010 	found_next = 0;
1011 	bytenr = sums->bytenr + total_bytes;
1012 	file_key.objectid = BTRFS_EXTENT_CSUM_OBJECTID;
1013 	file_key.offset = bytenr;
1014 	file_key.type = BTRFS_EXTENT_CSUM_KEY;
1015 
1016 	item = btrfs_lookup_csum(trans, root, path, bytenr, 1);
1017 	if (!IS_ERR(item)) {
1018 		ret = 0;
1019 		leaf = path->nodes[0];
1020 		item_end = btrfs_item_ptr(leaf, path->slots[0],
1021 					  struct btrfs_csum_item);
1022 		item_end = (struct btrfs_csum_item *)((char *)item_end +
1023 			   btrfs_item_size(leaf, path->slots[0]));
1024 		goto found;
1025 	}
1026 	ret = PTR_ERR(item);
1027 	if (ret != -EFBIG && ret != -ENOENT)
1028 		goto out;
1029 
1030 	if (ret == -EFBIG) {
1031 		u32 item_size;
1032 		/* we found one, but it isn't big enough yet */
1033 		leaf = path->nodes[0];
1034 		item_size = btrfs_item_size(leaf, path->slots[0]);
1035 		if ((item_size / csum_size) >=
1036 		    MAX_CSUM_ITEMS(fs_info, csum_size)) {
1037 			/* already at max size, make a new one */
1038 			goto insert;
1039 		}
1040 	} else {
1041 		/* We didn't find a csum item, insert one. */
1042 		ret = find_next_csum_offset(root, path, &next_offset);
1043 		if (ret < 0)
1044 			goto out;
1045 		found_next = 1;
1046 		goto insert;
1047 	}
1048 
1049 	/*
1050 	 * At this point, we know the tree has a checksum item that ends at an
1051 	 * offset matching the start of the checksum range we want to insert.
1052 	 * We try to extend that item as much as possible and then add as many
1053 	 * checksums to it as they fit.
1054 	 *
1055 	 * First check if the leaf has enough free space for at least one
1056 	 * checksum. If it has go directly to the item extension code, otherwise
1057 	 * release the path and do a search for insertion before the extension.
1058 	 */
1059 	if (btrfs_leaf_free_space(leaf) >= csum_size) {
1060 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1061 		csum_offset = (bytenr - found_key.offset) >>
1062 			fs_info->sectorsize_bits;
1063 		goto extend_csum;
1064 	}
1065 
1066 	btrfs_release_path(path);
1067 	path->search_for_extension = 1;
1068 	ret = btrfs_search_slot(trans, root, &file_key, path,
1069 				csum_size, 1);
1070 	path->search_for_extension = 0;
1071 	if (ret < 0)
1072 		goto out;
1073 
1074 	if (ret > 0) {
1075 		if (path->slots[0] == 0)
1076 			goto insert;
1077 		path->slots[0]--;
1078 	}
1079 
1080 	leaf = path->nodes[0];
1081 	btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1082 	csum_offset = (bytenr - found_key.offset) >> fs_info->sectorsize_bits;
1083 
1084 	if (found_key.type != BTRFS_EXTENT_CSUM_KEY ||
1085 	    found_key.objectid != BTRFS_EXTENT_CSUM_OBJECTID ||
1086 	    csum_offset >= MAX_CSUM_ITEMS(fs_info, csum_size)) {
1087 		goto insert;
1088 	}
1089 
1090 extend_csum:
1091 	if (csum_offset == btrfs_item_size(leaf, path->slots[0]) /
1092 	    csum_size) {
1093 		int extend_nr;
1094 		u64 tmp;
1095 		u32 diff;
1096 
1097 		tmp = sums->len - total_bytes;
1098 		tmp >>= fs_info->sectorsize_bits;
1099 		WARN_ON(tmp < 1);
1100 		extend_nr = max_t(int, 1, tmp);
1101 
1102 		/*
1103 		 * A log tree can already have checksum items with a subset of
1104 		 * the checksums we are trying to log. This can happen after
1105 		 * doing a sequence of partial writes into prealloc extents and
1106 		 * fsyncs in between, with a full fsync logging a larger subrange
1107 		 * of an extent for which a previous fast fsync logged a smaller
1108 		 * subrange. And this happens in particular due to merging file
1109 		 * extent items when we complete an ordered extent for a range
1110 		 * covered by a prealloc extent - this is done at
1111 		 * btrfs_mark_extent_written().
1112 		 *
1113 		 * So if we try to extend the previous checksum item, which has
1114 		 * a range that ends at the start of the range we want to insert,
1115 		 * make sure we don't extend beyond the start offset of the next
1116 		 * checksum item. If we are at the last item in the leaf, then
1117 		 * forget the optimization of extending and add a new checksum
1118 		 * item - it is not worth the complexity of releasing the path,
1119 		 * getting the first key for the next leaf, repeat the btree
1120 		 * search, etc, because log trees are temporary anyway and it
1121 		 * would only save a few bytes of leaf space.
1122 		 */
1123 		if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
1124 			if (path->slots[0] + 1 >=
1125 			    btrfs_header_nritems(path->nodes[0])) {
1126 				ret = find_next_csum_offset(root, path, &next_offset);
1127 				if (ret < 0)
1128 					goto out;
1129 				found_next = 1;
1130 				goto insert;
1131 			}
1132 
1133 			ret = find_next_csum_offset(root, path, &next_offset);
1134 			if (ret < 0)
1135 				goto out;
1136 
1137 			tmp = (next_offset - bytenr) >> fs_info->sectorsize_bits;
1138 			if (tmp <= INT_MAX)
1139 				extend_nr = min_t(int, extend_nr, tmp);
1140 		}
1141 
1142 		diff = (csum_offset + extend_nr) * csum_size;
1143 		diff = min(diff,
1144 			   MAX_CSUM_ITEMS(fs_info, csum_size) * csum_size);
1145 
1146 		diff = diff - btrfs_item_size(leaf, path->slots[0]);
1147 		diff = min_t(u32, btrfs_leaf_free_space(leaf), diff);
1148 		diff /= csum_size;
1149 		diff *= csum_size;
1150 
1151 		btrfs_extend_item(path, diff);
1152 		ret = 0;
1153 		goto csum;
1154 	}
1155 
1156 insert:
1157 	btrfs_release_path(path);
1158 	csum_offset = 0;
1159 	if (found_next) {
1160 		u64 tmp;
1161 
1162 		tmp = sums->len - total_bytes;
1163 		tmp >>= fs_info->sectorsize_bits;
1164 		tmp = min(tmp, (next_offset - file_key.offset) >>
1165 					 fs_info->sectorsize_bits);
1166 
1167 		tmp = max_t(u64, 1, tmp);
1168 		tmp = min_t(u64, tmp, MAX_CSUM_ITEMS(fs_info, csum_size));
1169 		ins_size = csum_size * tmp;
1170 	} else {
1171 		ins_size = csum_size;
1172 	}
1173 	ret = btrfs_insert_empty_item(trans, root, path, &file_key,
1174 				      ins_size);
1175 	if (ret < 0)
1176 		goto out;
1177 	if (WARN_ON(ret != 0))
1178 		goto out;
1179 	leaf = path->nodes[0];
1180 csum:
1181 	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_csum_item);
1182 	item_end = (struct btrfs_csum_item *)((unsigned char *)item +
1183 				      btrfs_item_size(leaf, path->slots[0]));
1184 	item = (struct btrfs_csum_item *)((unsigned char *)item +
1185 					  csum_offset * csum_size);
1186 found:
1187 	ins_size = (u32)(sums->len - total_bytes) >> fs_info->sectorsize_bits;
1188 	ins_size *= csum_size;
1189 	ins_size = min_t(u32, (unsigned long)item_end - (unsigned long)item,
1190 			      ins_size);
1191 	write_extent_buffer(leaf, sums->sums + index, (unsigned long)item,
1192 			    ins_size);
1193 
1194 	index += ins_size;
1195 	ins_size /= csum_size;
1196 	total_bytes += ins_size * fs_info->sectorsize;
1197 
1198 	btrfs_mark_buffer_dirty(path->nodes[0]);
1199 	if (total_bytes < sums->len) {
1200 		btrfs_release_path(path);
1201 		cond_resched();
1202 		goto again;
1203 	}
1204 out:
1205 	btrfs_free_path(path);
1206 	return ret;
1207 }
1208 
btrfs_extent_item_to_extent_map(struct btrfs_inode * inode,const struct btrfs_path * path,struct btrfs_file_extent_item * fi,const bool new_inline,struct extent_map * em)1209 void btrfs_extent_item_to_extent_map(struct btrfs_inode *inode,
1210 				     const struct btrfs_path *path,
1211 				     struct btrfs_file_extent_item *fi,
1212 				     const bool new_inline,
1213 				     struct extent_map *em)
1214 {
1215 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
1216 	struct btrfs_root *root = inode->root;
1217 	struct extent_buffer *leaf = path->nodes[0];
1218 	const int slot = path->slots[0];
1219 	struct btrfs_key key;
1220 	u64 extent_start, extent_end;
1221 	u64 bytenr;
1222 	u8 type = btrfs_file_extent_type(leaf, fi);
1223 	int compress_type = btrfs_file_extent_compression(leaf, fi);
1224 
1225 	btrfs_item_key_to_cpu(leaf, &key, slot);
1226 	extent_start = key.offset;
1227 	extent_end = btrfs_file_extent_end(path);
1228 	em->ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1229 	em->generation = btrfs_file_extent_generation(leaf, fi);
1230 	if (type == BTRFS_FILE_EXTENT_REG ||
1231 	    type == BTRFS_FILE_EXTENT_PREALLOC) {
1232 		em->start = extent_start;
1233 		em->len = extent_end - extent_start;
1234 		em->orig_start = extent_start -
1235 			btrfs_file_extent_offset(leaf, fi);
1236 		em->orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
1237 		bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1238 		if (bytenr == 0) {
1239 			em->block_start = EXTENT_MAP_HOLE;
1240 			return;
1241 		}
1242 		if (compress_type != BTRFS_COMPRESS_NONE) {
1243 			set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
1244 			em->compress_type = compress_type;
1245 			em->block_start = bytenr;
1246 			em->block_len = em->orig_block_len;
1247 		} else {
1248 			bytenr += btrfs_file_extent_offset(leaf, fi);
1249 			em->block_start = bytenr;
1250 			em->block_len = em->len;
1251 			if (type == BTRFS_FILE_EXTENT_PREALLOC)
1252 				set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
1253 		}
1254 	} else if (type == BTRFS_FILE_EXTENT_INLINE) {
1255 		em->block_start = EXTENT_MAP_INLINE;
1256 		em->start = extent_start;
1257 		em->len = extent_end - extent_start;
1258 		/*
1259 		 * Initialize orig_start and block_len with the same values
1260 		 * as in inode.c:btrfs_get_extent().
1261 		 */
1262 		em->orig_start = EXTENT_MAP_HOLE;
1263 		em->block_len = (u64)-1;
1264 		if (!new_inline && compress_type != BTRFS_COMPRESS_NONE) {
1265 			set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
1266 			em->compress_type = compress_type;
1267 		}
1268 	} else {
1269 		btrfs_err(fs_info,
1270 			  "unknown file extent item type %d, inode %llu, offset %llu, "
1271 			  "root %llu", type, btrfs_ino(inode), extent_start,
1272 			  root->root_key.objectid);
1273 	}
1274 }
1275 
1276 /*
1277  * Returns the end offset (non inclusive) of the file extent item the given path
1278  * points to. If it points to an inline extent, the returned offset is rounded
1279  * up to the sector size.
1280  */
btrfs_file_extent_end(const struct btrfs_path * path)1281 u64 btrfs_file_extent_end(const struct btrfs_path *path)
1282 {
1283 	const struct extent_buffer *leaf = path->nodes[0];
1284 	const int slot = path->slots[0];
1285 	struct btrfs_file_extent_item *fi;
1286 	struct btrfs_key key;
1287 	u64 end;
1288 
1289 	btrfs_item_key_to_cpu(leaf, &key, slot);
1290 	ASSERT(key.type == BTRFS_EXTENT_DATA_KEY);
1291 	fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
1292 
1293 	if (btrfs_file_extent_type(leaf, fi) == BTRFS_FILE_EXTENT_INLINE) {
1294 		end = btrfs_file_extent_ram_bytes(leaf, fi);
1295 		end = ALIGN(key.offset + end, leaf->fs_info->sectorsize);
1296 	} else {
1297 		end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
1298 	}
1299 
1300 	return end;
1301 }
1302