Debian Codegraph @

extents.c

raw symbols SCIP
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * Copyright (C) 2018 Ernesto A. Fernández <[email protected]>
4 */
5
6 #include <linux/buffer_head.h>
7 #include <linux/slab.h>
8 #include <linux/blk_types.h>
9 #include "apfs.h"
10
11 /**
12 * apfs_ext_is_hole - Does this extent represent a hole in a sparse file?
13 * @extent: the extent to check
14 */
15 static inline bool apfs_ext_is_hole(struct apfs_file_extent *extent)
16 {
17 return extent->phys_block_num == 0;
18 }
19
20 /**
21 * apfs_size_to_blocks - Return the block count for a given size, rounded up
22 * @sb: filesystem superblock
23 * @size: size in bytes
24 *
25 * TODO: reuse for inode.c
26 */
27 static inline u64 apfs_size_to_blocks(struct super_block *sb, u64 size)
28 {
29 return (size + sb->s_blocksize - 1) >> sb->s_blocksize_bits;
30 }
31
32 /**
33 * apfs_extent_from_query - Read the extent found by a successful query
34 * @query: the query that found the record
35 * @extent: Return parameter. The extent found.
36 *
37 * Reads the extent record into @extent and performs some basic sanity checks
38 * as a protection against crafted filesystems. Returns 0 on success or
39 * -EFSCORRUPTED otherwise.
40 */
41 int apfs_extent_from_query(struct apfs_query *query,
42 struct apfs_file_extent *extent)
43 {
44 struct super_block *sb = query->node->object.sb;
45 char *raw = query->node->object.data;
46 u64 ext_len;
47
48 if (!apfs_is_sealed(sb)) {
49 struct apfs_file_extent_val *ext = NULL;
50 struct apfs_file_extent_key *ext_key = NULL;
51
52 if (query->len != sizeof(*ext) || query->key_len != sizeof(*ext_key)) {
53 apfs_err(sb, "bad length of key (%d) or value (%d)", query->key_len, query->len);
54 return -EFSCORRUPTED;
55 }
56
57 ext = (struct apfs_file_extent_val *)(raw + query->off);
58 ext_key = (struct apfs_file_extent_key *)(raw + query->key_off);
59 ext_len = le64_to_cpu(ext->len_and_flags) & APFS_FILE_EXTENT_LEN_MASK;
60
61 extent->logical_addr = le64_to_cpu(ext_key->logical_addr);
62 extent->phys_block_num = le64_to_cpu(ext->phys_block_num);
63 extent->crypto_id = le64_to_cpu(ext->crypto_id);
64 } else {
65 struct apfs_fext_tree_val *fext_val = NULL;
66 struct apfs_fext_tree_key *fext_key = NULL;
67
68 if (query->len != sizeof(*fext_val) || query->key_len != sizeof(*fext_key)) {
69 apfs_err(sb, "bad length of sealed key (%d) or value (%d)", query->key_len, query->len);
70 return -EFSCORRUPTED;
71 }
72
73 fext_val = (struct apfs_fext_tree_val *)(raw + query->off);
74 fext_key = (struct apfs_fext_tree_key *)(raw + query->key_off);
75 ext_len = le64_to_cpu(fext_val->len_and_flags) & APFS_FILE_EXTENT_LEN_MASK;
76
77 extent->logical_addr = le64_to_cpu(fext_key->logical_addr);
78 extent->phys_block_num = le64_to_cpu(fext_val->phys_block_num);
79 extent->crypto_id = 0;
80 }
81
82 /* Extent length must be a multiple of the block size */
83 if (ext_len & (sb->s_blocksize - 1)) {
84 apfs_err(sb, "invalid length (0x%llx)", ext_len);
85 return -EFSCORRUPTED;
86 }
87 extent->len = ext_len;
88 return 0;
89 }
90
91 /**
92 * apfs_extent_read - Read the extent record that covers a block
93 * @dstream: data stream info
94 * @dsblock: logical number of the wanted block (must be in range)
95 * @extent: Return parameter. The extent found.
96 *
97 * Finds and caches the extent record. On success, returns a pointer to the
98 * cache record; on failure, returns an error code.
99 */
100 static int apfs_extent_read(struct apfs_dstream_info *dstream, sector_t dsblock,
101 struct apfs_file_extent *extent)
102 {
103 struct super_block *sb = dstream->ds_sb;
104 struct apfs_sb_info *sbi = APFS_SB(sb);
105 struct apfs_superblock *vsb_raw = sbi->s_vsb_raw;
106 struct apfs_key key;
107 struct apfs_query *query;
108 struct apfs_file_extent *cache = &dstream->ds_cached_ext;
109 u64 iaddr = dsblock << sb->s_blocksize_bits;
110 struct apfs_node *root = NULL;
111 int ret = 0;
112
113 spin_lock(&dstream->ds_ext_lock);
114 if (iaddr >= cache->logical_addr &&
115 iaddr < cache->logical_addr + cache->len) {
116 *extent = *cache;
117 spin_unlock(&dstream->ds_ext_lock);
118 return 0;
119 }
120 spin_unlock(&dstream->ds_ext_lock);
121
122 /* We will search for the extent that covers iblock */
123 if (!apfs_is_sealed(sb)) {
124 apfs_init_file_extent_key(dstream->ds_id, iaddr, &key);
125 root = sbi->s_cat_root;
126 } else {
127 apfs_init_fext_key(dstream->ds_id, iaddr, &key);
128 root = apfs_read_node(sb, le64_to_cpu(vsb_raw->apfs_fext_tree_oid), APFS_OBJ_PHYSICAL, false /* write */);
129 if (IS_ERR(root)) {
130 apfs_err(sb, "failed to read fext root 0x%llx", le64_to_cpu(vsb_raw->apfs_fext_tree_oid));
131 return PTR_ERR(root);
132 }
133 }
134
135 query = apfs_alloc_query(root, NULL /* parent */);
136 if (!query) {
137 ret = -ENOMEM;
138 goto done;
139 }
140 query->key = key;
141 query->flags = apfs_is_sealed(sb) ? APFS_QUERY_FEXT : APFS_QUERY_CAT;
142
143 ret = apfs_btree_query(sb, &query);
144 if (ret) {
145 apfs_err(sb, "query failed for id 0x%llx, addr 0x%llx", dstream->ds_id, iaddr);
146 if (ret == -ENODATA)
147 ret = -EFSCORRUPTED;
148 goto done;
149 }
150
151 ret = apfs_extent_from_query(query, extent);
152 if (ret) {
153 apfs_err(sb, "bad extent record for dstream 0x%llx", dstream->ds_id);
154 goto done;
155 }
156 if (iaddr < extent->logical_addr || iaddr >= extent->logical_addr + extent->len) {
157 apfs_err(sb, "no extent for addr 0x%llx in dstream 0x%llx", iaddr, dstream->ds_id);
158 ret = -EFSCORRUPTED;
159 goto done;
160 }
161
162 /*
163 * For now prioritize the deferral of writes.
164 * i_extent_dirty is protected by the read semaphore.
165 */
166 if (!dstream->ds_ext_dirty) {
167 spin_lock(&dstream->ds_ext_lock);
168 *cache = *extent;
169 spin_unlock(&dstream->ds_ext_lock);
170 }
171
172 done:
173 apfs_free_query(query);
174 if (apfs_is_sealed(sb))
175 apfs_node_free(root);
176 return ret;
177 }
178
179 /**
180 * apfs_logic_to_phys_bno - Find the physical block number for a dstream block
181 * @dstream: data stream info
182 * @dsblock: logical number of the wanted block
183 * @bno: on return, the physical block number (or zero for holes)
184 *
185 * Returns 0 on success or a negative error code in case of failure.
186 */
187 int apfs_logic_to_phys_bno(struct apfs_dstream_info *dstream, sector_t dsblock, u64 *bno)
188 {
189 struct super_block *sb = dstream->ds_sb;
190 struct apfs_file_extent ext;
191 u64 blk_off;
192 int ret;
193
194 ret = apfs_extent_read(dstream, dsblock, &ext);
195 if (ret)
196 return ret;
197
198 if (apfs_ext_is_hole(&ext)) {
199 *bno = 0;
200 return 0;
201 }
202
203 /* Find the block offset of iblock within the extent */
204 blk_off = dsblock - (ext.logical_addr >> sb->s_blocksize_bits);
205 *bno = ext.phys_block_num + blk_off;
206 return 0;
207 }
208
209 /* This does the same as apfs_get_block(), but without taking any locks */
210 int __apfs_get_block(struct apfs_dstream_info *dstream, sector_t dsblock,
211 struct buffer_head *bh_result, int create)
212 {
213 struct super_block *sb = dstream->ds_sb;
214 struct apfs_file_extent ext;
215 u64 blk_off, bno, map_len;
216 int ret;
217
218 ASSERT(!create);
219
220 if (dsblock >= apfs_size_to_blocks(sb, dstream->ds_size))
221 return 0;
222
223 ret = apfs_extent_read(dstream, dsblock, &ext);
224 if (ret) {
225 apfs_err(sb, "extent read failed");
226 return ret;
227 }
228
229 /* Find the block offset of iblock within the extent */
230 blk_off = dsblock - (ext.logical_addr >> sb->s_blocksize_bits);
231
232 /* Make sure we don't read past the extent boundaries */
233 map_len = ext.len - (blk_off << sb->s_blocksize_bits);
234 if (bh_result->b_size > map_len)
235 bh_result->b_size = map_len;
236
237 /*
238 * Save the requested mapping length as apfs_map_bh() replaces it with
239 * the filesystem block size
240 */
241 map_len = bh_result->b_size;
242 /* Extents representing holes have block number 0 */
243 if (!apfs_ext_is_hole(&ext)) {
244 /* Find the block number of iblock within the disk */
245 bno = ext.phys_block_num + blk_off;
246 apfs_map_bh(bh_result, sb, bno);
247 }
248 bh_result->b_size = map_len;
249 return 0;
250 }
251
252 int apfs_get_block(struct inode *inode, sector_t iblock,
253 struct buffer_head *bh_result, int create)
254 {
255 struct apfs_nxsb_info *nxi = APFS_NXI(inode->i_sb);
256 struct apfs_inode_info *ai = APFS_I(inode);
257 int ret;
258
259 down_read(&nxi->nx_big_sem);
260 ret = __apfs_get_block(&ai->i_dstream, iblock, bh_result, create);
261 up_read(&nxi->nx_big_sem);
262 return ret;
263 }
264
265 /**
266 * apfs_set_extent_length - Set a new length in an extent record's value
267 * @ext: the extent record's value
268 * @len: the new length
269 *
270 * Preserves the flags, though none are defined yet and I don't know if that
271 * will ever be important.
272 */
273 static inline void apfs_set_extent_length(struct apfs_file_extent_val *ext, u64 len)
274 {
275 u64 len_and_flags = le64_to_cpu(ext->len_and_flags);
276 u64 flags = len_and_flags & APFS_FILE_EXTENT_FLAG_MASK;
277
278 ext->len_and_flags = cpu_to_le64(flags | len);
279 }
280
281 static int apfs_range_put_reference(struct super_block *sb, u64 paddr, u64 length);
282
283 /**
284 * apfs_shrink_extent_head - Shrink an extent record in its head
285 * @query: the query that found the record
286 * @dstream: data stream info
287 * @start: new logical start for the extent
288 *
289 * Also deletes the physical extent records for the head. Returns 0 on success
290 * or a negative error code in case of failure.
291 */
292 static int apfs_shrink_extent_head(struct apfs_query *query, struct apfs_dstream_info *dstream, u64 start)
293 {
294 struct super_block *sb = query->node->object.sb;
295 struct apfs_file_extent_key key;
296 struct apfs_file_extent_val val;
297 struct apfs_file_extent extent;
298 u64 new_len, head_len;
299 void *raw = NULL;
300 int err = 0;
301
302 err = apfs_extent_from_query(query, &extent);
303 if (err) {
304 apfs_err(sb, "bad extent record for dstream 0x%llx", dstream->ds_id);
305 return err;
306 }
307 raw = query->node->object.data;
308 key = *(struct apfs_file_extent_key *)(raw + query->key_off);
309 val = *(struct apfs_file_extent_val *)(raw + query->off);
310
311 new_len = extent.logical_addr + extent.len - start;
312 head_len = extent.len - new_len;
313
314 /* Delete the physical records for the blocks lost in the shrinkage */
315 if (!apfs_ext_is_hole(&extent)) {
316 err = apfs_range_put_reference(sb, extent.phys_block_num, head_len);
317 if (err) {
318 apfs_err(sb, "failed to put range 0x%llx-0x%llx", extent.phys_block_num, head_len);
319 return err;
320 }
321 } else {
322 dstream->ds_sparse_bytes -= head_len;
323 }
324
325 /* This is the actual shrinkage of the logical extent */
326 key.logical_addr = cpu_to_le64(start);
327 apfs_set_extent_length(&val, new_len);
328 if (!apfs_ext_is_hole(&extent))
329 le64_add_cpu(&val.phys_block_num, head_len >> sb->s_blocksize_bits);
330 return apfs_btree_replace(query, &key, sizeof(key), &val, sizeof(val));
331 }
332
333 /**
334 * apfs_shrink_extent_tail - Shrink an extent record in its tail
335 * @query: the query that found the record
336 * @dstream: data stream info
337 * @end: new logical end for the extent
338 *
339 * Also puts the physical extent records for the tail. Returns 0 on success or
340 * a negative error code in case of failure.
341 */
342 static int apfs_shrink_extent_tail(struct apfs_query *query, struct apfs_dstream_info *dstream, u64 end)
343 {
344 struct super_block *sb = query->node->object.sb;
345 struct apfs_file_extent_val *val;
346 struct apfs_file_extent extent;
347 u64 new_len, new_blkcount, tail_len;
348 void *raw;
349 int err = 0;
350
351 ASSERT((end & (sb->s_blocksize - 1)) == 0);
352
353 err = apfs_query_join_transaction(query);
354 if (err) {
355 apfs_err(sb, "query join failed");
356 return err;
357 }
358 raw = query->node->object.data;
359
360 err = apfs_extent_from_query(query, &extent);
361 if (err) {
362 apfs_err(sb, "bad extent record for dstream 0x%llx", dstream->ds_id);
363 return err;
364 }
365 val = raw + query->off;
366
367 new_len = end - extent.logical_addr;
368 new_blkcount = new_len >> sb->s_blocksize_bits;
369 tail_len = extent.len - new_len;
370
371 /* Delete the physical records for the blocks lost in the shrinkage */
372 if (!apfs_ext_is_hole(&extent)) {
373 err = apfs_range_put_reference(sb, extent.phys_block_num + new_blkcount, tail_len);
374 if (err) {
375 apfs_err(sb, "failed to put range 0x%llx-0x%llx", extent.phys_block_num + new_blkcount, tail_len);
376 return err;
377 }
378 } else {
379 dstream->ds_sparse_bytes -= tail_len;
380 }
381
382 /* This is the actual shrinkage of the logical extent */
383 apfs_set_extent_length(val, new_len);
384 return err;
385 }
386
387 /**
388 * apfs_query_found_extent - Did this query find an extent with the right id?
389 * @query: the (successful) query that found the record
390 */
391 static inline bool apfs_query_found_extent(struct apfs_query *query)
392 {
393 void *raw = query->node->object.data;
394 struct apfs_key_header *hdr;
395
396 if (query->key_len < sizeof(*hdr))
397 return false;
398 hdr = raw + query->key_off;
399
400 if (apfs_cat_type(hdr) != APFS_TYPE_FILE_EXTENT)
401 return false;
402 if (apfs_cat_cnid(hdr) != query->key.id)
403 return false;
404 return true;
405 }
406
407 /**
408 * apfs_update_tail_extent - Grow the tail extent for a data stream
409 * @dstream: data stream info
410 * @extent: new in-memory extent
411 *
412 * Also takes care of any needed changes to the physical extent records. Returns
413 * 0 on success or a negative error code in case of failure.
414 */
415 static int apfs_update_tail_extent(struct apfs_dstream_info *dstream, const struct apfs_file_extent *extent)
416 {
417 struct super_block *sb = dstream->ds_sb;
418 struct apfs_sb_info *sbi = APFS_SB(sb);
419 struct apfs_query *query;
420 struct apfs_file_extent_key raw_key;
421 struct apfs_file_extent_val raw_val;
422 u64 extent_id = dstream->ds_id;
423 int ret;
424 u64 new_crypto;
425
426 apfs_key_set_hdr(APFS_TYPE_FILE_EXTENT, extent_id, &raw_key);
427 raw_key.logical_addr = cpu_to_le64(extent->logical_addr);
428 raw_val.len_and_flags = cpu_to_le64(extent->len);
429 raw_val.phys_block_num = cpu_to_le64(extent->phys_block_num);
430 if (apfs_vol_is_encrypted(sb))
431 new_crypto = extent_id;
432 else
433 new_crypto = 0;
434 raw_val.crypto_id = cpu_to_le64(new_crypto);
435
436 query = apfs_alloc_query(sbi->s_cat_root, NULL /* parent */);
437 if (!query)
438 return -ENOMEM;
439 /* We want the last extent record */
440 apfs_init_file_extent_key(extent_id, -1, &query->key);
441 query->flags = APFS_QUERY_CAT;
442
443 ret = apfs_btree_query(sb, &query);
444 if (ret && ret != -ENODATA) {
445 apfs_err(sb, "query failed for last extent of id 0x%llx", extent_id);
446 goto out;
447 }
448
449 if (ret == -ENODATA || !apfs_query_found_extent(query)) {
450 /* We are creating the first extent for the file */
451 ret = apfs_btree_insert(query, &raw_key, sizeof(raw_key), &raw_val, sizeof(raw_val));
452 if (ret) {
453 apfs_err(sb, "insertion failed for id 0x%llx, addr 0x%llx", extent_id, extent->logical_addr);
454 goto out;
455 }
456 } else {
457 struct apfs_file_extent tail;
458
459 ret = apfs_extent_from_query(query, &tail);
460 if (ret) {
461 apfs_err(sb, "bad extent record for dstream 0x%llx", dstream->ds_id);
462 goto out;
463 }
464
465 if (tail.logical_addr > extent->logical_addr) {
466 apfs_alert(sb, "extent is not tail - bug!");
467 ret = -EOPNOTSUPP;
468 goto out;
469 } else if (tail.logical_addr == extent->logical_addr) {
470 ret = apfs_btree_replace(query, &raw_key, sizeof(raw_key), &raw_val, sizeof(raw_val));
471 if (ret) {
472 apfs_err(sb, "update failed for id 0x%llx, addr 0x%llx", extent_id, extent->logical_addr);
473 goto out;
474 }
475 if (apfs_ext_is_hole(&tail)) {
476 dstream->ds_sparse_bytes -= tail.len;
477 } else if (tail.phys_block_num != extent->phys_block_num) {
478 ret = apfs_range_put_reference(sb, tail.phys_block_num, tail.len);
479 if (ret) {
480 apfs_err(sb, "failed to put range 0x%llx-0x%llx", tail.phys_block_num, tail.len);
481 goto out;
482 }
483 }
484 if (new_crypto == tail.crypto_id)
485 goto out;
486 ret = apfs_crypto_adj_refcnt(sb, tail.crypto_id, -1);
487 if (ret) {
488 apfs_err(sb, "failed to put crypto id 0x%llx", tail.crypto_id);
489 goto out;
490 }
491 } else {
492 /*
493 * TODO: we could actually also continue the tail extent
494 * if it's right next to the new one (both logically and
495 * physically), even if they don't overlap. Or maybe we
496 * should always make sure that the tail extent is in
497 * the cache before a write...
498 */
499 if (extent->logical_addr < tail.logical_addr + tail.len) {
500 ret = apfs_shrink_extent_tail(query, dstream, extent->logical_addr);
501 if (ret) {
502 apfs_err(sb, "failed to shrink tail of dstream 0x%llx", extent_id);
503 goto out;
504 }
505 }
506 ret = apfs_btree_insert(query, &raw_key, sizeof(raw_key), &raw_val, sizeof(raw_val));
507 if (ret) {
508 apfs_err(sb, "insertion failed for id 0x%llx, addr 0x%llx", extent_id, extent->logical_addr);
509 goto out;
510 }
511 }
512 }
513
514 ret = apfs_crypto_adj_refcnt(sb, new_crypto, 1);
515 if (ret)
516 apfs_err(sb, "failed to take crypto id 0x%llx", new_crypto);
517
518 out:
519 apfs_free_query(query);
520 return ret;
521 }
522
523 /**
524 * apfs_split_extent - Break an extent in two
525 * @query: query pointing to the extent
526 * @div: logical address for the division
527 *
528 * Returns 0 on success or a negative error code in case of failure.
529 */
530 static int apfs_split_extent(struct apfs_query *query, u64 div)
531 {
532 struct super_block *sb = query->node->object.sb;
533 struct apfs_file_extent_val *val1;
534 struct apfs_file_extent_key key2;
535 struct apfs_file_extent_val val2;
536 struct apfs_file_extent extent;
537 u64 len1, len2, blkcount1;
538 void *raw;
539 int err = 0;
540
541 err = apfs_query_join_transaction(query);
542 if (err) {
543 apfs_err(sb, "query join failed");
544 return err;
545 }
546 raw = query->node->object.data;
547
548 err = apfs_extent_from_query(query, &extent);
549 if (err) {
550 apfs_err(sb, "bad extent record");
551 return err;
552 }
553 val1 = raw + query->off;
554 val2 = *(struct apfs_file_extent_val *)(raw + query->off);
555 key2 = *(struct apfs_file_extent_key *)(raw + query->key_off);
556
557 len1 = div - extent.logical_addr;
558 blkcount1 = len1 >> sb->s_blocksize_bits;
559 len2 = extent.len - len1;
560
561 /* Modify the current extent in place to become the first half */
562 apfs_set_extent_length(val1, len1);
563
564 /* Insert the second half right after the first */
565 key2.logical_addr = cpu_to_le64(div);
566 if (!apfs_ext_is_hole(&extent))
567 val2.phys_block_num = cpu_to_le64(extent.phys_block_num + blkcount1);
568 apfs_set_extent_length(&val2, len2);
569 err = apfs_btree_insert(query, &key2, sizeof(key2), &val2, sizeof(val2));
570 if (err) {
571 apfs_err(sb, "insertion failed in division 0x%llx", div);
572 return err;
573 }
574
575 return apfs_crypto_adj_refcnt(sb, extent.crypto_id, 1);
576 }
577
578 /**
579 * apfs_update_mid_extent - Create or update a non-tail extent for a dstream
580 * @dstream: data stream info
581 * @extent: new in-memory extent
582 *
583 * Also takes care of any needed changes to the physical extent records. Returns
584 * 0 on success or a negative error code in case of failure.
585 */
586 static int apfs_update_mid_extent(struct apfs_dstream_info *dstream, const struct apfs_file_extent *extent)
587 {
588 struct super_block *sb = dstream->ds_sb;
589 struct apfs_sb_info *sbi = APFS_SB(sb);
590 struct apfs_key key;
591 struct apfs_query *query;
592 struct apfs_file_extent_key raw_key;
593 struct apfs_file_extent_val raw_val;
594 struct apfs_file_extent prev_ext;
595 u64 extent_id = dstream->ds_id;
596 u64 prev_crypto, new_crypto;
597 u64 prev_start, prev_end;
598 bool second_run = false;
599 int ret;
600
601 apfs_key_set_hdr(APFS_TYPE_FILE_EXTENT, extent_id, &raw_key);
602 raw_key.logical_addr = cpu_to_le64(extent->logical_addr);
603 raw_val.len_and_flags = cpu_to_le64(extent->len);
604 raw_val.phys_block_num = cpu_to_le64(extent->phys_block_num);
605 if (apfs_vol_is_encrypted(sb))
606 new_crypto = extent_id;
607 else
608 new_crypto = 0;
609 raw_val.crypto_id = cpu_to_le64(new_crypto);
610
611 apfs_init_file_extent_key(extent_id, extent->logical_addr, &key);
612
613 search_and_insert:
614 query = apfs_alloc_query(sbi->s_cat_root, NULL /* parent */);
615 if (!query)
616 return -ENOMEM;
617 query->key = key;
618 query->flags = APFS_QUERY_CAT;
619
620 ret = apfs_btree_query(sb, &query);
621 if (ret && ret != -ENODATA) {
622 apfs_err(sb, "query failed for id 0x%llx, addr 0x%llx", extent_id, extent->logical_addr);
623 goto out;
624 }
625
626 if (ret == -ENODATA || !apfs_query_found_extent(query)) {
627 /*
628 * The new extent goes in a hole we just made, right at the
629 * beginning of the file.
630 */
631 if (!second_run) {
632 apfs_err(sb, "missing extent on dstream 0x%llx", extent_id);
633 ret = -EFSCORRUPTED;
634 } else {
635 ret = apfs_btree_insert(query, &raw_key, sizeof(raw_key), &raw_val, sizeof(raw_val));
636 if (ret)
637 apfs_err(sb, "insertion failed for id 0x%llx, addr 0x%llx", extent_id, extent->logical_addr);
638 }
639 goto out;
640 }
641
642 if (apfs_extent_from_query(query, &prev_ext)) {
643 apfs_err(sb, "bad mid extent record on dstream 0x%llx", extent_id);
644 ret = -EFSCORRUPTED;
645 goto out;
646 }
647 prev_crypto = prev_ext.crypto_id;
648 prev_start = prev_ext.logical_addr;
649 prev_end = prev_ext.logical_addr + prev_ext.len;
650
651 if (prev_end == extent->logical_addr && second_run) {
652 /* The new extent goes in the hole we just made */
653 ret = apfs_btree_insert(query, &raw_key, sizeof(raw_key), &raw_val, sizeof(raw_val));
654 if (ret) {
655 apfs_err(sb, "insertion failed for id 0x%llx, addr 0x%llx", extent_id, extent->logical_addr);
656 goto out;
657 }
658 } else if (prev_start == extent->logical_addr && prev_ext.len == extent->len) {
659 /* The old and new extents are the same logical block */
660 ret = apfs_btree_replace(query, &raw_key, sizeof(raw_key), &raw_val, sizeof(raw_val));
661 if (ret) {
662 apfs_err(sb, "update failed for id 0x%llx, addr 0x%llx", extent_id, extent->logical_addr);
663 goto out;
664 }
665 if (apfs_ext_is_hole(&prev_ext)) {
666 dstream->ds_sparse_bytes -= prev_ext.len;
667 } else if (prev_ext.phys_block_num != extent->phys_block_num) {
668 ret = apfs_range_put_reference(sb, prev_ext.phys_block_num, prev_ext.len);
669 if (ret) {
670 apfs_err(sb, "failed to put range 0x%llx-0x%llx", prev_ext.phys_block_num, prev_ext.len);
671 goto out;
672 }
673 }
674 ret = apfs_crypto_adj_refcnt(sb, prev_crypto, -1);
675 if (ret) {
676 apfs_err(sb, "failed to put crypto id 0x%llx", prev_crypto);
677 goto out;
678 }
679 } else if (prev_start == extent->logical_addr) {
680 /* The new extent is the first logical block of the old one */
681 if (second_run) {
682 /* I don't know if this is possible, but be safe */
683 apfs_alert(sb, "recursion shrinking extent head for dstream 0x%llx", extent_id);
684 ret = -EFSCORRUPTED;
685 goto out;
686 }
687 ret = apfs_shrink_extent_head(query, dstream, extent->logical_addr + extent->len);
688 if (ret) {
689 apfs_err(sb, "failed to shrink extent in dstream 0x%llx", extent_id);
690 goto out;
691 }
692 /* The query should point to the previous record, start again */
693 apfs_free_query(query);
694 second_run = true;
695 goto search_and_insert;
696 } else if (prev_end == extent->logical_addr + extent->len) {
697 /* The new extent is the last logical block of the old one */
698 ret = apfs_shrink_extent_tail(query, dstream, extent->logical_addr);
699 if (ret) {
700 apfs_err(sb, "failed to shrink extent in dstream 0x%llx", extent_id);
701 goto out;
702 }
703 ret = apfs_btree_insert(query, &raw_key, sizeof(raw_key), &raw_val, sizeof(raw_val));
704 if (ret) {
705 apfs_err(sb, "insertion failed for id 0x%llx, addr 0x%llx", extent_id, extent->logical_addr);
706 goto out;
707 }
708 } else if (prev_start < extent->logical_addr && prev_end > extent->logical_addr + extent->len) {
709 /* The new extent is logically in the middle of the old one */
710 if (second_run) {
711 /* I don't know if this is possible, but be safe */
712 apfs_alert(sb, "recursion when splitting extents for dstream 0x%llx", extent_id);
713 ret = -EFSCORRUPTED;
714 goto out;
715 }
716 ret = apfs_split_extent(query, extent->logical_addr + extent->len);
717 if (ret) {
718 apfs_err(sb, "failed to split extent in dstream 0x%llx", extent_id);
719 goto out;
720 }
721 /* The split may make the query invalid */
722 apfs_free_query(query);
723 second_run = true;
724 goto search_and_insert;
725 } else {
726 /* I don't know what this is, be safe */
727 apfs_alert(sb, "strange extents for dstream 0x%llx", extent_id);
728 ret = -EFSCORRUPTED;
729 goto out;
730 }
731
732 ret = apfs_crypto_adj_refcnt(sb, new_crypto, 1);
733 if (ret)
734 apfs_err(sb, "failed to take crypto id 0x%llx", new_crypto);
735
736 out:
737 apfs_free_query(query);
738 return ret;
739 }
740
741 /**
742 * apfs_update_extent - Create or update the extent record for an extent
743 * @dstream: data stream info
744 * @extent: new in-memory file extent
745 *
746 * The @extent must either be a new tail for the dstream, or a single block.
747 * Returns 0 on success or a negative error code in case of failure.
748 */
749 static int apfs_update_extent(struct apfs_dstream_info *dstream, const struct apfs_file_extent *extent)
750 {
751 struct super_block *sb = dstream->ds_sb;
752
753 if (extent->logical_addr + extent->len >= dstream->ds_size)
754 return apfs_update_tail_extent(dstream, extent);
755 if (extent->len > sb->s_blocksize) {
756 apfs_err(sb, "can't create mid extents of length 0x%llx", extent->len);
757 return -EOPNOTSUPP;
758 }
759 return apfs_update_mid_extent(dstream, extent);
760 }
761
762 static int apfs_extend_phys_extent(struct apfs_query *query, u64 bno, u64 blkcnt, u64 dstream_id)
763 {
764 struct apfs_phys_ext_key raw_key;
765 struct apfs_phys_ext_val raw_val;
766 u64 kind = (u64)APFS_KIND_NEW << APFS_PEXT_KIND_SHIFT;
767
768 apfs_key_set_hdr(APFS_TYPE_EXTENT, bno, &raw_key);
769 raw_val.len_and_kind = cpu_to_le64(kind | blkcnt);
770 raw_val.owning_obj_id = cpu_to_le64(dstream_id);
771 raw_val.refcnt = cpu_to_le32(1);
772 return apfs_btree_replace(query, &raw_key, sizeof(raw_key), &raw_val, sizeof(raw_val));
773 }
774
775 static int apfs_insert_new_phys_extent(struct apfs_query *query, u64 bno, u64 blkcnt, u64 dstream_id)
776 {
777 struct apfs_phys_ext_key raw_key;
778 struct apfs_phys_ext_val raw_val;
779 u64 kind = (u64)APFS_KIND_NEW << APFS_PEXT_KIND_SHIFT;
780
781 apfs_key_set_hdr(APFS_TYPE_EXTENT, bno, &raw_key);
782 raw_val.len_and_kind = cpu_to_le64(kind | blkcnt);
783 raw_val.owning_obj_id = cpu_to_le64(dstream_id);
784 raw_val.refcnt = cpu_to_le32(1);
785 return apfs_btree_insert(query, &raw_key, sizeof(raw_key), &raw_val, sizeof(raw_val));
786 }
787
788 static int apfs_phys_ext_from_query(struct apfs_query *query, struct apfs_phys_extent *pext);
789
790 /**
791 * apfs_insert_phys_extent - Create or grow the physical record for an extent
792 * @dstream: data stream info for the extent
793 * @extent: new in-memory file extent
794 *
795 * Only works for appending to extents, for now. TODO: reference counting.
796 * Returns 0 on success or a negative error code in case of failure.
797 */
798 static int apfs_insert_phys_extent(struct apfs_dstream_info *dstream, const struct apfs_file_extent *extent)
799 {
800 struct super_block *sb = dstream->ds_sb;
801 struct apfs_superblock *vsb_raw = APFS_SB(sb)->s_vsb_raw;
802 struct apfs_node *extref_root;
803 struct apfs_query *query = NULL;
804 struct apfs_phys_extent pext;
805 u64 blkcnt = extent->len >> sb->s_blocksize_bits;
806 u64 last_bno, new_base, new_blkcnt;
807 int ret;
808
809 extref_root = apfs_read_node(sb,
810 le64_to_cpu(vsb_raw->apfs_extentref_tree_oid),
811 APFS_OBJ_PHYSICAL, true /* write */);
812 if (IS_ERR(extref_root)) {
813 apfs_err(sb, "failed to read extref root 0x%llx", le64_to_cpu(vsb_raw->apfs_extentref_tree_oid));
814 return PTR_ERR(extref_root);
815 }
816 apfs_assert_in_transaction(sb, &vsb_raw->apfs_o);
817 vsb_raw->apfs_extentref_tree_oid = cpu_to_le64(extref_root->object.oid);
818
819 query = apfs_alloc_query(extref_root, NULL /* parent */);
820 if (!query) {
821 ret = -ENOMEM;
822 goto out;
823 }
824
825 /*
826 * The cached logical extent may have been split into multiple physical
827 * extents because of clones. If that happens, we want to grow the last
828 * one.
829 */
830 last_bno = extent->phys_block_num + blkcnt - 1;
831 apfs_init_extent_key(last_bno, &query->key);
832 query->flags = APFS_QUERY_EXTENTREF;
833
834 ret = apfs_btree_query(sb, &query);
835 if (ret && ret != -ENODATA) {
836 apfs_err(sb, "query failed for paddr 0x%llx", last_bno);
837 goto out;
838 }
839
840 if (ret == -ENODATA) {
841 /* This is a fresh new physical extent */
842 ret = apfs_insert_new_phys_extent(query, extent->phys_block_num, blkcnt, dstream->ds_id);
843 if (ret)
844 apfs_err(sb, "insertion failed for paddr 0x%llx", extent->phys_block_num);
845 goto out;
846 }
847
848 ret = apfs_phys_ext_from_query(query, &pext);
849 if (ret) {
850 apfs_err(sb, "bad pext record for bno 0x%llx", last_bno);
851 goto out;
852 }
853 if (pext.bno + pext.blkcount <= extent->phys_block_num) {
854 /* Also a fresh new physical extent */
855 ret = apfs_insert_new_phys_extent(query, extent->phys_block_num, blkcnt, dstream->ds_id);
856 if (ret)
857 apfs_err(sb, "insertion failed for paddr 0x%llx", extent->phys_block_num);
858 goto out;
859 }
860
861 /*
862 * There is an existing physical extent that overlaps the new one. The
863 * cache was dirty, so the existing extent can't cover the whole tail.
864 */
865 if (pext.bno + pext.blkcount >= extent->phys_block_num + blkcnt) {
866 apfs_err(sb, "dirty cache tail covered by existing physical extent 0x%llx-0x%llx", pext.bno, pext.blkcount);
867 ret = -EFSCORRUPTED;
868 goto out;
869 }
870 if (pext.refcnt == 1) {
871 new_base = pext.bno;
872 new_blkcnt = extent->phys_block_num + blkcnt - new_base;
873 ret = apfs_extend_phys_extent(query, new_base, new_blkcnt, dstream->ds_id);
874 if (ret)
875 apfs_err(sb, "update failed for paddr 0x%llx", new_base);
876 } else {
877 /*
878 * We can't extend this one, because it would extend the other
879 * references as well.
880 */
881 new_base = pext.bno + pext.blkcount;
882 new_blkcnt = extent->phys_block_num + blkcnt - new_base;
883 ret = apfs_insert_new_phys_extent(query, new_base, new_blkcnt, dstream->ds_id);
884 if (ret)
885 apfs_err(sb, "insertion failed for paddr 0x%llx", new_base);
886 }
887
888 out:
889 apfs_free_query(query);
890 apfs_node_free(extref_root);
891 return ret;
892 }
893
894 /**
895 * apfs_phys_ext_from_query - Read the physical extent record found by a query
896 * @query: the (successful) query that found the record
897 * @pext: on return, the physical extent read
898 *
899 * Reads the physical extent record into @pext and performs some basic sanity
900 * checks as a protection against crafted filesystems. Returns 0 on success or
901 * -EFSCORRUPTED otherwise.
902 */
903 static int apfs_phys_ext_from_query(struct apfs_query *query, struct apfs_phys_extent *pext)
904 {
905 struct super_block *sb = query->node->object.sb;
906 struct apfs_phys_ext_key *key;
907 struct apfs_phys_ext_val *val;
908 char *raw = query->node->object.data;
909
910 if (query->len != sizeof(*val) || query->key_len != sizeof(*key)) {
911 apfs_err(sb, "bad length of key (%d) or value (%d)", query->key_len, query->len);
912 return -EFSCORRUPTED;
913 }
914
915 key = (struct apfs_phys_ext_key *)(raw + query->key_off);
916 val = (struct apfs_phys_ext_val *)(raw + query->off);
917
918 pext->bno = apfs_cat_cnid(&key->hdr);
919 pext->blkcount = le64_to_cpu(val->len_and_kind) & APFS_PEXT_LEN_MASK;
920 pext->len = pext->blkcount << sb->s_blocksize_bits;
921 pext->refcnt = le32_to_cpu(val->refcnt);
922 pext->kind = le64_to_cpu(val->len_and_kind) >> APFS_PEXT_KIND_SHIFT;
923 return 0;
924 }
925
926 /**
927 * apfs_free_phys_ext - Add all blocks in a physical extent to the free queue
928 * @sb: superblock structure
929 * @pext: physical range to free
930 *
931 * Returns 0 on success or a negative error code in case of failure.
932 */
933 static int apfs_free_phys_ext(struct super_block *sb, struct apfs_phys_extent *pext)
934 {
935 struct apfs_superblock *vsb_raw = APFS_SB(sb)->s_vsb_raw;
936
937 apfs_assert_in_transaction(sb, &vsb_raw->apfs_o);
938 le64_add_cpu(&vsb_raw->apfs_fs_alloc_count, -pext->blkcount);
939 le64_add_cpu(&vsb_raw->apfs_total_blocks_freed, pext->blkcount);
940
941 return apfs_free_queue_insert(sb, pext->bno, pext->blkcount);
942 }
943
944 /**
945 * apfs_put_phys_extent - Reduce the reference count for a physical extent
946 * @pext: physical extent data, already read
947 * @query: query that found the extent
948 *
949 * Returns 0 on success or a negative error code in case of failure.
950 */
951 static int apfs_put_phys_extent(struct apfs_phys_extent *pext, struct apfs_query *query)
952 {
953 struct super_block *sb = query->node->object.sb;
954 struct apfs_phys_ext_val *val;
955 void *raw;
956 int err;
957
958 if (--pext->refcnt == 0) {
959 err = apfs_btree_remove(query);
960 if (err) {
961 apfs_err(sb, "removal failed for paddr 0x%llx", pext->bno);
962 return err;
963 }
964 return pext->kind == APFS_KIND_NEW ? apfs_free_phys_ext(sb, pext) : 0;
965 }
966
967 err = apfs_query_join_transaction(query);
968 if (err) {
969 apfs_err(sb, "query join failed");
970 return err;
971 }
972 raw = query->node->object.data;
973 val = raw + query->off;
974 val->refcnt = cpu_to_le32(pext->refcnt);
975 return 0;
976 }
977
978 /**
979 * apfs_take_phys_extent - Increase the reference count for a physical extent
980 * @pext: physical extent data, already read
981 * @query: query that found the extent
982 *
983 * Returns 0 on success or a negative error code in case of failure.
984 */
985 static int apfs_take_phys_extent(struct apfs_phys_extent *pext, struct apfs_query *query)
986 {
987 struct super_block *sb = query->node->object.sb;
988 struct apfs_phys_ext_val *val;
989 void *raw;
990 int err;
991
992 /* An update extent may be dropped when a reference is taken */
993 if (++pext->refcnt == 0)
994 return apfs_btree_remove(query);
995
996 err = apfs_query_join_transaction(query);
997 if (err) {
998 apfs_err(sb, "query join failed");
999 return err;
1000 }
1001 raw = query->node->object.data;
1002 val = raw + query->off;
1003 val->refcnt = cpu_to_le32(pext->refcnt);
1004 return 0;
1005 }
1006
1007 /**
1008 * apfs_set_phys_ext_length - Set new length in a physical extent record's value
1009 * @pext: the physical extent record's value
1010 * @len: the new length (in blocks)
1011 *
1012 * Preserves the kind, though I doubt that's the right thing to do in general.
1013 */
1014 static inline void apfs_set_phys_ext_length(struct apfs_phys_ext_val *pext, u64 len)
1015 {
1016 u64 len_and_kind = le64_to_cpu(pext->len_and_kind);
1017 u64 kind = len_and_kind & APFS_PEXT_KIND_MASK;
1018
1019 pext->len_and_kind = cpu_to_le64(kind | len);
1020 }
1021
1022 /**
1023 * apfs_split_phys_ext - Break a physical extent in two
1024 * @query: query pointing to the extent
1025 * @div: first physical block number to come after the division
1026 *
1027 * Returns 0 on success or a negative error code in case of failure.
1028 */
1029 static int apfs_split_phys_ext(struct apfs_query *query, u64 div)
1030 {
1031 struct super_block *sb = query->node->object.sb;
1032 struct apfs_phys_ext_val *val1;
1033 struct apfs_phys_ext_key key2;
1034 struct apfs_phys_ext_val val2;
1035 struct apfs_phys_extent pextent;
1036 u64 blkcount1, blkcount2;
1037 void *raw;
1038 int err = 0;
1039
1040 err = apfs_query_join_transaction(query);
1041 if (err) {
1042 apfs_err(sb, "query join failed");
1043 return err;
1044 }
1045 raw = query->node->object.data;
1046
1047 err = apfs_phys_ext_from_query(query, &pextent);
1048 if (err) {
1049 apfs_err(sb, "bad pext record over div 0x%llx", div);
1050 return err;
1051 }
1052 val1 = raw + query->off;
1053 val2 = *(struct apfs_phys_ext_val *)(raw + query->off);
1054 key2 = *(struct apfs_phys_ext_key *)(raw + query->key_off);
1055
1056 blkcount1 = div - pextent.bno;
1057 blkcount2 = pextent.blkcount - blkcount1;
1058
1059 /* Modify the current extent in place to become the first half */
1060 apfs_set_phys_ext_length(val1, blkcount1);
1061
1062 /* Insert the second half right after the first */
1063 apfs_key_set_hdr(APFS_TYPE_EXTENT, div, &key2);
1064 apfs_set_phys_ext_length(&val2, blkcount2);
1065 return apfs_btree_insert(query, &key2, sizeof(key2), &val2, sizeof(val2));
1066 }
1067
1068 /**
1069 * apfs_create_update_pext - Create a reference update physical extent record
1070 * @query: query that searched for the physical extent
1071 * @extent: range of physical blocks to update
1072 * @diff: reference count change
1073 *
1074 * Returns 0 on success or a negative error code in case of failure.
1075 */
1076 static int apfs_create_update_pext(struct apfs_query *query, const struct apfs_file_extent *extent, u32 diff)
1077 {
1078 struct super_block *sb = query->node->object.sb;
1079 struct apfs_phys_ext_key key = {0};
1080 struct apfs_phys_ext_val val = {0};
1081
1082 apfs_key_set_hdr(APFS_TYPE_EXTENT, extent->phys_block_num, &key);
1083 val.len_and_kind = cpu_to_le64((u64)APFS_KIND_UPDATE << APFS_PEXT_KIND_SHIFT | extent->len >> sb->s_blocksize_bits);
1084 val.owning_obj_id = cpu_to_le64(APFS_OWNING_OBJ_ID_INVALID);
1085 val.refcnt = cpu_to_le32(diff);
1086 return apfs_btree_insert(query, &key, sizeof(key), &val, sizeof(val));
1087 }
1088
1089 /**
1090 * apfs_dstream_cache_is_tail - Is the tail of this dstream in its extent cache?
1091 * @dstream: dstream to check
1092 */
1093 static inline bool apfs_dstream_cache_is_tail(struct apfs_dstream_info *dstream)
1094 {
1095 struct apfs_file_extent *cache = &dstream->ds_cached_ext;
1096
1097 /* nx_big_sem provides the locking for the cache here */
1098 return cache->len && (dstream->ds_size <= cache->logical_addr + cache->len);
1099 }
1100
1101 /**
1102 * apfs_flush_extent_cache - Write the cached extent to the catalog, if dirty
1103 * @dstream: data stream to flush
1104 *
1105 * Returns 0 on success or a negative error code in case of failure.
1106 */
1107 int apfs_flush_extent_cache(struct apfs_dstream_info *dstream)
1108 {
1109 struct super_block *sb = dstream->ds_sb;
1110 struct apfs_file_extent *ext = &dstream->ds_cached_ext;
1111 int err;
1112
1113 if (!dstream->ds_ext_dirty)
1114 return 0;
1115 ASSERT(ext->len > 0);
1116
1117 err = apfs_update_extent(dstream, ext);
1118 if (err) {
1119 apfs_err(sb, "extent update failed");
1120 return err;
1121 }
1122 err = apfs_insert_phys_extent(dstream, ext);
1123 if (err) {
1124 apfs_err(sb, "pext insertion failed");
1125 return err;
1126 }
1127
1128 /*
1129 * TODO: keep track of the byte and block count through the use of
1130 * inode_add_bytes() and inode_set_bytes(). This hasn't been done with
1131 * care in the rest of the module and it doesn't seem to matter beyond
1132 * stat(), so I'm ignoring it for now.
1133 */
1134
1135 dstream->ds_ext_dirty = false;
1136 return 0;
1137 }
1138
1139 /**
1140 * apfs_create_hole - Create and insert a hole extent for the dstream
1141 * @dstream: data stream info
1142 * @start: first logical block number for the hole
1143 * @end: first logical block number right after the hole
1144 *
1145 * Returns 0 on success, or a negative error code in case of failure.
1146 * TODO: what happens to the crypto refcount?
1147 */
1148 static int apfs_create_hole(struct apfs_dstream_info *dstream, u64 start, u64 end)
1149 {
1150 struct super_block *sb = dstream->ds_sb;
1151 struct apfs_sb_info *sbi = APFS_SB(sb);
1152 struct apfs_query *query;
1153 struct apfs_file_extent_key raw_key;
1154 struct apfs_file_extent_val raw_val;
1155 u64 extent_id = dstream->ds_id;
1156 int ret;
1157
1158 if (start == end)
1159 return 0;
1160
1161 /* File extent records use addresses, not block numbers */
1162 start <<= sb->s_blocksize_bits;
1163 end <<= sb->s_blocksize_bits;
1164
1165 apfs_key_set_hdr(APFS_TYPE_FILE_EXTENT, extent_id, &raw_key);
1166 raw_key.logical_addr = cpu_to_le64(start);
1167 raw_val.len_and_flags = cpu_to_le64(end - start);
1168 raw_val.phys_block_num = cpu_to_le64(0); /* It's a hole... */
1169 raw_val.crypto_id = cpu_to_le64(apfs_vol_is_encrypted(sb) ? extent_id : 0);
1170
1171 query = apfs_alloc_query(sbi->s_cat_root, NULL /* parent */);
1172 if (!query)
1173 return -ENOMEM;
1174 apfs_init_file_extent_key(extent_id, start, &query->key);
1175 query->flags = APFS_QUERY_CAT;
1176
1177 ret = apfs_btree_query(sb, &query);
1178 if (ret && ret != -ENODATA) {
1179 apfs_err(sb, "query failed for id 0x%llx, addr 0x%llx", extent_id, start);
1180 goto out;
1181 }
1182
1183 ret = apfs_btree_insert(query, &raw_key, sizeof(raw_key), &raw_val, sizeof(raw_val));
1184 if (ret)
1185 apfs_err(sb, "insertion failed for id 0x%llx, addr 0x%llx", extent_id, start);
1186 dstream->ds_sparse_bytes += end - start;
1187
1188 out:
1189 apfs_free_query(query);
1190 return ret;
1191 }
1192
1193 /**
1194 * apfs_zero_dstream_tail - Zero out stale bytes in a data stream's last block
1195 * @dstream: data stream info
1196 *
1197 * Returns 0 on success, or a negative error code in case of failure.
1198 */
1199 static int apfs_zero_dstream_tail(struct apfs_dstream_info *dstream)
1200 {
1201 struct super_block *sb = dstream->ds_sb;
1202 struct inode *inode = NULL;
1203 struct page *page = NULL;
1204 void *fsdata = NULL;
1205 int valid_length;
1206 int err;
1207
1208 /* No stale bytes if no actual content */
1209 if (dstream->ds_size <= dstream->ds_sparse_bytes)
1210 return 0;
1211
1212 /* No stale tail if the last block is fully used */
1213 valid_length = dstream->ds_size & (sb->s_blocksize - 1);
1214 if (valid_length == 0)
1215 return 0;
1216
1217 inode = dstream->ds_inode;
1218 if (!inode) {
1219 /* This should never happen, but be safe */
1220 apfs_alert(sb, "attempt to zero the tail of xattr dstream 0x%llx", dstream->ds_id);
1221 return -EFSCORRUPTED;
1222 }
1223
1224 /* This will take care of the CoW and zeroing */
1225 err = __apfs_write_begin(NULL, inode->i_mapping, inode->i_size, 0, 0, &page, &fsdata);
1226 if (err)
1227 return err;
1228 return __apfs_write_end(NULL, inode->i_mapping, inode->i_size, 0, 0, page, fsdata);
1229 }
1230
1231 /**
1232 * apfs_zero_bh_tail - Zero out stale bytes in a buffer head
1233 * @sb: filesystem superblock
1234 * @bh: buffer head to zero
1235 * @length: length of valid bytes to be left alone
1236 */
1237 static void apfs_zero_bh_tail(struct super_block *sb, struct buffer_head *bh, u64 length)
1238 {
1239 ASSERT(buffer_trans(bh));
1240 if (length < sb->s_blocksize)
1241 memset(bh->b_data + length, 0, sb->s_blocksize - length);
1242 }
1243
1244 /**
1245 * apfs_range_in_snap - Check if a given block range overlaps a snapshot
1246 * @sb: filesystem superblock
1247 * @bno: first block in the range
1248 * @blkcnt: block count for the range
1249 * @in_snap: on return, the result
1250 *
1251 * Returns 0 on success, or a negative error code in case of failure.
1252 */
1253 static int apfs_range_in_snap(struct super_block *sb, u64 bno, u64 blkcnt, bool *in_snap)
1254 {
1255 struct apfs_superblock *vsb_raw = APFS_SB(sb)->s_vsb_raw;
1256 struct apfs_node *extref_root = NULL;
1257 struct apfs_query *query = NULL;
1258 struct apfs_phys_extent pext = {0};
1259 int ret;
1260
1261 /* Avoid the tree queries when we don't even have snapshots */
1262 if (vsb_raw->apfs_num_snapshots == 0) {
1263 *in_snap = false;
1264 return 0;
1265 }
1266
1267 /*
1268 * Now check if the current physical extent tree has an entry for
1269 * these blocks
1270 */
1271 extref_root = apfs_read_node(sb, le64_to_cpu(vsb_raw->apfs_extentref_tree_oid), APFS_OBJ_PHYSICAL, false /* write */);
1272 if (IS_ERR(extref_root)) {
1273 apfs_err(sb, "failed to read extref root 0x%llx", le64_to_cpu(vsb_raw->apfs_extentref_tree_oid));
1274 return PTR_ERR(extref_root);
1275 }
1276
1277 query = apfs_alloc_query(extref_root, NULL /* parent */);
1278 if (!query) {
1279 ret = -ENOMEM;
1280 goto out;
1281 }
1282
1283 apfs_init_extent_key(bno, &query->key);
1284 query->flags = APFS_QUERY_EXTENTREF;
1285
1286 ret = apfs_btree_query(sb, &query);
1287 if (ret && ret != -ENODATA) {
1288 apfs_err(sb, "query failed for paddr 0x%llx", bno);
1289 goto out;
1290 }
1291 if (ret == -ENODATA) {
1292 *in_snap = false;
1293 ret = 0;
1294 goto out;
1295 }
1296
1297 ret = apfs_phys_ext_from_query(query, &pext);
1298 if (ret) {
1299 apfs_err(sb, "bad pext record for paddr 0x%llx", bno);
1300 goto out;
1301 }
1302
1303 if (pext.bno <= bno && pext.bno + pext.blkcount >= bno + blkcnt) {
1304 if (pext.kind == APFS_KIND_NEW) {
1305 *in_snap = false;
1306 goto out;
1307 }
1308 }
1309
1310 /*
1311 * I think the file extent could still be covered by two different
1312 * physical extents from the current tree, but it's easier to just
1313 * assume the worst here.
1314 */
1315 *in_snap = true;
1316
1317 out:
1318 apfs_free_query(query);
1319 apfs_node_free(extref_root);
1320 return ret;
1321 }
1322
1323 /**
1324 * apfs_dstream_cache_in_snap - Check if the cached extent overlaps a snapshot
1325 * @dstream: the data stream to check
1326 * @in_snap: on return, the result
1327 *
1328 * Returns 0 on success, or a negative error code in case of failure.
1329 */
1330 static int apfs_dstream_cache_in_snap(struct apfs_dstream_info *dstream, bool *in_snap)
1331 {
1332 struct super_block *sb = dstream->ds_sb;
1333 struct apfs_file_extent *cache = NULL;
1334
1335 /* All changes to extents get flushed when a snaphot is created */
1336 if (dstream->ds_ext_dirty) {
1337 *in_snap = false;
1338 return 0;
1339 }
1340
1341 cache = &dstream->ds_cached_ext;
1342 return apfs_range_in_snap(sb, cache->phys_block_num, cache->len >> sb->s_blocksize_bits, in_snap);
1343 }
1344
1345 /**
1346 * apfs_dstream_get_new_block - Like the get_block_t function, but for dstreams
1347 * @dstream: data stream info
1348 * @dsblock: logical dstream block to map
1349 * @bh_result: buffer head to map (NULL if none)
1350 * @bno: if not NULL, the new block number is returned here
1351 *
1352 * Returns 0 on success, or a negative error code in case of failure.
1353 */
1354 static int apfs_dstream_get_new_block(struct apfs_dstream_info *dstream, u64 dsblock, struct buffer_head *bh_result, u64 *bno)
1355 {
1356 struct super_block *sb = dstream->ds_sb;
1357 struct apfs_superblock *vsb_raw = APFS_SB(sb)->s_vsb_raw;
1358 struct apfs_file_extent *cache = NULL;
1359 u64 phys_bno, logical_addr, cache_blks, dstream_blks;
1360 bool in_snap = true;
1361 int err;
1362
1363 /* TODO: preallocate tail blocks */
1364 logical_addr = dsblock << sb->s_blocksize_bits;
1365
1366 err = apfs_spaceman_allocate_block(sb, &phys_bno, false /* backwards */);
1367 if (err) {
1368 apfs_err(sb, "block allocation failed");
1369 return err;
1370 }
1371 apfs_assert_in_transaction(sb, &vsb_raw->apfs_o);
1372 le64_add_cpu(&vsb_raw->apfs_fs_alloc_count, 1);
1373 le64_add_cpu(&vsb_raw->apfs_total_blocks_alloced, 1);
1374 if (bno)
1375 *bno = phys_bno;
1376
1377 if (bh_result) {
1378 apfs_map_bh(bh_result, sb, phys_bno);
1379 err = apfs_transaction_join(sb, bh_result);
1380 if (err)
1381 return err;
1382
1383 if (!buffer_uptodate(bh_result)) {
1384 /*
1385 * Truly new buffers need to be marked as such, to get
1386 * zeroed; this also takes care of holes in sparse files
1387 */
1388 set_buffer_new(bh_result);
1389 } else if (dstream->ds_size > logical_addr) {
1390 /*
1391 * The last block may have stale data left from a
1392 * truncation
1393 */
1394 apfs_zero_bh_tail(sb, bh_result, dstream->ds_size - logical_addr);
1395 }
1396 }
1397
1398 dstream_blks = apfs_size_to_blocks(sb, dstream->ds_size);
1399 if (dstream_blks < dsblock) {
1400 /*
1401 * This recurses into apfs_dstream_get_new_block() and dirties
1402 * the extent cache, so it must happen before flushing it.
1403 */
1404 err = apfs_zero_dstream_tail(dstream);
1405 if (err) {
1406 apfs_err(sb, "failed to zero tail for dstream 0x%llx", dstream->ds_id);
1407 return err;
1408 }
1409 }
1410
1411 err = apfs_dstream_cache_in_snap(dstream, &in_snap);
1412 if (err)
1413 return err;
1414
1415 cache = &dstream->ds_cached_ext;
1416 cache_blks = apfs_size_to_blocks(sb, cache->len);
1417
1418 /* TODO: allow dirty caches of several blocks in the middle of a file */
1419 if (!in_snap && apfs_dstream_cache_is_tail(dstream) &&
1420 logical_addr == cache->logical_addr + cache->len &&
1421 phys_bno == cache->phys_block_num + cache_blks) {
1422 cache->len += sb->s_blocksize;
1423 dstream->ds_ext_dirty = true;
1424 return 0;
1425 }
1426
1427 err = apfs_flush_extent_cache(dstream);
1428 if (err) {
1429 apfs_err(sb, "extent cache flush failed for dstream 0x%llx", dstream->ds_id);
1430 return err;
1431 }
1432
1433 if (dstream_blks < dsblock) {
1434 /*
1435 * This puts new extents after the reported end of the file, so
1436 * it must happen after the flush to avoid conflict with those
1437 * extent operations.
1438 */
1439 err = apfs_create_hole(dstream, dstream_blks, dsblock);
1440 if (err) {
1441 apfs_err(sb, "hole creation failed for dstream 0x%llx", dstream->ds_id);
1442 return err;
1443 }
1444 }
1445
1446 cache->logical_addr = logical_addr;
1447 cache->phys_block_num = phys_bno;
1448 cache->len = sb->s_blocksize;
1449 dstream->ds_ext_dirty = true;
1450 return 0;
1451 }
1452
1453 /**
1454 * apfs_dstream_get_new_bno - Allocate a new block inside a dstream
1455 * @dstream: data stream info
1456 * @dsblock: logical dstream block to allocate
1457 * @bno: on return, the new block number
1458 *
1459 * Returns 0 on success, or a negative error code in case of failure.
1460 */
1461 int apfs_dstream_get_new_bno(struct apfs_dstream_info *dstream, u64 dsblock, u64 *bno)
1462 {
1463 return apfs_dstream_get_new_block(dstream, dsblock, NULL /* bh_result */, bno);
1464 }
1465
1466 int apfs_get_new_block(struct inode *inode, sector_t iblock,
1467 struct buffer_head *bh_result, int create)
1468 {
1469 struct apfs_inode_info *ai = APFS_I(inode);
1470
1471 ASSERT(create);
1472 return apfs_dstream_get_new_block(&ai->i_dstream, iblock, bh_result, NULL /* bno */);
1473 }
1474
1475 /**
1476 * apfs_shrink_dstream_last_extent - Shrink last extent of dstream being resized
1477 * @dstream: data stream info
1478 * @new_size: new size for the whole data stream
1479 *
1480 * Deletes, shrinks or zeroes the last extent, as needed for the truncation of
1481 * the data stream.
1482 *
1483 * Only works with the last extent, so it needs to be called repeatedly to
1484 * complete the truncation. Returns -EAGAIN in that case, or 0 when the process
1485 * is complete. Returns other negative error codes in case of failure.
1486 */
1487 static int apfs_shrink_dstream_last_extent(struct apfs_dstream_info *dstream, loff_t new_size)
1488 {
1489 struct super_block *sb = dstream->ds_sb;
1490 struct apfs_sb_info *sbi = APFS_SB(sb);
1491 struct apfs_query *query;
1492 struct apfs_file_extent tail;
1493 u64 extent_id = dstream->ds_id;
1494 int ret = 0;
1495
1496 query = apfs_alloc_query(sbi->s_cat_root, NULL /* parent */);
1497 if (!query)
1498 return -ENOMEM;
1499 apfs_init_file_extent_key(extent_id, -1, &query->key);
1500 query->flags = APFS_QUERY_CAT;
1501
1502 ret = apfs_btree_query(sb, &query);
1503 if (ret && ret != -ENODATA) {
1504 apfs_err(sb, "query failed for last extent of id 0x%llx", extent_id);
1505 goto out;
1506 }
1507
1508 if (!apfs_query_found_extent(query)) {
1509 /* No more extents, we deleted the whole file already? */
1510 if (new_size) {
1511 apfs_err(sb, "missing extent for dstream 0x%llx", extent_id);
1512 ret = -EFSCORRUPTED;
1513 } else {
1514 ret = 0;
1515 }
1516 goto out;
1517 }
1518
1519 ret = apfs_extent_from_query(query, &tail);
1520 if (ret) {
1521 apfs_err(sb, "bad tail extent record on dstream 0x%llx", extent_id);
1522 goto out;
1523 }
1524
1525 if (tail.logical_addr + tail.len < new_size) {
1526 apfs_err(sb, "missing extent for dstream 0x%llx", extent_id);
1527 ret = -EFSCORRUPTED; /* Tail extent missing */
1528 } else if (tail.logical_addr + tail.len == new_size) {
1529 ret = 0; /* Nothing more to be done */
1530 } else if (tail.logical_addr >= new_size) {
1531 /* This whole extent needs to go */
1532 ret = apfs_btree_remove(query);
1533 if (ret) {
1534 apfs_err(sb, "removal failed for id 0x%llx, addr 0x%llx", dstream->ds_id, tail.logical_addr);
1535 goto out;
1536 }
1537 if (apfs_ext_is_hole(&tail)) {
1538 dstream->ds_sparse_bytes -= tail.len;
1539 } else {
1540 ret = apfs_range_put_reference(sb, tail.phys_block_num, tail.len);
1541 if (ret) {
1542 apfs_err(sb, "failed to put range 0x%llx-0x%llx", tail.phys_block_num, tail.len);
1543 goto out;
1544 }
1545 }
1546 ret = apfs_crypto_adj_refcnt(sb, tail.crypto_id, -1);
1547 if (ret) {
1548 apfs_err(sb, "failed to take crypto id 0x%llx", tail.crypto_id);
1549 goto out;
1550 }
1551 ret = tail.logical_addr == new_size ? 0 : -EAGAIN;
1552 } else {
1553 /*
1554 * The file is being truncated in the middle of this extent.
1555 * TODO: preserve the physical tail to be overwritten later.
1556 */
1557 new_size = apfs_size_to_blocks(sb, new_size) << sb->s_blocksize_bits;
1558 ret = apfs_shrink_extent_tail(query, dstream, new_size);
1559 if (ret)
1560 apfs_err(sb, "failed to shrink tail of dstream 0x%llx", extent_id);
1561 }
1562
1563 out:
1564 apfs_free_query(query);
1565 return ret;
1566 }
1567
1568 /**
1569 * apfs_shrink_dstream - Shrink a data stream's extents to a new length
1570 * @dstream: data stream info
1571 * @new_size: the new size
1572 *
1573 * Returns 0 on success, or a negative error code in case of failure.
1574 */
1575 static int apfs_shrink_dstream(struct apfs_dstream_info *dstream, loff_t new_size)
1576 {
1577 int ret;
1578
1579 do {
1580 ret = apfs_shrink_dstream_last_extent(dstream, new_size);
1581 } while (ret == -EAGAIN);
1582
1583 return ret;
1584 }
1585
1586 /**
1587 * apfs_truncate - Truncate a data stream's content
1588 * @dstream: data stream info
1589 * @new_size: the new size
1590 *
1591 * Returns 0 on success, or a negative error code in case of failure.
1592 */
1593 int apfs_truncate(struct apfs_dstream_info *dstream, loff_t new_size)
1594 {
1595 struct super_block *sb = dstream->ds_sb;
1596 u64 old_blks, new_blks;
1597 struct apfs_file_extent *cache = &dstream->ds_cached_ext;
1598 int err;
1599
1600 /* TODO: don't write the cached extent if it will be deleted */
1601 err = apfs_flush_extent_cache(dstream);
1602 if (err) {
1603 apfs_err(sb, "extent cache flush failed for dstream 0x%llx", dstream->ds_id);
1604 return err;
1605 }
1606 dstream->ds_ext_dirty = false;
1607
1608 /* TODO: keep the cache valid on truncation */
1609 cache->len = 0;
1610
1611 /* "<=", because a partial write may have left extents beyond the end */
1612 if (new_size <= dstream->ds_size)
1613 return apfs_shrink_dstream(dstream, new_size);
1614
1615 err = apfs_zero_dstream_tail(dstream);
1616 if (err) {
1617 apfs_err(sb, "failed to zero tail for dstream 0x%llx", dstream->ds_id);
1618 return err;
1619 }
1620 new_blks = apfs_size_to_blocks(sb, new_size);
1621 old_blks = apfs_size_to_blocks(sb, dstream->ds_size);
1622 return apfs_create_hole(dstream, old_blks, new_blks);
1623 }
1624
1625 /**
1626 * apfs_dstream_delete_front - Deletes as many leading extents as possible
1627 * @sb: filesystem superblock
1628 * @ds_id: id for the dstream to delete
1629 *
1630 * Returns 0 on success, or a negative error code in case of failure, which may
1631 * be -ENODATA if there are no more extents, or -EAGAIN if the free queue is
1632 * getting too full.
1633 */
1634 static int apfs_dstream_delete_front(struct super_block *sb, u64 ds_id)
1635 {
1636 struct apfs_sb_info *sbi = APFS_SB(sb);
1637 struct apfs_spaceman *sm = APFS_SM(sb);
1638 struct apfs_spaceman_phys *sm_raw = sm->sm_raw;
1639 struct apfs_spaceman_free_queue *fq = NULL;
1640 struct apfs_query *query = NULL;
1641 struct apfs_file_extent head;
1642 bool first_match = true;
1643 int ret;
1644
1645 fq = &sm_raw->sm_fq[APFS_SFQ_MAIN];
1646 if (le64_to_cpu(fq->sfq_count) > APFS_TRANS_MAIN_QUEUE_MAX)
1647 return -EAGAIN;
1648
1649 query = apfs_alloc_query(sbi->s_cat_root, NULL /* parent */);
1650 if (!query)
1651 return -ENOMEM;
1652 apfs_init_file_extent_key(ds_id, 0, &query->key);
1653 query->flags = APFS_QUERY_CAT;
1654
1655 next_extent:
1656 ret = apfs_btree_query(sb, &query);
1657 if (ret && ret != -ENODATA) {
1658 apfs_err(sb, "query failed for first extent of id 0x%llx", ds_id);
1659 goto out;
1660 }
1661 apfs_query_direct_forward(query);
1662 if (!apfs_query_found_extent(query)) {
1663 /*
1664 * After the original lookup, the query may not be set to the
1665 * first extent, but instead to the record that comes right
1666 * before.
1667 */
1668 if (first_match) {
1669 first_match = false;
1670 goto next_extent;
1671 }
1672 ret = -ENODATA;
1673 goto out;
1674 }
1675 first_match = false;
1676
1677 ret = apfs_extent_from_query(query, &head);
1678 if (ret) {
1679 apfs_err(sb, "bad head extent record on dstream 0x%llx", ds_id);
1680 goto out;
1681 }
1682 ret = apfs_btree_remove(query);
1683 if (ret) {
1684 apfs_err(sb, "removal failed for id 0x%llx, addr 0x%llx", ds_id, head.logical_addr);
1685 goto out;
1686 }
1687
1688 /*
1689 * The official fsck doesn't complain about wrong sparse byte counts
1690 * for orphans, so I guess we don't need to update them here
1691 */
1692 if (!apfs_ext_is_hole(&head)) {
1693 ret = apfs_range_put_reference(sb, head.phys_block_num, head.len);
1694 if (ret) {
1695 apfs_err(sb, "failed to put range 0x%llx-0x%llx", head.phys_block_num, head.len);
1696 goto out;
1697 }
1698 ret = apfs_crypto_adj_refcnt(sb, head.crypto_id, -1);
1699 if (ret) {
1700 apfs_err(sb, "failed to take crypto id 0x%llx", head.crypto_id);
1701 goto out;
1702 }
1703 }
1704
1705 if (le64_to_cpu(fq->sfq_count) <= APFS_TRANS_MAIN_QUEUE_MAX)
1706 goto next_extent;
1707 ret = -EAGAIN;
1708 out:
1709 apfs_free_query(query);
1710 return ret;
1711 }
1712
1713 /**
1714 * apfs_inode_delete_front - Deletes as many leading extents as possible
1715 * @inode: inode to delete
1716 *
1717 * Tries to delete all extents for @inode, in which case it returns 0. If the
1718 * free queue is getting too full, deletes as much as is reasonable and returns
1719 * -EAGAIN. May return other negative error codes as well.
1720 */
1721 int apfs_inode_delete_front(struct inode *inode)
1722 {
1723 struct super_block *sb = inode->i_sb;
1724 struct apfs_dstream_info *dstream = NULL;
1725 struct apfs_inode_info *ai = APFS_I(inode);
1726 int ret;
1727
1728 if (!ai->i_has_dstream)
1729 return 0;
1730
1731 dstream = &ai->i_dstream;
1732 ret = apfs_flush_extent_cache(dstream);
1733 if (ret) {
1734 apfs_err(sb, "extent cache flush failed for dstream 0x%llx", dstream->ds_id);
1735 return ret;
1736 }
1737
1738 ret = apfs_dstream_delete_front(sb, dstream->ds_id);
1739 if (ret == -ENODATA)
1740 return 0;
1741 return ret;
1742 }
1743
1744 #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 20, 0)
1745 loff_t apfs_remap_file_range(struct file *src_file, loff_t off, struct file *dst_file, loff_t destoff, loff_t len, unsigned int remap_flags)
1746 #else
1747 int apfs_clone_file_range(struct file *src_file, loff_t off, struct file *dst_file, loff_t destoff, u64 len)
1748 #endif
1749 {
1750 struct inode *src_inode = file_inode(src_file);
1751 struct inode *dst_inode = file_inode(dst_file);
1752 struct apfs_inode_info *src_ai = APFS_I(src_inode);
1753 struct apfs_inode_info *dst_ai = APFS_I(dst_inode);
1754 struct apfs_dstream_info *src_ds = &src_ai->i_dstream;
1755 struct apfs_dstream_info *dst_ds = &dst_ai->i_dstream;
1756 struct super_block *sb = src_inode->i_sb;
1757 struct apfs_sb_info *sbi = APFS_SB(sb);
1758 const u64 xfield_flags = APFS_INODE_MAINTAIN_DIR_STATS | APFS_INODE_IS_SPARSE | APFS_INODE_HAS_PURGEABLE_FLAGS;
1759 int err;
1760
1761 #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 20, 0)
1762 if (remap_flags & ~(REMAP_FILE_ADVISORY))
1763 return -EINVAL;
1764 #endif
1765 if (src_inode == dst_inode)
1766 return -EINVAL;
1767
1768 /* We only want to clone whole files, like in the official driver */
1769 if (off != 0 || destoff != 0 || len != 0)
1770 return -EINVAL;
1771
1772 /*
1773 * Clones here work in two steps: first the user creates an empty target
1774 * file, and then the user calls the ioctl, which replaces the file with
1775 * a clone. This is not atomic, of course.
1776 */
1777 if (dst_ai->i_has_dstream || dst_ai->i_bsd_flags & APFS_INOBSD_COMPRESSED) {
1778 apfs_warn(sb, "clones can only replace freshly created files");
1779 return -EOPNOTSUPP;
1780 }
1781 if (dst_ai->i_int_flags & xfield_flags) {
1782 apfs_warn(sb, "clone can't replace a file that has xfields");
1783 return -EOPNOTSUPP;
1784 }
1785
1786 if (!src_ai->i_has_dstream) {
1787 apfs_warn(sb, "can't clone a file with no dstream");
1788 return -EOPNOTSUPP;
1789 }
1790
1791 err = apfs_transaction_start(sb, APFS_TRANS_REG);
1792 if (err)
1793 return err;
1794 apfs_inode_join_transaction(sb, src_inode);
1795 apfs_inode_join_transaction(sb, dst_inode);
1796
1797 err = apfs_flush_extent_cache(src_ds);
1798 if (err) {
1799 apfs_err(sb, "extent cache flush failed for dstream 0x%llx", src_ds->ds_id);
1800 goto fail;
1801 }
1802 err = apfs_dstream_adj_refcnt(src_ds, +1);
1803 if (err) {
1804 apfs_err(sb, "failed to take dstream id 0x%llx", src_ds->ds_id);
1805 goto fail;
1806 }
1807 src_ds->ds_shared = true;
1808
1809 #if LINUX_VERSION_CODE < KERNEL_VERSION(6, 6, 0)
1810 dst_inode->i_mtime = dst_inode->i_ctime = current_time(dst_inode);
1811 #elif LINUX_VERSION_CODE < KERNEL_VERSION(6, 7, 0)
1812 dst_inode->i_mtime = inode_set_ctime_current(dst_inode);
1813 #else
1814 inode_set_mtime_to_ts(dst_inode, inode_set_ctime_current(dst_inode));
1815 #endif
1816 dst_inode->i_size = src_inode->i_size;
1817 dst_ai->i_key_class = src_ai->i_key_class;
1818 dst_ai->i_int_flags = src_ai->i_int_flags;
1819 dst_ai->i_bsd_flags = src_ai->i_bsd_flags;
1820 dst_ai->i_has_dstream = true;
1821
1822 dst_ds->ds_sb = src_ds->ds_sb;
1823 dst_ds->ds_inode = dst_inode;
1824 dst_ds->ds_id = src_ds->ds_id;
1825 dst_ds->ds_size = src_ds->ds_size;
1826 dst_ds->ds_sparse_bytes = src_ds->ds_sparse_bytes;
1827 dst_ds->ds_cached_ext = src_ds->ds_cached_ext;
1828 dst_ds->ds_ext_dirty = false;
1829 dst_ds->ds_shared = true;
1830
1831 dst_ai->i_int_flags |= APFS_INODE_WAS_EVER_CLONED | APFS_INODE_WAS_CLONED;
1832 src_ai->i_int_flags |= APFS_INODE_WAS_EVER_CLONED;
1833
1834 /*
1835 * The sparse flag is the important one here: if we need it, it will get
1836 * set later by apfs_update_inode(), after the xfield gets created.
1837 */
1838 dst_ai->i_int_flags &= ~xfield_flags;
1839
1840 /*
1841 * Commit the transaction to make sure all buffers in the source inode
1842 * go through copy-on-write. This is a bit excessive, but I don't expect
1843 * clones to be created often enough for it to matter.
1844 */
1845 sbi->s_nxi->nx_transaction.t_state |= APFS_NX_TRANS_FORCE_COMMIT;
1846 err = apfs_transaction_commit(sb);
1847 if (err)
1848 goto fail;
1849 return dst_ds->ds_size;
1850
1851 fail:
1852 apfs_transaction_abort(sb);
1853 return err;
1854 }
1855
1856 /**
1857 * apfs_extent_create_record - Create a logical extent record for a dstream id
1858 * @sb: filesystem superblock
1859 * @dstream_id: the dstream id
1860 * @extent: extent info for the record
1861 *
1862 * Returns 0 on success, or a negative error code in case of failure.
1863 */
1864 static int apfs_extent_create_record(struct super_block *sb, u64 dstream_id, struct apfs_file_extent *extent)
1865 {
1866 struct apfs_sb_info *sbi = APFS_SB(sb);
1867 struct apfs_query *query = NULL;
1868 struct apfs_file_extent_val raw_val;
1869 struct apfs_file_extent_key raw_key;
1870 int ret = 0;
1871
1872 query = apfs_alloc_query(sbi->s_cat_root, NULL /* parent */);
1873 if (!query)
1874 return -ENOMEM;
1875 apfs_init_file_extent_key(dstream_id, extent->logical_addr, &query->key);
1876 query->flags = APFS_QUERY_CAT | APFS_QUERY_EXACT;
1877
1878 ret = apfs_btree_query(sb, &query);
1879 if (ret && ret != -ENODATA) {
1880 apfs_err(sb, "query failed for id 0x%llx, addr 0x%llx", dstream_id, extent->logical_addr);
1881 goto out;
1882 }
1883
1884 apfs_key_set_hdr(APFS_TYPE_FILE_EXTENT, dstream_id, &raw_key);
1885 raw_key.logical_addr = cpu_to_le64(extent->logical_addr);
1886 raw_val.len_and_flags = cpu_to_le64(extent->len);
1887 raw_val.phys_block_num = cpu_to_le64(extent->phys_block_num);
1888 raw_val.crypto_id = cpu_to_le64(apfs_vol_is_encrypted(sb) ? dstream_id : 0); /* TODO */
1889
1890 ret = apfs_btree_insert(query, &raw_key, sizeof(raw_key), &raw_val, sizeof(raw_val));
1891 if (ret)
1892 apfs_err(sb, "insertion failed for id 0x%llx, addr 0x%llx", dstream_id, extent->logical_addr);
1893 out:
1894 apfs_free_query(query);
1895 return ret;
1896 }
1897
1898 /**
1899 * apfs_put_single_extent - Put a reference to a single extent
1900 * @sb: filesystem superblock
1901 * @paddr_end: first block after the extent to put
1902 * @paddr_min: don't put references before this block
1903 *
1904 * Puts a reference to the physical extent range that ends in @paddr_end. Sets
1905 * @paddr_end to the beginning of the extent, so that the caller can continue
1906 * with the previous one. Returns 0 on success, or a negative error code in
1907 * case of failure.
1908 *
1909 * TODO: unify this with apfs_take_single_extent(), they are almost the same.
1910 */
1911 static int apfs_put_single_extent(struct super_block *sb, u64 *paddr_end, u64 paddr_min)
1912 {
1913 struct apfs_superblock *vsb_raw = APFS_SB(sb)->s_vsb_raw;
1914 struct apfs_node *extref_root = NULL;
1915 struct apfs_key key;
1916 struct apfs_query *query = NULL;
1917 struct apfs_phys_extent prev_ext;
1918 u64 prev_start, prev_end;
1919 bool cropped_head = false, cropped_tail = false;
1920 struct apfs_file_extent tmp = {0}; /* TODO: clean up all the fake extent interfaces? */
1921 int ret;
1922
1923 extref_root = apfs_read_node(sb, le64_to_cpu(vsb_raw->apfs_extentref_tree_oid), APFS_OBJ_PHYSICAL, true /* write */);
1924 if (IS_ERR(extref_root)) {
1925 apfs_err(sb, "failed to read extref root 0x%llx", le64_to_cpu(vsb_raw->apfs_extentref_tree_oid));
1926 return PTR_ERR(extref_root);
1927 }
1928 apfs_assert_in_transaction(sb, &vsb_raw->apfs_o);
1929 vsb_raw->apfs_extentref_tree_oid = cpu_to_le64(extref_root->object.oid);
1930
1931 apfs_init_extent_key(*paddr_end - 1, &key);
1932
1933 restart:
1934 query = apfs_alloc_query(extref_root, NULL /* parent */);
1935 if (!query) {
1936 ret = -ENOMEM;
1937 goto out;
1938 }
1939 query->key = key;
1940 query->flags = APFS_QUERY_EXTENTREF;
1941
1942 ret = apfs_btree_query(sb, &query);
1943 if (ret && ret != -ENODATA) {
1944 apfs_err(sb, "query failed for paddr 0x%llx", *paddr_end - 1);
1945 goto out;
1946 }
1947
1948 if (ret == -ENODATA) {
1949 /* The whole range to put is part of a snapshot */
1950 tmp.phys_block_num = paddr_min;
1951 tmp.len = (*paddr_end - paddr_min) << sb->s_blocksize_bits;
1952 ret = apfs_create_update_pext(query, &tmp, -1);
1953 *paddr_end = paddr_min;
1954 goto out;
1955 }
1956
1957 ret = apfs_phys_ext_from_query(query, &prev_ext);
1958 if (ret) {
1959 apfs_err(sb, "bad pext record over paddr 0x%llx", *paddr_end - 1);
1960 goto out;
1961 }
1962 prev_start = prev_ext.bno;
1963 prev_end = prev_ext.bno + prev_ext.blkcount;
1964 if (prev_end < *paddr_end) {
1965 /* The extent to put is part of a snapshot */
1966 tmp.phys_block_num = max(prev_end, paddr_min);
1967 tmp.len = (*paddr_end - tmp.phys_block_num) << sb->s_blocksize_bits;
1968 ret = apfs_create_update_pext(query, &tmp, -1);
1969 *paddr_end = tmp.phys_block_num;
1970 goto out;
1971 }
1972
1973 if ((cropped_tail && prev_end > *paddr_end) || (cropped_head && prev_start < paddr_min)) {
1974 /* This should never happen, but be safe */
1975 apfs_alert(sb, "recursion cropping physical extent 0x%llx-0x%llx", prev_start, prev_end);
1976 ret = -EFSCORRUPTED;
1977 goto out;
1978 }
1979
1980 if (prev_end > *paddr_end) {
1981 ret = apfs_split_phys_ext(query, *paddr_end);
1982 if (ret) {
1983 apfs_err(sb, "failed to split pext at 0x%llx", *paddr_end);
1984 goto out;
1985 }
1986 /* The split may make the query invalid */
1987 apfs_free_query(query);
1988 cropped_tail = true;
1989 goto restart;
1990 }
1991
1992 if (prev_start < paddr_min) {
1993 ret = apfs_split_phys_ext(query, paddr_min);
1994 if (ret) {
1995 apfs_err(sb, "failed to split pext at 0x%llx", paddr_min);
1996 goto out;
1997 }
1998 /* The split may make the query invalid */
1999 apfs_free_query(query);
2000 cropped_head = true;
2001 goto restart;
2002 }
2003
2004 /* The extent to put already exists */
2005 ret = apfs_put_phys_extent(&prev_ext, query);
2006 if (ret)
2007 apfs_err(sb, "failed to put pext at 0x%llx", prev_ext.bno);
2008 *paddr_end = prev_start;
2009
2010 out:
2011 apfs_free_query(query);
2012 apfs_node_free(extref_root);
2013 return ret;
2014 }
2015
2016 /**
2017 * apfs_range_put_reference - Put a reference to a physical range
2018 * @sb: filesystem superblock
2019 * @paddr: first block of the range
2020 * @length: length of the range (in bytes)
2021 *
2022 * Returns 0 on success, or a negative error code in case of failure.
2023 */
2024 static int apfs_range_put_reference(struct super_block *sb, u64 paddr, u64 length)
2025 {
2026 u64 extent_end;
2027 int err;
2028
2029 ASSERT(paddr);
2030
2031 extent_end = paddr + (length >> sb->s_blocksize_bits);
2032 while (extent_end > paddr) {
2033 err = apfs_put_single_extent(sb, &extent_end, paddr);
2034 if (err)
2035 return err;
2036 }
2037 return 0;
2038 }
2039
2040 /**
2041 * apfs_take_single_extent - Take a reference to a single extent
2042 * @sb: filesystem superblock
2043 * @paddr_end: first block after the extent to take
2044 * @paddr_min: don't take references before this block
2045 *
2046 * Takes a reference to the physical extent range that ends in @paddr_end. Sets
2047 * @paddr_end to the beginning of the extent, so that the caller can continue
2048 * with the previous one. Returns 0 on success, or a negative error code in
2049 * case of failure.
2050 */
2051 static int apfs_take_single_extent(struct super_block *sb, u64 *paddr_end, u64 paddr_min)
2052 {
2053 struct apfs_superblock *vsb_raw = APFS_SB(sb)->s_vsb_raw;
2054 struct apfs_node *extref_root = NULL;
2055 struct apfs_key key;
2056 struct apfs_query *query = NULL;
2057 struct apfs_phys_extent prev_ext;
2058 u64 prev_start, prev_end;
2059 bool cropped_head = false, cropped_tail = false;
2060 struct apfs_file_extent tmp = {0}; /* TODO: clean up all the fake extent interfaces? */
2061 int ret;
2062
2063 extref_root = apfs_read_node(sb, le64_to_cpu(vsb_raw->apfs_extentref_tree_oid), APFS_OBJ_PHYSICAL, true /* write */);
2064 if (IS_ERR(extref_root)) {
2065 apfs_err(sb, "failed to read extref root 0x%llx", le64_to_cpu(vsb_raw->apfs_extentref_tree_oid));
2066 return PTR_ERR(extref_root);
2067 }
2068 apfs_assert_in_transaction(sb, &vsb_raw->apfs_o);
2069 vsb_raw->apfs_extentref_tree_oid = cpu_to_le64(extref_root->object.oid);
2070
2071 apfs_init_extent_key(*paddr_end - 1, &key);
2072
2073 restart:
2074 query = apfs_alloc_query(extref_root, NULL /* parent */);
2075 if (!query) {
2076 ret = -ENOMEM;
2077 goto out;
2078 }
2079 query->key = key;
2080 query->flags = APFS_QUERY_EXTENTREF;
2081
2082 ret = apfs_btree_query(sb, &query);
2083 if (ret && ret != -ENODATA) {
2084 apfs_err(sb, "query failed for paddr 0x%llx", *paddr_end - 1);
2085 goto out;
2086 }
2087
2088 if (ret == -ENODATA) {
2089 /* The whole range to take is part of a snapshot */
2090 tmp.phys_block_num = paddr_min;
2091 tmp.len = (*paddr_end - paddr_min) << sb->s_blocksize_bits;
2092 ret = apfs_create_update_pext(query, &tmp, +1);
2093 *paddr_end = paddr_min;
2094 goto out;
2095 }
2096
2097 ret = apfs_phys_ext_from_query(query, &prev_ext);
2098 if (ret) {
2099 apfs_err(sb, "bad pext record over paddr 0x%llx", *paddr_end - 1);
2100 goto out;
2101 }
2102 prev_start = prev_ext.bno;
2103 prev_end = prev_ext.bno + prev_ext.blkcount;
2104 if (prev_end < *paddr_end) {
2105 /* The extent to take is part of a snapshot */
2106 tmp.phys_block_num = max(prev_end, paddr_min);
2107 tmp.len = (*paddr_end - tmp.phys_block_num) << sb->s_blocksize_bits;
2108 ret = apfs_create_update_pext(query, &tmp, +1);
2109 *paddr_end = tmp.phys_block_num;
2110 goto out;
2111 }
2112
2113 if ((cropped_tail && prev_end > *paddr_end) || (cropped_head && prev_start < paddr_min)) {
2114 /* This should never happen, but be safe */
2115 apfs_alert(sb, "recursion cropping physical extent 0x%llx-0x%llx", prev_start, prev_end);
2116 ret = -EFSCORRUPTED;
2117 goto out;
2118 }
2119
2120 if (prev_end > *paddr_end) {
2121 ret = apfs_split_phys_ext(query, *paddr_end);
2122 if (ret) {
2123 apfs_err(sb, "failed to split pext at 0x%llx", *paddr_end);
2124 goto out;
2125 }
2126 /* The split may make the query invalid */
2127 apfs_free_query(query);
2128 cropped_tail = true;
2129 goto restart;
2130 }
2131
2132 if (prev_start < paddr_min) {
2133 ret = apfs_split_phys_ext(query, paddr_min);
2134 if (ret) {
2135 apfs_err(sb, "failed to split pext at 0x%llx", paddr_min);
2136 goto out;
2137 }
2138 /* The split may make the query invalid */
2139 apfs_free_query(query);
2140 cropped_head = true;
2141 goto restart;
2142 }
2143
2144 /* The extent to take already exists */
2145 ret = apfs_take_phys_extent(&prev_ext, query);
2146 if (ret)
2147 apfs_err(sb, "failed to take pext at 0x%llx", prev_ext.bno);
2148 *paddr_end = prev_start;
2149
2150 out:
2151 apfs_free_query(query);
2152 apfs_node_free(extref_root);
2153 return ret;
2154 }
2155
2156 /**
2157 * apfs_range_take_reference - Take a reference to a physical range
2158 * @sb: filesystem superblock
2159 * @paddr: first block of the range
2160 * @length: length of the range (in bytes)
2161 *
2162 * Returns 0 on success, or a negative error code in case of failure.
2163 */
2164 static int apfs_range_take_reference(struct super_block *sb, u64 paddr, u64 length)
2165 {
2166 u64 extent_end;
2167 int err;
2168
2169 ASSERT(paddr);
2170
2171 extent_end = paddr + (length >> sb->s_blocksize_bits);
2172 while (extent_end > paddr) {
2173 err = apfs_take_single_extent(sb, &extent_end, paddr);
2174 if (err)
2175 return err;
2176 }
2177 return 0;
2178 }
2179
2180 /**
2181 * apfs_clone_single_extent - Make a copy of an extent in a dstream to a new one
2182 * @dstream: old dstream
2183 * @new_id: id of the new dstream
2184 * @log_addr: logical address for the extent
2185 *
2186 * Duplicates the logical extent, and updates the references to the physical
2187 * extents as required. Sets @addr to the end of the extent, so that the caller
2188 * can continue in the same place. Returns 0 on success, or a negative error
2189 * code in case of failure.
2190 */
2191 static int apfs_clone_single_extent(struct apfs_dstream_info *dstream, u64 new_id, u64 *log_addr)
2192 {
2193 struct super_block *sb = dstream->ds_sb;
2194 struct apfs_file_extent extent;
2195 int err;
2196
2197 err = apfs_extent_read(dstream, *log_addr >> sb->s_blocksize_bits, &extent);
2198 if (err) {
2199 apfs_err(sb, "failed to read an extent to clone for dstream 0x%llx", dstream->ds_id);
2200 return err;
2201 }
2202 err = apfs_extent_create_record(sb, new_id, &extent);
2203 if (err) {
2204 apfs_err(sb, "failed to create extent record for clone of dstream 0x%llx", dstream->ds_id);
2205 return err;
2206 }
2207
2208 if (!apfs_ext_is_hole(&extent)) {
2209 err = apfs_range_take_reference(sb, extent.phys_block_num, extent.len);
2210 if (err) {
2211 apfs_err(sb, "failed to take a reference to physical range 0x%llx-0x%llx", extent.phys_block_num, extent.len);
2212 return err;
2213 }
2214 }
2215
2216 *log_addr += extent.len;
2217 return 0;
2218 }
2219
2220 /**
2221 * apfs_clone_extents - Make a copy of all extents in a dstream to a new one
2222 * @dstream: old dstream
2223 * @new_id: id for the new dstream
2224 *
2225 * Returns 0 on success, or a negative error code in case of failure.
2226 */
2227 int apfs_clone_extents(struct apfs_dstream_info *dstream, u64 new_id)
2228 {
2229 u64 next = 0;
2230 int err;
2231
2232 while (next < dstream->ds_size) {
2233 err = apfs_clone_single_extent(dstream, new_id, &next);
2234 if (err)
2235 return err;
2236 }
2237 return 0;
2238 }
2239
2240 /**
2241 * apfs_nonsparse_dstream_read - Read from a dstream without holes
2242 * @dstream: dstream to read
2243 * @buf: destination buffer
2244 * @count: exact number of bytes to read
2245 * @offset: dstream offset to read from
2246 *
2247 * Returns 0 on success or a negative error code in case of failure.
2248 */
2249 int apfs_nonsparse_dstream_read(struct apfs_dstream_info *dstream, void *buf, size_t count, u64 offset)
2250 {
2251 struct super_block *sb = dstream->ds_sb;
2252 u64 logical_start_block, logical_end_block, log_bno, blkcnt, idx;
2253 struct buffer_head **bhs = NULL;
2254 int ret = 0;
2255
2256 /* Save myself from thinking about overflow here */
2257 if (count >= APFS_MAX_FILE_SIZE || offset >= APFS_MAX_FILE_SIZE) {
2258 apfs_err(sb, "dstream read overflow (0x%llx-0x%llx)", offset, (unsigned long long)count);
2259 return -EFBIG;
2260 }
2261
2262 if (offset + count > dstream->ds_size) {
2263 apfs_err(sb, "reading past the end (0x%llx-0x%llx)", offset, (unsigned long long)count);
2264 /* No caller is expected to legitimately read out-of-bounds */
2265 return -EFSCORRUPTED;
2266 }
2267
2268 logical_start_block = offset >> sb->s_blocksize_bits;
2269 logical_end_block = (offset + count + sb->s_blocksize - 1) >> sb->s_blocksize_bits;
2270 blkcnt = logical_end_block - logical_start_block;
2271 bhs = kcalloc(blkcnt, sizeof(*bhs), GFP_KERNEL);
2272 if (!bhs)
2273 return -ENOMEM;
2274
2275 for (log_bno = logical_start_block; log_bno < logical_end_block; log_bno++) {
2276 struct buffer_head *bh = NULL;
2277 u64 bno = 0;
2278
2279 idx = log_bno - logical_start_block;
2280
2281 ret = apfs_logic_to_phys_bno(dstream, log_bno, &bno);
2282 if (ret)
2283 goto out;
2284 if (bno == 0) {
2285 apfs_err(sb, "nonsparse dstream has a hole");
2286 ret = -EFSCORRUPTED;
2287 goto out;
2288 }
2289
2290 bhs[idx] = __apfs_getblk(sb, bno);
2291 if (!bhs[idx]) {
2292 apfs_err(sb, "failed to map block 0x%llx", bno);
2293 ret = -EIO;
2294 goto out;
2295 }
2296
2297 bh = bhs[idx];
2298 if (!buffer_uptodate(bh)) {
2299 get_bh(bh);
2300 lock_buffer(bh);
2301 apfs_submit_bh(REQ_OP_READ, 0, bh);
2302 }
2303 }
2304
2305 for (log_bno = logical_start_block; log_bno < logical_end_block; log_bno++) {
2306 int off_in_block, left_in_block;
2307
2308 idx = log_bno - logical_start_block;
2309 wait_on_buffer(bhs[idx]);
2310 if (!buffer_uptodate(bhs[idx])) {
2311 apfs_err(sb, "failed to read a block");
2312 ret = -EIO;
2313 goto out;
2314 }
2315
2316 if (log_bno == logical_start_block)
2317 off_in_block = offset & (sb->s_blocksize - 1);
2318 else
2319 off_in_block = 0;
2320
2321 if (log_bno == logical_end_block - 1)
2322 left_in_block = count + offset - (log_bno << sb->s_blocksize_bits) - off_in_block;
2323 else
2324 left_in_block = sb->s_blocksize - off_in_block;
2325
2326 memcpy(buf, bhs[idx]->b_data + off_in_block, left_in_block);
2327 buf += left_in_block;
2328 }
2329
2330 out:
2331 if (bhs) {
2332 for (idx = 0; idx < blkcnt; idx++)
2333 brelse(bhs[idx]);
2334 kfree(bhs);
2335 }
2336 return ret;
2337 }
2338
2339 /**
2340 * apfs_nonsparse_dstream_preread - Attempt to preread a dstream without holes
2341 * @dstream: dstream to preread
2342 *
2343 * Requests reads for all blocks of a dstream, but doesn't wait for the result.
2344 */
2345 void apfs_nonsparse_dstream_preread(struct apfs_dstream_info *dstream)
2346 {
2347 struct super_block *sb = dstream->ds_sb;
2348 u64 logical_end_block, log_bno;
2349
2350 logical_end_block = (dstream->ds_size + sb->s_blocksize - 1) >> sb->s_blocksize_bits;
2351
2352 for (log_bno = 0; log_bno < logical_end_block; log_bno++) {
2353 struct buffer_head *bh = NULL;
2354 u64 bno = 0;
2355 int ret;
2356
2357 ret = apfs_logic_to_phys_bno(dstream, log_bno, &bno);
2358 if (ret || bno == 0)
2359 return;
2360
2361 bh = __apfs_getblk(sb, bno);
2362 if (!bh)
2363 return;
2364 if (!buffer_uptodate(bh)) {
2365 get_bh(bh);
2366 lock_buffer(bh);
2367 apfs_submit_bh(REQ_OP_READ, 0, bh);
2368 }
2369 brelse(bh);
2370 bh = NULL;
2371 }
2372 }