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