Debian Codegraph @

btree.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 "apfs.h"
9
10 struct apfs_node *apfs_query_root(const struct apfs_query *query)
11 {
12 while (query->parent)
13 query = query->parent;
14 ASSERT(apfs_node_is_root(query->node));
15 return query->node;
16 }
17
18 static u64 apfs_catalog_base_oid(struct apfs_query *query)
19 {
20 struct apfs_query *root_query = NULL;
21
22 root_query = query;
23 while (root_query->parent)
24 root_query = root_query->parent;
25
26 return root_query->node->object.oid;
27 }
28
29 /**
30 * apfs_child_from_query - Read the child id found by a successful nonleaf query
31 * @query: the query that found the record
32 * @child: Return parameter. The child id found.
33 *
34 * Reads the child id in the nonleaf node record into @child and performs a
35 * basic sanity check as a protection against crafted filesystems. Returns 0
36 * on success or -EFSCORRUPTED otherwise.
37 */
38 static int apfs_child_from_query(struct apfs_query *query, u64 *child)
39 {
40 struct super_block *sb = query->node->object.sb;
41 char *raw = query->node->object.data;
42
43 if (query->flags & APFS_QUERY_CAT && apfs_is_sealed(sb)) {
44 struct apfs_btn_index_node_val *index_val = NULL;
45
46 if (query->len != sizeof(*index_val)) {
47 apfs_err(sb, "bad sealed index value length (%d)", query->len);
48 return -EFSCORRUPTED;
49 }
50 index_val = (struct apfs_btn_index_node_val *)(raw + query->off);
51 *child = le64_to_cpu(index_val->binv_child_oid) + apfs_catalog_base_oid(query);
52 } else {
53 if (query->len != 8) { /* The value on a nonleaf node is the child id */
54 apfs_err(sb, "bad index value length (%d)", query->len);
55 return -EFSCORRUPTED;
56 }
57 *child = le64_to_cpup((__le64 *)(raw + query->off));
58 }
59 return 0;
60 }
61
62 /**
63 * apfs_omap_cache_lookup - Look for an oid in an omap's cache
64 * @omap: the object map
65 * @oid: object id to look up
66 * @bno: on return, the block number for the oid
67 *
68 * Returns 0 on success, or -1 if this mapping is not cached.
69 */
70 static int apfs_omap_cache_lookup(struct apfs_omap *omap, u64 oid, u64 *bno)
71 {
72 struct apfs_omap_cache *cache = &omap->omap_cache;
73 struct apfs_omap_rec *record = NULL;
74 int slot;
75 int ret = -1;
76
77 if (cache->disabled)
78 return -1;
79
80 /* Uninitialized cache records use OID 0, so check this just in case */
81 if (!oid)
82 return -1;
83
84 slot = oid & APFS_OMAP_CACHE_SLOT_MASK;
85 record = &cache->recs[slot];
86
87 spin_lock(&cache->lock);
88 if (record->oid == oid) {
89 *bno = record->bno;
90 ret = 0;
91 }
92 spin_unlock(&cache->lock);
93
94 return ret;
95 }
96
97 /**
98 * apfs_omap_cache_save - Save a record in an omap's cache
99 * @omap: the object map
100 * @oid: object id of the record
101 * @bno: block number for the oid
102 */
103 static void apfs_omap_cache_save(struct apfs_omap *omap, u64 oid, u64 bno)
104 {
105 struct apfs_omap_cache *cache = &omap->omap_cache;
106 struct apfs_omap_rec *record = NULL;
107 int slot;
108
109 if (cache->disabled)
110 return;
111
112 slot = oid & APFS_OMAP_CACHE_SLOT_MASK;
113 record = &cache->recs[slot];
114
115 spin_lock(&cache->lock);
116 record->oid = oid;
117 record->bno = bno;
118 spin_unlock(&cache->lock);
119 }
120
121 /**
122 * apfs_omap_cache_delete - Try to delete a record from an omap's cache
123 * @omap: the object map
124 * @oid: object id of the record
125 */
126 static void apfs_omap_cache_delete(struct apfs_omap *omap, u64 oid)
127 {
128 struct apfs_omap_cache *cache = &omap->omap_cache;
129 struct apfs_omap_rec *record = NULL;
130 int slot;
131
132 if (cache->disabled)
133 return;
134
135 slot = oid & APFS_OMAP_CACHE_SLOT_MASK;
136 record = &cache->recs[slot];
137
138 spin_lock(&cache->lock);
139 if (record->oid == oid) {
140 record->oid = 0;
141 record->bno = 0;
142 }
143 spin_unlock(&cache->lock);
144 }
145
146 /**
147 * apfs_mounted_xid - Returns the mounted xid for this superblock
148 * @sb: superblock structure
149 *
150 * This function is needed instead of APFS_NXI(@sb)->nx_xid in situations where
151 * we might be working with a snapshot. Snapshots are read-only and should
152 * mostly ignore xids, so this only appears to matter for omap lookups.
153 */
154 static inline u64 apfs_mounted_xid(struct super_block *sb)
155 {
156 struct apfs_sb_info *sbi = APFS_SB(sb);
157 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
158
159 return sbi->s_snap_xid ? sbi->s_snap_xid : nxi->nx_xid;
160 }
161
162 /**
163 * apfs_xid_in_snapshot - Check if an xid is part of a snapshot
164 * @omap: the object map
165 * @xid: the xid to check
166 */
167 static inline bool apfs_xid_in_snapshot(struct apfs_omap *omap, u64 xid)
168 {
169 return xid <= omap->omap_latest_snap;
170 }
171
172 /**
173 * apfs_omap_lookup_block_with_xid - Find bno of a virtual object from oid/xid
174 * @sb: filesystem superblock
175 * @omap: object map to be searched
176 * @id: id of the node
177 * @xid: transaction id
178 * @block: on return, the found block number
179 * @write: get write access to the object?
180 *
181 * Searches @omap for the most recent matching object with a transaction id
182 * below @xid. Returns 0 on success or a negative error code in case of failure.
183 */
184 static int apfs_omap_lookup_block_with_xid(struct super_block *sb, struct apfs_omap *omap, u64 id, u64 xid, u64 *block, bool write)
185 {
186 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
187 struct apfs_query *query;
188 struct apfs_omap_map map = {0};
189 int ret = 0;
190
191 if (!write) {
192 if (!apfs_omap_cache_lookup(omap, id, block))
193 return 0;
194 }
195
196 query = apfs_alloc_query(omap->omap_root, NULL /* parent */);
197 if (!query)
198 return -ENOMEM;
199 apfs_init_omap_key(id, xid, &query->key);
200 query->flags |= APFS_QUERY_OMAP;
201
202 ret = apfs_btree_query(sb, &query);
203 if (ret) {
204 if (ret != -ENODATA)
205 apfs_err(sb, "query failed for oid 0x%llx, xid 0x%llx", id, xid);
206 goto fail;
207 }
208
209 ret = apfs_omap_map_from_query(query, &map);
210 if (ret) {
211 apfs_alert(sb, "bad object map leaf block: 0x%llx",
212 query->node->object.block_nr);
213 goto fail;
214 }
215 *block = map.bno;
216
217 if (write) {
218 struct apfs_omap_key key;
219 struct apfs_omap_val val;
220 struct buffer_head *new_bh;
221 bool preserve;
222
223 preserve = apfs_xid_in_snapshot(omap, map.xid);
224
225 new_bh = apfs_read_object_block(sb, *block, write, preserve);
226 if (IS_ERR(new_bh)) {
227 apfs_err(sb, "CoW failed for oid 0x%llx, xid 0x%llx", id, xid);
228 ret = PTR_ERR(new_bh);
229 goto fail;
230 }
231
232 key.ok_oid = cpu_to_le64(id);
233 key.ok_xid = cpu_to_le64(nxi->nx_xid);
234 val.ov_flags = cpu_to_le32(map.flags);
235 val.ov_size = cpu_to_le32(sb->s_blocksize);
236 val.ov_paddr = cpu_to_le64(new_bh->b_blocknr);
237
238 if (preserve)
239 ret = apfs_btree_insert(query, &key, sizeof(key), &val, sizeof(val));
240 else
241 ret = apfs_btree_replace(query, &key, sizeof(key), &val, sizeof(val));
242 if (ret)
243 apfs_err(sb, "CoW omap update failed (oid 0x%llx, xid 0x%llx)", id, xid);
244
245 *block = new_bh->b_blocknr;
246 brelse(new_bh);
247 }
248
249 apfs_omap_cache_save(omap, id, *block);
250
251 fail:
252 apfs_free_query(query);
253 return ret;
254 }
255
256 /**
257 * apfs_omap_lookup_block - Find the block number of a b-tree node from its id
258 * @sb: filesystem superblock
259 * @omap: object map to be searched
260 * @id: id of the node
261 * @block: on return, the found block number
262 * @write: get write access to the object?
263 *
264 * Returns 0 on success or a negative error code in case of failure.
265 */
266 int apfs_omap_lookup_block(struct super_block *sb, struct apfs_omap *omap, u64 id, u64 *block, bool write)
267 {
268 return apfs_omap_lookup_block_with_xid(sb, omap, id, apfs_mounted_xid(sb), block, write);
269 }
270
271 /**
272 * apfs_omap_lookup_newest_block - Find newest bno for a virtual object's oid
273 * @sb: filesystem superblock
274 * @omap: object map to be searched
275 * @id: id of the object
276 * @block: on return, the found block number
277 * @write: get write access to the object?
278 *
279 * Returns 0 on success or a negative error code in case of failure.
280 */
281 int apfs_omap_lookup_newest_block(struct super_block *sb, struct apfs_omap *omap, u64 id, u64 *block, bool write)
282 {
283 return apfs_omap_lookup_block_with_xid(sb, omap, id, -1, block, write);
284 }
285
286 /**
287 * apfs_create_omap_rec - Create a record in the volume's omap tree
288 * @sb: filesystem superblock
289 * @oid: object id
290 * @bno: block number
291 *
292 * Returns 0 on success or a negative error code in case of failure.
293 */
294 int apfs_create_omap_rec(struct super_block *sb, u64 oid, u64 bno)
295 {
296 struct apfs_sb_info *sbi = APFS_SB(sb);
297 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
298 struct apfs_omap *omap = sbi->s_omap;
299 struct apfs_query *query;
300 struct apfs_omap_key raw_key;
301 struct apfs_omap_val raw_val;
302 int ret;
303
304 query = apfs_alloc_query(omap->omap_root, NULL /* parent */);
305 if (!query)
306 return -ENOMEM;
307 apfs_init_omap_key(oid, nxi->nx_xid, &query->key);
308 query->flags |= APFS_QUERY_OMAP;
309
310 ret = apfs_btree_query(sb, &query);
311 if (ret && ret != -ENODATA) {
312 apfs_err(sb, "query failed for oid 0x%llx, bno 0x%llx", oid, bno);
313 goto fail;
314 }
315
316 raw_key.ok_oid = cpu_to_le64(oid);
317 raw_key.ok_xid = cpu_to_le64(nxi->nx_xid);
318 raw_val.ov_flags = 0;
319 raw_val.ov_size = cpu_to_le32(sb->s_blocksize);
320 raw_val.ov_paddr = cpu_to_le64(bno);
321
322 ret = apfs_btree_insert(query, &raw_key, sizeof(raw_key),
323 &raw_val, sizeof(raw_val));
324 if (ret) {
325 apfs_err(sb, "insertion failed for oid 0x%llx, bno 0x%llx", oid, bno);
326 goto fail;
327 }
328
329 apfs_omap_cache_save(omap, oid, bno);
330
331 fail:
332 apfs_free_query(query);
333 return ret;
334 }
335
336 /**
337 * apfs_delete_omap_rec - Delete an existing record from the volume's omap tree
338 * @sb: filesystem superblock
339 * @oid: object id for the record
340 *
341 * Returns 0 on success or a negative error code in case of failure.
342 */
343 int apfs_delete_omap_rec(struct super_block *sb, u64 oid)
344 {
345 struct apfs_sb_info *sbi = APFS_SB(sb);
346 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
347 struct apfs_omap *omap = sbi->s_omap;
348 struct apfs_query *query;
349 int ret;
350
351 query = apfs_alloc_query(omap->omap_root, NULL /* parent */);
352 if (!query)
353 return -ENOMEM;
354 apfs_init_omap_key(oid, nxi->nx_xid, &query->key);
355 query->flags |= APFS_QUERY_OMAP;
356
357 ret = apfs_btree_query(sb, &query);
358 if (ret == -ENODATA) {
359 apfs_err(sb, "nonexistent record (oid 0x%llx)", oid);
360 ret = -EFSCORRUPTED;
361 goto fail;
362 }
363 if (ret) {
364 apfs_err(sb, "query failed (oid 0x%llx)", oid);
365 goto fail;
366 }
367 ret = apfs_btree_remove(query);
368 if (ret) {
369 apfs_err(sb, "removal failed (oid 0x%llx)", oid);
370 goto fail;
371 }
372 apfs_omap_cache_delete(omap, oid);
373
374 fail:
375 apfs_free_query(query);
376 return ret;
377 }
378
379 /**
380 * apfs_alloc_query - Allocates a query structure
381 * @node: node to be searched
382 * @parent: query for the parent node
383 *
384 * Callers other than apfs_btree_query() should set @parent to NULL, and @node
385 * to the root of the b-tree. They should also initialize most of the query
386 * fields themselves; when @parent is not NULL the query will inherit them.
387 *
388 * Returns the allocated query, or NULL in case of failure.
389 */
390 struct apfs_query *apfs_alloc_query(struct apfs_node *node,
391 struct apfs_query *parent)
392 {
393 struct apfs_query *query;
394
395 query = kzalloc(sizeof(*query), GFP_KERNEL);
396 if (!query)
397 return NULL;
398
399 /* To be released by free_query. */
400 query->node = node;
401
402 if (parent) {
403 query->key = parent->key;
404 query->flags = parent->flags & ~(APFS_QUERY_DONE | APFS_QUERY_NEXT);
405 query->parent = parent;
406 query->depth = parent->depth + 1;
407 }
408
409 /*
410 * We start the search with the last record and go backwards, but
411 * some queries later use the PREV flag later to list them in order.
412 */
413 if (query->flags & APFS_QUERY_PREV)
414 query->index = -1;
415 else
416 query->index = node->records;
417
418 return query;
419 }
420
421 /**
422 * apfs_free_query - Free a query structure
423 * @query: query to free
424 *
425 * Also frees the ancestor queries, if they are kept.
426 */
427 void apfs_free_query(struct apfs_query *query)
428 {
429 while (query) {
430 struct apfs_query *parent = query->parent;
431
432 /* The caller decides whether to free the root node */
433 if (query->depth != 0)
434 apfs_node_free(query->node);
435 kfree(query);
436 query = parent;
437 }
438 }
439
440 /**
441 * apfs_query_set_before_first - Set the query to point before the first record
442 * @sb: superblock structure
443 * @query: the query to set
444 *
445 * Queries set in this way are used to insert a record before the first one.
446 * Only the leaf gets set to the -1 entry; queries for other levels must be set
447 * to 0, since the first entry in each index node will need to be modified.
448 *
449 * Returns 0 on success, or a negative error code in case of failure.
450 */
451 static int apfs_query_set_before_first(struct super_block *sb, struct apfs_query **query)
452 {
453 struct apfs_node *node = NULL;
454 struct apfs_query *parent = NULL;
455 u64 child_id;
456 u32 storage = apfs_query_storage(*query);
457 int err;
458
459 while ((*query)->depth < 12) {
460 if (apfs_node_is_leaf((*query)->node)) {
461 (*query)->index = -1;
462 return 0;
463 }
464 apfs_node_query_first(*query);
465
466 err = apfs_child_from_query(*query, &child_id);
467 if (err) {
468 apfs_alert(sb, "bad index block: 0x%llx",
469 (*query)->node->object.block_nr);
470 return err;
471 }
472
473 /* Now go a level deeper */
474 node = apfs_read_node(sb, child_id, storage, false /* write */);
475 if (IS_ERR(node)) {
476 apfs_err(sb, "failed to read child 0x%llx of node 0x%llx", child_id, (*query)->node->object.oid);
477 return PTR_ERR(node);
478 }
479
480 parent = *query;
481 *query = apfs_alloc_query(node, parent);
482 if (!*query) {
483 apfs_node_free(node);
484 *query = parent;
485 return -ENOMEM;
486 }
487 node = NULL;
488 }
489
490 apfs_err(sb, "btree is too high");
491 return -EFSCORRUPTED;
492 }
493
494 /**
495 * apfs_btree_query - Execute a query on a b-tree
496 * @sb: filesystem superblock
497 * @query: the query to execute
498 *
499 * Searches the b-tree starting at @query->index in @query->node, looking for
500 * the record corresponding to @query->key.
501 *
502 * Returns 0 in case of success and sets the @query->len, @query->off and
503 * @query->index fields to the results of the query. @query->node will now
504 * point to the leaf node holding the record.
505 *
506 * In case of failure returns an appropriate error code.
507 */
508 int apfs_btree_query(struct super_block *sb, struct apfs_query **query)
509 {
510 struct apfs_node *node;
511 struct apfs_query *parent;
512 u64 child_id;
513 u32 storage = apfs_query_storage(*query);
514 int err;
515
516 next_node:
517 if ((*query)->depth >= 12) {
518 /*
519 * We need a maximum depth for the tree so we can't loop
520 * forever if the filesystem is damaged. 12 should be more
521 * than enough to map every block.
522 */
523 apfs_err(sb, "btree is too high");
524 err = -EFSCORRUPTED;
525 goto fail;
526 }
527
528 err = apfs_node_query(sb, *query);
529 if (err == -ENODATA && !(*query)->parent && (*query)->index == -1) {
530 /*
531 * We may be trying to insert a record before all others: don't
532 * let the query give up at the root node.
533 */
534 err = apfs_query_set_before_first(sb, query);
535 if (err) {
536 apfs_err(sb, "failed to set before the first record");
537 goto fail;
538 }
539 err = -ENODATA;
540 goto fail;
541 } else if (err == -EAGAIN) {
542 if (!(*query)->parent) {
543 /* We are at the root of the tree */
544 err = -ENODATA;
545 goto fail;
546 }
547
548 /* Move back up one level and continue the query */
549 parent = (*query)->parent;
550 (*query)->parent = NULL; /* Don't free the parent */
551 apfs_free_query(*query);
552 *query = parent;
553 goto next_node;
554 } else if (err) {
555 goto fail;
556 }
557 if (apfs_node_is_leaf((*query)->node)) /* All done */
558 return 0;
559
560 err = apfs_child_from_query(*query, &child_id);
561 if (err) {
562 apfs_alert(sb, "bad index block: 0x%llx",
563 (*query)->node->object.block_nr);
564 goto fail;
565 }
566
567 /* Now go a level deeper and search the child */
568 node = apfs_read_node(sb, child_id, storage, false /* write */);
569 if (IS_ERR(node)) {
570 apfs_err(sb, "failed to read node 0x%llx", child_id);
571 err = PTR_ERR(node);
572 goto fail;
573 }
574
575 if (node->object.oid != child_id)
576 apfs_debug(sb, "corrupt b-tree");
577
578 /*
579 * Remember the parent node and index in case the search needs
580 * to be continued later.
581 */
582 parent = *query;
583 *query = apfs_alloc_query(node, parent);
584 if (!*query) {
585 apfs_node_free(node);
586 *query = parent;
587 err = -ENOMEM;
588 goto fail;
589 }
590 node = NULL;
591 goto next_node;
592
593 fail:
594 /* Don't leave stale record info here or some callers will use it */
595 (*query)->key_len = (*query)->len = 0;
596 return err;
597 }
598
599 static int __apfs_btree_replace(struct apfs_query *query, void *key, int key_len, void *val, int val_len);
600
601 /**
602 * apfs_query_join_transaction - Add the found node to the current transaction
603 * @query: query that found the node
604 */
605 int apfs_query_join_transaction(struct apfs_query *query)
606 {
607 struct apfs_node *node = query->node;
608 struct super_block *sb = node->object.sb;
609 u64 oid = node->object.oid;
610 u32 storage = apfs_query_storage(query);
611 struct apfs_obj_phys *raw = NULL;
612
613 /*
614 * Ephemeral objects are checkpoint data, and all of their xids get
615 * updated on commit. There is no real need to do it here as well, but
616 * it's better for consistency with the other object types.
617 */
618 if (storage == APFS_OBJ_EPHEMERAL) {
619 ASSERT(node->object.ephemeral);
620 raw = (void *)node->object.data;
621 raw->o_xid = cpu_to_le64(APFS_NXI(sb)->nx_xid);
622 return 0;
623 }
624
625 if (buffer_trans(node->object.o_bh)) /* Already in the transaction */
626 return 0;
627 /* Root nodes should join the transaction before the query is created */
628 ASSERT(!apfs_node_is_root(node));
629
630 node = apfs_read_node(sb, oid, storage, true /* write */);
631 if (IS_ERR(node)) {
632 apfs_err(sb, "Cow failed for node 0x%llx", oid);
633 return PTR_ERR(node);
634 }
635 apfs_node_free(query->node);
636 query->node = node;
637
638 if (storage == APFS_OBJ_PHYSICAL && query->parent) {
639 __le64 bno = cpu_to_le64(node->object.block_nr);
640
641 /* The parent node needs to report the new location */
642 return __apfs_btree_replace(query->parent, NULL /* key */, 0 /* key_len */, &bno, sizeof(bno));
643 }
644 return 0;
645 }
646
647 /**
648 * apfs_btree_change_rec_count - Update the b-tree info before a record change
649 * @query: query used to insert/remove/replace the leaf record
650 * @change: change in the record count
651 * @key_len: length of the new leaf record key (0 if removed or unchanged)
652 * @val_len: length of the new leaf record value (0 if removed or unchanged)
653 *
654 * Don't call this function if @query->parent was reset to NULL, or if the same
655 * is true of any of its ancestor queries.
656 */
657 static void apfs_btree_change_rec_count(struct apfs_query *query, int change,
658 int key_len, int val_len)
659 {
660 struct super_block *sb;
661 struct apfs_node *root;
662 struct apfs_btree_node_phys *root_raw;
663 struct apfs_btree_info *info;
664
665 if (change == -1)
666 ASSERT(!key_len && !val_len);
667 ASSERT(apfs_node_is_leaf(query->node));
668
669 root = apfs_query_root(query);
670 ASSERT(apfs_node_is_root(root));
671
672 sb = root->object.sb;
673 root_raw = (void *)root->object.data;
674 info = (void *)root_raw + sb->s_blocksize - sizeof(*info);
675
676 apfs_assert_in_transaction(sb, &root_raw->btn_o);
677 if (key_len > le32_to_cpu(info->bt_longest_key))
678 info->bt_longest_key = cpu_to_le32(key_len);
679 if (val_len > le32_to_cpu(info->bt_longest_val))
680 info->bt_longest_val = cpu_to_le32(val_len);
681 le64_add_cpu(&info->bt_key_count, change);
682 }
683
684 /**
685 * apfs_btree_change_node_count - Change the node count for a b-tree
686 * @query: query used to remove/create the node
687 * @change: change in the node count
688 *
689 * Also changes the node count in the volume superblock. Don't call this
690 * function if @query->parent was reset to NULL, or if the same is true of
691 * any of its ancestor queries.
692 */
693 void apfs_btree_change_node_count(struct apfs_query *query, int change)
694 {
695 struct super_block *sb;
696 struct apfs_node *root;
697 struct apfs_btree_node_phys *root_raw;
698 struct apfs_btree_info *info;
699
700 root = apfs_query_root(query);
701 ASSERT(apfs_node_is_root(root));
702
703 sb = root->object.sb;
704 root_raw = (void *)root->object.data;
705 info = (void *)root_raw + sb->s_blocksize - sizeof(*info);
706
707 apfs_assert_in_transaction(sb, &root_raw->btn_o);
708 le64_add_cpu(&info->bt_node_count, change);
709 }
710
711 /**
712 * apfs_query_refresh - Recreate a catalog query invalidated by node splits
713 * @old_query: query chain to refresh
714 * @root: root node of the query chain
715 * @nodata: is the query expected to find nothing?
716 *
717 * On success, @old_query is left pointing to the same leaf record, but with
718 * valid ancestor queries as well. Returns a negative error code in case of
719 * failure, or 0 on success.
720 */
721 static int apfs_query_refresh(struct apfs_query *old_query, struct apfs_node *root, bool nodata)
722 {
723 struct super_block *sb = NULL;
724 struct apfs_query *new_query = NULL;
725 int err = 0;
726
727 sb = root->object.sb;
728
729 if (!apfs_node_is_leaf(old_query->node)) {
730 apfs_alert(sb, "attempting refresh of non-leaf query");
731 return -EFSCORRUPTED;
732 }
733 if (apfs_node_is_root(old_query->node)) {
734 apfs_alert(sb, "attempting refresh of root query");
735 return -EFSCORRUPTED;
736 }
737
738 new_query = apfs_alloc_query(root, NULL /* parent */);
739 if (!new_query)
740 return -ENOMEM;
741 new_query->key = old_query->key;
742 new_query->flags = old_query->flags & ~(APFS_QUERY_DONE | APFS_QUERY_NEXT);
743
744 err = apfs_btree_query(sb, &new_query);
745 if (!nodata && err == -ENODATA) {
746 apfs_err(sb, "record should exist");
747 err = -EFSCORRUPTED;
748 goto fail;
749 }
750 if (err && err != -ENODATA) {
751 apfs_err(sb, "failed to rerun");
752 goto fail;
753 }
754 err = 0;
755
756 /* Replace the parent of the original query with the new valid one */
757 apfs_free_query(old_query->parent);
758 old_query->parent = new_query->parent;
759 new_query->parent = NULL;
760
761 /*
762 * The records may have moved around so update this too. TODO: rework
763 * the query struct so this stuff is not needed.
764 */
765 ASSERT(old_query->node->object.oid == new_query->node->object.oid);
766 old_query->index = new_query->index;
767 old_query->key_off = new_query->key_off;
768 old_query->key_len = new_query->key_len;
769 old_query->off = new_query->off;
770 old_query->len = new_query->len;
771 old_query->depth = new_query->depth;
772
773 fail:
774 apfs_free_query(new_query);
775 return err;
776 }
777
778 /**
779 * __apfs_btree_insert - Insert a new record into a b-tree (at any level)
780 * @query: query run to search for the record
781 * @key: on-disk record key
782 * @key_len: length of @key
783 * @val: on-disk record value (NULL for ghost records)
784 * @val_len: length of @val (0 for ghost records)
785 *
786 * The new record is placed right after the one found by @query. On success,
787 * returns 0 and sets @query to the new record; returns a negative error code
788 * in case of failure, which may be -EAGAIN if a split happened and the caller
789 * must retry.
790 */
791 int __apfs_btree_insert(struct apfs_query *query, void *key, int key_len, void *val, int val_len)
792 {
793 struct apfs_node *node = query->node;
794 struct super_block *sb = node->object.sb;
795 struct apfs_btree_node_phys *node_raw;
796 int needed_room;
797 int err;
798
799 apfs_assert_query_is_valid(query);
800
801 err = apfs_query_join_transaction(query);
802 if (err) {
803 apfs_err(sb, "query join failed");
804 return err;
805 }
806
807 node = query->node;
808 node_raw = (void *)node->object.data;
809 apfs_assert_in_transaction(node->object.sb, &node_raw->btn_o);
810
811 needed_room = key_len + val_len;
812 if (!apfs_node_has_room(node, needed_room, false /* replace */)) {
813 if (node->records == 1) {
814 /* The new record just won't fit in the node */
815 err = apfs_create_single_rec_node(query, key, key_len, val, val_len);
816 if (err && err != -EAGAIN)
817 apfs_err(sb, "failed to create single-record node");
818 return err;
819 }
820 err = apfs_node_split(query);
821 if (err && err != -EAGAIN) {
822 apfs_err(sb, "node split failed");
823 return err;
824 }
825 return -EAGAIN;
826 }
827
828 apfs_assert_query_is_valid(query);
829
830 if (query->parent && query->index == -1) {
831 /* We are about to insert a record before all others */
832 err = __apfs_btree_replace(query->parent, key, key_len, NULL /* val */, 0 /* val_len */);
833 if (err) {
834 if (err != -EAGAIN)
835 apfs_err(sb, "parent update failed");
836 return err;
837 }
838 }
839
840 apfs_assert_query_is_valid(query);
841
842 err = apfs_node_insert(query, key, key_len, val, val_len);
843 if (err) {
844 apfs_err(sb, "node record insertion failed");
845 return err;
846 }
847 return 0;
848 }
849
850 /**
851 * apfs_btree_insert - Insert a new record into a b-tree leaf
852 * @query: query run to search for the record
853 * @key: on-disk record key
854 * @key_len: length of @key
855 * @val: on-disk record value (NULL for ghost records)
856 * @val_len: length of @val (0 for ghost records)
857 *
858 * The new record is placed right after the one found by @query. On success,
859 * returns 0 and sets @query to the new record; returns a negative error code
860 * in case of failure.
861 */
862 int apfs_btree_insert(struct apfs_query *query, void *key, int key_len, void *val, int val_len)
863 {
864 struct super_block *sb = NULL;
865 struct apfs_node *root = NULL, *leaf = NULL;
866 int err;
867
868 root = apfs_query_root(query);
869 ASSERT(apfs_node_is_root(root));
870 leaf = query->node;
871 ASSERT(apfs_node_is_leaf(leaf));
872 sb = root->object.sb;
873
874 while (true) {
875 err = __apfs_btree_insert(query, key, key_len, val, val_len);
876 if (err != -EAGAIN) {
877 if (err)
878 return err;
879 break;
880 }
881 err = apfs_query_refresh(query, root, true /* nodata */);
882 if (err) {
883 apfs_err(sb, "query refresh failed");
884 return err;
885 }
886 }
887
888 apfs_assert_query_is_valid(query);
889 apfs_btree_change_rec_count(query, 1 /* change */, key_len, val_len);
890 return 0;
891 }
892
893 /**
894 * __apfs_btree_remove - Remove a record from a b-tree (at any level)
895 * @query: exact query that found the record
896 *
897 * Returns 0 on success, or a negative error code in case of failure, which may
898 * be -EAGAIN if a split happened and the caller must retry.
899 */
900 static int __apfs_btree_remove(struct apfs_query *query)
901 {
902 struct apfs_node *node = query->node;
903 struct super_block *sb = node->object.sb;
904 struct apfs_btree_node_phys *node_raw;
905 int later_entries = node->records - query->index - 1;
906 int err;
907
908 apfs_assert_query_is_valid(query);
909
910 err = apfs_query_join_transaction(query);
911 if (err) {
912 apfs_err(sb, "query join failed");
913 return err;
914 }
915
916 node = query->node;
917 node_raw = (void *)query->node->object.data;
918 apfs_assert_in_transaction(node->object.sb, &node_raw->btn_o);
919
920 if (query->parent && node->records == 1) {
921 /* Just get rid of the node */
922 err = __apfs_btree_remove(query->parent);
923 if (err == -EAGAIN)
924 return -EAGAIN;
925 if (err) {
926 apfs_err(sb, "parent index removal failed");
927 return err;
928 }
929 apfs_btree_change_node_count(query, -1 /* change */);
930 err = apfs_delete_node(node, query->flags & APFS_QUERY_TREE_MASK);
931 if (err) {
932 apfs_err(sb, "node deletion failed");
933 return err;
934 }
935 return 0;
936 }
937
938 apfs_assert_query_is_valid(query);
939
940 /* The first key in a node must match the parent record's */
941 if (query->parent && query->index == 0) {
942 int first_key_len, first_key_off;
943 void *key;
944
945 first_key_len = apfs_node_locate_key(node, 1, &first_key_off);
946 if (!first_key_len)
947 return -EFSCORRUPTED;
948 key = (void *)node_raw + first_key_off;
949
950 err = __apfs_btree_replace(query->parent, key, first_key_len, NULL /* val */, 0 /* val_len */);
951 if (err == -EAGAIN)
952 return -EAGAIN;
953 if (err) {
954 apfs_err(sb, "parent update failed");
955 return err;
956 }
957 }
958
959 apfs_assert_query_is_valid(query);
960
961 /* Remove the entry from the table of contents */
962 if (apfs_node_has_fixed_kv_size(node)) {
963 struct apfs_kvoff *toc_entry;
964
965 toc_entry = (struct apfs_kvoff *)node_raw->btn_data +
966 query->index;
967 memmove(toc_entry, toc_entry + 1,
968 later_entries * sizeof(*toc_entry));
969 } else {
970 struct apfs_kvloc *toc_entry;
971
972 toc_entry = (struct apfs_kvloc *)node_raw->btn_data +
973 query->index;
974 memmove(toc_entry, toc_entry + 1,
975 later_entries * sizeof(*toc_entry));
976 }
977
978 apfs_node_free_range(node, query->key_off, query->key_len);
979 apfs_node_free_range(node, query->off, query->len);
980
981 --node->records;
982 if (node->records == 0) {
983 /* All descendants are gone, root is the whole tree */
984 node_raw->btn_level = 0;
985 node->flags |= APFS_BTNODE_LEAF;
986 }
987 apfs_update_node(node);
988
989 --query->index;
990 return 0;
991 }
992
993 /**
994 * apfs_btree_remove - Remove a record from a b-tree leaf
995 * @query: exact query that found the record
996 *
997 * Returns 0 on success, or a negative error code in case of failure.
998 */
999 int apfs_btree_remove(struct apfs_query *query)
1000 {
1001 struct super_block *sb = NULL;
1002 struct apfs_node *root = NULL, *leaf = NULL;
1003 int err;
1004
1005 root = apfs_query_root(query);
1006 ASSERT(apfs_node_is_root(root));
1007 leaf = query->node;
1008 ASSERT(apfs_node_is_leaf(leaf));
1009 sb = root->object.sb;
1010
1011 while (true) {
1012 err = __apfs_btree_remove(query);
1013 if (err != -EAGAIN) {
1014 if (err)
1015 return err;
1016 break;
1017 }
1018 err = apfs_query_refresh(query, root, false /* nodata */);
1019 if (err) {
1020 apfs_err(sb, "query refresh failed");
1021 return err;
1022 }
1023 }
1024
1025 apfs_assert_query_is_valid(query);
1026 apfs_btree_change_rec_count(query, -1 /* change */, 0 /* key_len */, 0 /* val_len */);
1027 return 0;
1028 }
1029
1030 /**
1031 * __apfs_btree_replace - Replace a record in a b-tree (at any level)
1032 * @query: exact query that found the record
1033 * @key: new on-disk record key (NULL if unchanged)
1034 * @key_len: length of @key
1035 * @val: new on-disk record value (NULL if unchanged)
1036 * @val_len: length of @val
1037 *
1038 * It's important that the order of the records is not changed by the new @key.
1039 * This function is not needed to replace an old value with a new one of the
1040 * same length: it can just be overwritten in place.
1041 *
1042 * Returns 0 on success, and @query is left pointing to the same record; returns
1043 * a negative error code in case of failure, which may be -EAGAIN if a split
1044 * happened and the caller must retry.
1045 */
1046 static int __apfs_btree_replace(struct apfs_query *query, void *key, int key_len, void *val, int val_len)
1047 {
1048 struct apfs_node *node = query->node;
1049 struct super_block *sb = node->object.sb;
1050 struct apfs_btree_node_phys *node_raw;
1051 int needed_room;
1052 int err;
1053
1054 ASSERT(key || val);
1055 apfs_assert_query_is_valid(query);
1056
1057 err = apfs_query_join_transaction(query);
1058 if (err) {
1059 apfs_err(sb, "query join failed");
1060 return err;
1061 }
1062
1063 node = query->node;
1064 node_raw = (void *)node->object.data;
1065 apfs_assert_in_transaction(sb, &node_raw->btn_o);
1066
1067 needed_room = key_len + val_len;
1068 /* We can reuse the space of the replaced key/value */
1069 if (key)
1070 needed_room -= query->key_len;
1071 if (val)
1072 needed_room -= query->len;
1073
1074 if (!apfs_node_has_room(node, needed_room, true /* replace */)) {
1075 if (node->records == 1) {
1076 apfs_alert(sb, "no room in empty node?");
1077 return -EFSCORRUPTED;
1078 }
1079 err = apfs_node_split(query);
1080 if (err && err != -EAGAIN) {
1081 apfs_err(sb, "node split failed");
1082 return err;
1083 }
1084 return -EAGAIN;
1085 }
1086
1087 apfs_assert_query_is_valid(query);
1088
1089 /* The first key in a node must match the parent record's */
1090 if (key && query->parent && query->index == 0) {
1091 err = __apfs_btree_replace(query->parent, key, key_len, NULL /* val */, 0 /* val_len */);
1092 if (err) {
1093 if (err != -EAGAIN)
1094 apfs_err(sb, "parent update failed");
1095 return err;
1096 }
1097 }
1098
1099 apfs_assert_query_is_valid(query);
1100
1101 err = apfs_node_replace(query, key, key_len, val, val_len);
1102 if (err) {
1103 apfs_err(sb, "node record replacement failed");
1104 return err;
1105 }
1106 return 0;
1107 }
1108
1109 /**
1110 * apfs_btree_replace - Replace a record in a b-tree leaf
1111 * @query: exact query that found the record
1112 * @key: new on-disk record key (NULL if unchanged)
1113 * @key_len: length of @key
1114 * @val: new on-disk record value (NULL if unchanged)
1115 * @val_len: length of @val
1116 *
1117 * It's important that the order of the records is not changed by the new @key.
1118 * This function is not needed to replace an old value with a new one of the
1119 * same length: it can just be overwritten in place.
1120 *
1121 * Returns 0 on success, and @query is left pointing to the same record; returns
1122 * a negative error code in case of failure.
1123 */
1124 int apfs_btree_replace(struct apfs_query *query, void *key, int key_len, void *val, int val_len)
1125 {
1126 struct super_block *sb = NULL;
1127 struct apfs_node *root = NULL, *leaf = NULL;
1128 int err;
1129
1130 root = apfs_query_root(query);
1131 ASSERT(apfs_node_is_root(root));
1132 leaf = query->node;
1133 ASSERT(apfs_node_is_leaf(leaf));
1134 sb = root->object.sb;
1135
1136 while (true) {
1137 err = __apfs_btree_replace(query, key, key_len, val, val_len);
1138 if (err != -EAGAIN) {
1139 if (err)
1140 return err;
1141 break;
1142 }
1143 err = apfs_query_refresh(query, root, false /* nodata */);
1144 if (err) {
1145 apfs_err(sb, "query refresh failed");
1146 return err;
1147 }
1148 }
1149
1150 apfs_assert_query_is_valid(query);
1151 apfs_btree_change_rec_count(query, 0 /* change */, key_len, val_len);
1152 return 0;
1153 }
1154
1155 /**
1156 * apfs_query_direct_forward - Set a query to start listing records forwards
1157 * @query: a successfully executed query
1158 *
1159 * Multiple queries list records backwards, but queries marked with this
1160 * function after execution will go in the opposite direction.
1161 */
1162 void apfs_query_direct_forward(struct apfs_query *query)
1163 {
1164 if (query->flags & APFS_QUERY_PREV)
1165 return;
1166
1167 apfs_assert_query_is_valid(query);
1168 ASSERT(apfs_node_is_leaf(query->node));
1169
1170 while (query) {
1171 query->flags |= APFS_QUERY_PREV;
1172 query = query->parent;
1173 }
1174 }