Debian Codegraph @

node.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/slab.h>
7 #include <linux/buffer_head.h>
8 #include "apfs.h"
9
10 /**
11 * apfs_node_is_valid - Check basic sanity of the node index
12 * @sb: filesystem superblock
13 * @node: node to check
14 *
15 * Verifies that the node index fits in a single block, and that the number
16 * of records fits in the index. Without this check a crafted filesystem could
17 * pretend to have too many records, and calls to apfs_node_locate_key() and
18 * apfs_node_locate_value() would read beyond the limits of the node.
19 */
20 static bool apfs_node_is_valid(struct super_block *sb,
21 struct apfs_node *node)
22 {
23 u32 records = node->records;
24 int index_size = node->key - sizeof(struct apfs_btree_node_phys);
25 int entry_size;
26
27 if (node->key > sb->s_blocksize)
28 return false;
29
30 entry_size = (apfs_node_has_fixed_kv_size(node)) ?
31 sizeof(struct apfs_kvoff) : sizeof(struct apfs_kvloc);
32
33 /* Coarse bound to prevent multiplication overflow in final check */
34 if (records > 1 << 16)
35 return false;
36
37 return records * entry_size <= index_size;
38 }
39
40 void apfs_node_free(struct apfs_node *node)
41 {
42 struct apfs_object *obj = NULL;
43
44 if (!node)
45 return;
46 obj = &node->object;
47
48 if (obj->o_bh) {
49 brelse(obj->o_bh);
50 obj->o_bh = NULL;
51 } else if (!obj->ephemeral) {
52 /* Ephemeral data always remains in memory */
53 kfree(obj->data);
54 }
55 obj->data = NULL;
56
57 kfree(node);
58 }
59
60 /**
61 * apfs_read_node - Read a node header from disk
62 * @sb: filesystem superblock
63 * @oid: object id for the node
64 * @storage: storage type for the node object
65 * @write: request write access?
66 *
67 * Returns ERR_PTR in case of failure, otherwise return a pointer to the
68 * resulting apfs_node structure with the initial reference taken.
69 *
70 * For now we assume the node has not been read before.
71 */
72 struct apfs_node *apfs_read_node(struct super_block *sb, u64 oid, u32 storage,
73 bool write)
74 {
75 struct apfs_sb_info *sbi = APFS_SB(sb);
76 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
77 struct buffer_head *bh = NULL;
78 struct apfs_ephemeral_object_info *eph_info = NULL;
79 struct apfs_btree_node_phys *raw = NULL;
80 struct apfs_node *node = NULL;
81 struct apfs_nloc *free_head = NULL;
82 u64 bno;
83 int err;
84
85 switch (storage) {
86 case APFS_OBJ_VIRTUAL:
87 /* All virtual nodes are inside a volume, at least for now */
88 err = apfs_omap_lookup_block(sb, sbi->s_omap, oid, &bno, write);
89 if (err) {
90 apfs_err(sb, "omap lookup failed for oid 0x%llx", oid);
91 return ERR_PTR(err);
92 }
93 /* CoW has already been done, don't worry about snapshots */
94 bh = apfs_read_object_block(sb, bno, write, false /* preserve */);
95 if (IS_ERR(bh)) {
96 apfs_err(sb, "object read failed for bno 0x%llx", bno);
97 return (void *)bh;
98 }
99 bno = bh->b_blocknr;
100 raw = (struct apfs_btree_node_phys *)bh->b_data;
101 break;
102 case APFS_OBJ_PHYSICAL:
103 bh = apfs_read_object_block(sb, oid, write, false /* preserve */);
104 if (IS_ERR(bh)) {
105 apfs_err(sb, "object read failed for bno 0x%llx", oid);
106 return (void *)bh;
107 }
108 bno = oid = bh->b_blocknr;
109 raw = (struct apfs_btree_node_phys *)bh->b_data;
110 break;
111 case APFS_OBJ_EPHEMERAL:
112 /* Ephemeral objects are already in memory */
113 eph_info = apfs_ephemeral_object_lookup(sb, oid);
114 if (IS_ERR(eph_info)) {
115 apfs_err(sb, "no ephemeral node for oid 0x%llx", oid);
116 return (void *)eph_info;
117 }
118 if (eph_info->size != sb->s_blocksize) {
119 apfs_err(sb, "unsupported size for ephemeral node (%u)", eph_info->size);
120 return ERR_PTR(-EOPNOTSUPP);
121 }
122 bno = 0; /* In memory, so meaningless */
123 raw = eph_info->object;
124 /* Only for consistency, will happen again on commit */
125 if (write)
126 raw->btn_o.o_xid = cpu_to_le64(nxi->nx_xid);
127 break;
128 default:
129 apfs_alert(sb, "invalid storage type %u - bug!", storage);
130 return ERR_PTR(-EINVAL);
131 }
132
133 node = kmalloc(sizeof(*node), GFP_KERNEL);
134 if (!node) {
135 brelse(bh);
136 return ERR_PTR(-ENOMEM);
137 }
138
139 node->tree_type = le32_to_cpu(raw->btn_o.o_subtype);
140 node->flags = le16_to_cpu(raw->btn_flags);
141 node->records = le32_to_cpu(raw->btn_nkeys);
142 node->key = sizeof(*raw) + le16_to_cpu(raw->btn_table_space.off)
143 + le16_to_cpu(raw->btn_table_space.len);
144 node->free = node->key + le16_to_cpu(raw->btn_free_space.off);
145 node->val = node->free + le16_to_cpu(raw->btn_free_space.len);
146
147 free_head = &raw->btn_key_free_list;
148 node->key_free_list_len = le16_to_cpu(free_head->len);
149 free_head = &raw->btn_val_free_list;
150 node->val_free_list_len = le16_to_cpu(free_head->len);
151
152 node->object.sb = sb;
153 node->object.block_nr = bno;
154 node->object.oid = oid;
155 node->object.o_bh = bh;
156 node->object.data = (char *)raw;
157 node->object.ephemeral = !bh;
158
159 /* Ephemeral objects already got checked on mount */
160 if (!node->object.ephemeral && nxi->nx_flags & APFS_CHECK_NODES && !apfs_obj_verify_csum(sb, bh)) {
161 /* TODO: don't check this twice for virtual/physical objects */
162 apfs_err(sb, "bad checksum for node in block 0x%llx", (unsigned long long)bno);
163 apfs_node_free(node);
164 return ERR_PTR(-EFSBADCRC);
165 }
166 if (!apfs_node_is_valid(sb, node)) {
167 apfs_err(sb, "bad node in block 0x%llx", (unsigned long long)bno);
168 apfs_node_free(node);
169 return ERR_PTR(-EFSCORRUPTED);
170 }
171
172 return node;
173 }
174
175 /**
176 * apfs_node_min_table_size - Return the minimum size for a node's toc
177 * @sb: superblock structure
178 * @type: tree type for the node
179 * @flags: flags for the node
180 */
181 static int apfs_node_min_table_size(struct super_block *sb, u32 type, u16 flags)
182 {
183 bool leaf = flags & APFS_BTNODE_LEAF;
184 int key_size, val_size, toc_size;
185 int space, count;
186
187 /* Preallocate the whole table for trees with fixed key/value sizes */
188 switch (type) {
189 case APFS_OBJECT_TYPE_OMAP:
190 key_size = sizeof(struct apfs_omap_key);
191 val_size = leaf ? sizeof(struct apfs_omap_val) : sizeof(__le64);
192 toc_size = sizeof(struct apfs_kvoff);
193 break;
194 case APFS_OBJECT_TYPE_SPACEMAN_FREE_QUEUE:
195 key_size = sizeof(struct apfs_spaceman_free_queue_key);
196 val_size = sizeof(__le64); /* We assume no ghosts here */
197 toc_size = sizeof(struct apfs_kvoff);
198 break;
199 case APFS_OBJECT_TYPE_OMAP_SNAPSHOT:
200 key_size = sizeof(__le64);
201 val_size = leaf ? sizeof(struct apfs_omap_snapshot) : sizeof(__le64);
202 toc_size = sizeof(struct apfs_kvoff);
203 break;
204 case APFS_OBJECT_TYPE_FEXT_TREE:
205 key_size = sizeof(struct apfs_fext_tree_key);
206 val_size = leaf ? sizeof(struct apfs_fext_tree_val) : sizeof(__le64);
207 toc_size = sizeof(struct apfs_kvoff);
208 break;
209 default:
210 /* Make room for one record at least */
211 toc_size = sizeof(struct apfs_kvloc);
212 return APFS_BTREE_TOC_ENTRY_INCREMENT * toc_size;
213 }
214
215 /* The footer of root nodes is ignored for some reason */
216 space = sb->s_blocksize - sizeof(struct apfs_btree_node_phys);
217 count = space / (key_size + val_size + toc_size);
218 return count * toc_size;
219 }
220
221 /**
222 * apfs_set_empty_btree_info - Set the info footer for an empty b-tree node
223 * @sb: filesystem superblock
224 * @info: pointer to the on-disk info footer
225 * @subtype: subtype of the root node, i.e., tree type
226 *
227 * For now only supports the extent reference tree.
228 */
229 static void apfs_set_empty_btree_info(struct super_block *sb, struct apfs_btree_info *info, u32 subtype)
230 {
231 u32 flags;
232
233 ASSERT(subtype == APFS_OBJECT_TYPE_BLOCKREFTREE || subtype == APFS_OBJECT_TYPE_OMAP_SNAPSHOT);
234
235 memset(info, 0, sizeof(*info));
236
237 flags = APFS_BTREE_PHYSICAL;
238 if (subtype == APFS_OBJECT_TYPE_BLOCKREFTREE)
239 flags |= APFS_BTREE_KV_NONALIGNED;
240
241 info->bt_fixed.bt_flags = cpu_to_le32(flags);
242 info->bt_fixed.bt_node_size = cpu_to_le32(sb->s_blocksize);
243 info->bt_key_count = 0;
244 info->bt_node_count = cpu_to_le64(1); /* Only one node: the root */
245 if (subtype == APFS_OBJECT_TYPE_BLOCKREFTREE)
246 return;
247
248 info->bt_fixed.bt_key_size = cpu_to_le32(8);
249 info->bt_longest_key = info->bt_fixed.bt_key_size;
250 info->bt_fixed.bt_val_size = cpu_to_le32(sizeof(struct apfs_omap_snapshot));
251 info->bt_longest_val = info->bt_fixed.bt_val_size;
252 }
253
254 /**
255 * apfs_make_empty_btree_root - Make an empty root for a b-tree
256 * @sb: filesystem superblock
257 * @subtype: subtype of the root node, i.e., tree type
258 * @oid: on return, the root's object id
259 *
260 * For now only supports the extent reference tree and an omap's snapshot tree.
261 * Returns 0 on success or a negative error code in case of failure.
262 */
263 int apfs_make_empty_btree_root(struct super_block *sb, u32 subtype, u64 *oid)
264 {
265 struct apfs_superblock *vsb_raw = APFS_SB(sb)->s_vsb_raw;
266 struct apfs_btree_node_phys *root = NULL;
267 struct buffer_head *bh = NULL;
268 u64 bno;
269 u16 flags;
270 int toc_len, free_len, head_len, info_len;
271 int err;
272
273 ASSERT(subtype == APFS_OBJECT_TYPE_BLOCKREFTREE || subtype == APFS_OBJECT_TYPE_OMAP_SNAPSHOT);
274
275 err = apfs_spaceman_allocate_block(sb, &bno, true /* backwards */);
276 if (err) {
277 apfs_err(sb, "block allocation failed");
278 return err;
279 }
280 apfs_assert_in_transaction(sb, &vsb_raw->apfs_o);
281 le64_add_cpu(&vsb_raw->apfs_fs_alloc_count, 1);
282 le64_add_cpu(&vsb_raw->apfs_total_blocks_alloced, 1);
283
284 bh = apfs_getblk(sb, bno);
285 if (!bh)
286 return -EIO;
287 root = (void *)bh->b_data;
288 err = apfs_transaction_join(sb, bh);
289 if (err)
290 goto fail;
291 set_buffer_csum(bh);
292
293 flags = APFS_BTNODE_ROOT | APFS_BTNODE_LEAF;
294 if (subtype == APFS_OBJECT_TYPE_OMAP_SNAPSHOT)
295 flags |= APFS_BTNODE_FIXED_KV_SIZE;
296 root->btn_flags = cpu_to_le16(flags);
297
298 toc_len = apfs_node_min_table_size(sb, subtype, flags);
299 head_len = sizeof(*root);
300 info_len = sizeof(struct apfs_btree_info);
301 free_len = sb->s_blocksize - head_len - toc_len - info_len;
302
303 root->btn_level = 0; /* Root */
304
305 /* No keys and no values, so this is straightforward */
306 root->btn_nkeys = 0;
307 root->btn_table_space.off = 0;
308 root->btn_table_space.len = cpu_to_le16(toc_len);
309 root->btn_free_space.off = 0;
310 root->btn_free_space.len = cpu_to_le16(free_len);
311
312 /* No fragmentation */
313 root->btn_key_free_list.off = cpu_to_le16(APFS_BTOFF_INVALID);
314 root->btn_key_free_list.len = 0;
315 root->btn_val_free_list.off = cpu_to_le16(APFS_BTOFF_INVALID);
316 root->btn_val_free_list.len = 0;
317
318 apfs_set_empty_btree_info(sb, (void *)root + sb->s_blocksize - info_len, subtype);
319
320 root->btn_o.o_oid = cpu_to_le64(bno);
321 root->btn_o.o_xid = cpu_to_le64(APFS_NXI(sb)->nx_xid);
322 root->btn_o.o_type = cpu_to_le32(APFS_OBJECT_TYPE_BTREE | APFS_OBJ_PHYSICAL);
323 root->btn_o.o_subtype = cpu_to_le32(subtype);
324
325 *oid = bno;
326 err = 0;
327 fail:
328 root = NULL;
329 brelse(bh);
330 bh = NULL;
331 return err;
332 }
333
334 /**
335 * apfs_create_node - Allocates a new nonroot b-tree node on disk
336 * @sb: filesystem superblock
337 * @storage: storage type for the node object
338 *
339 * On success returns a pointer to the new in-memory node structure; the object
340 * header is initialized, and the node fields are given reasonable defaults.
341 * On failure, returns an error pointer.
342 */
343 static struct apfs_node *apfs_create_node(struct super_block *sb, u32 storage)
344 {
345 struct apfs_sb_info *sbi = APFS_SB(sb);
346 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
347 struct apfs_nx_superblock *msb_raw = nxi->nx_raw;
348 struct apfs_superblock *vsb_raw = sbi->s_vsb_raw;
349 struct apfs_ephemeral_object_info *eph_info = NULL;
350 struct apfs_node *node = NULL;
351 struct buffer_head *bh = NULL;
352 struct apfs_btree_node_phys *raw = NULL;
353 u64 bno, oid;
354 int err;
355
356 switch (storage) {
357 case APFS_OBJ_VIRTUAL:
358 err = apfs_spaceman_allocate_block(sb, &bno, true /* backwards */);
359 if (err) {
360 apfs_err(sb, "block allocation failed");
361 return ERR_PTR(err);
362 }
363 apfs_assert_in_transaction(sb, &vsb_raw->apfs_o);
364 le64_add_cpu(&vsb_raw->apfs_fs_alloc_count, 1);
365 le64_add_cpu(&vsb_raw->apfs_total_blocks_alloced, 1);
366
367 oid = le64_to_cpu(msb_raw->nx_next_oid);
368 le64_add_cpu(&msb_raw->nx_next_oid, 1);
369 err = apfs_create_omap_rec(sb, oid, bno);
370 if (err) {
371 apfs_err(sb, "omap rec creation failed (0x%llx-0x%llx)", oid, bno);
372 return ERR_PTR(err);
373 }
374 break;
375 case APFS_OBJ_PHYSICAL:
376 err = apfs_spaceman_allocate_block(sb, &bno, true /* backwards */);
377 if (err) {
378 apfs_err(sb, "block allocation failed");
379 return ERR_PTR(err);
380 }
381 /* We don't write to the container's omap */
382 apfs_assert_in_transaction(sb, &vsb_raw->apfs_o);
383 le64_add_cpu(&vsb_raw->apfs_fs_alloc_count, 1);
384 le64_add_cpu(&vsb_raw->apfs_total_blocks_alloced, 1);
385 oid = bno;
386 break;
387 case APFS_OBJ_EPHEMERAL:
388 if (nxi->nx_eph_count >= APFS_EPHEMERAL_LIST_LIMIT) {
389 apfs_err(sb, "creating too many ephemeral objects?");
390 return ERR_PTR(-EOPNOTSUPP);
391 }
392 eph_info = &nxi->nx_eph_list[nxi->nx_eph_count++];
393 eph_info->object = kzalloc(sb->s_blocksize, GFP_KERNEL);
394 if (!eph_info->object)
395 return ERR_PTR(-ENOMEM);
396 eph_info->size = sb->s_blocksize;
397 oid = eph_info->oid = le64_to_cpu(msb_raw->nx_next_oid);
398 le64_add_cpu(&msb_raw->nx_next_oid, 1);
399 break;
400 default:
401 apfs_alert(sb, "invalid storage type %u - bug!", storage);
402 return ERR_PTR(-EINVAL);
403 }
404
405 if (storage == APFS_OBJ_EPHEMERAL) {
406 bh = NULL;
407 bno = 0;
408 raw = eph_info->object;
409 } else {
410 bh = apfs_getblk(sb, bno);
411 if (!bh)
412 return ERR_PTR(-EIO);
413 bno = bh->b_blocknr;
414 raw = (void *)bh->b_data;
415 err = apfs_transaction_join(sb, bh);
416 if (err)
417 goto fail;
418 set_buffer_csum(bh);
419 }
420
421 /* Set most of the object header, but the subtype is up to the caller */
422 raw->btn_o.o_oid = cpu_to_le64(oid);
423 raw->btn_o.o_xid = cpu_to_le64(nxi->nx_xid);
424 raw->btn_o.o_type = cpu_to_le32(storage | APFS_OBJECT_TYPE_BTREE_NODE);
425 raw->btn_o.o_subtype = 0;
426
427 /* The caller is expected to change most node fields */
428 raw->btn_flags = 0;
429 raw->btn_level = 0;
430 raw->btn_nkeys = 0;
431 raw->btn_table_space.off = 0; /* Put the toc right after the header */
432 raw->btn_table_space.len = 0;
433 raw->btn_free_space.off = 0;
434 raw->btn_free_space.len = cpu_to_le16(sb->s_blocksize - sizeof(*raw));
435 raw->btn_key_free_list.off = cpu_to_le16(APFS_BTOFF_INVALID);
436 raw->btn_key_free_list.len = 0;
437 raw->btn_val_free_list.off = cpu_to_le16(APFS_BTOFF_INVALID);
438 raw->btn_val_free_list.len = 0;
439
440 node = kmalloc(sizeof(*node), GFP_KERNEL);
441 if (!node) {
442 err = -ENOMEM;
443 goto fail;
444 }
445
446 node->object.sb = sb;
447 node->object.block_nr = bno;
448 node->object.oid = oid;
449 node->object.o_bh = bh;
450 node->object.data = (char *)raw;
451 node->object.ephemeral = !bh;
452 return node;
453
454 fail:
455 if (storage == APFS_OBJ_EPHEMERAL)
456 kfree(raw);
457 else
458 brelse(bh);
459 raw = NULL;
460 bh = NULL;
461 return ERR_PTR(err);
462 }
463
464 /**
465 * apfs_delete_node - Deletes a nonroot node from disk
466 * @node: node to delete
467 * @type: tree type for the query that found the node
468 *
469 * Does nothing to the in-memory node structure. Returns 0 on success, or a
470 * negative error code in case of failure.
471 */
472 int apfs_delete_node(struct apfs_node *node, int type)
473 {
474 struct super_block *sb = node->object.sb;
475 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
476 struct apfs_superblock *vsb_raw;
477 u64 oid = node->object.oid;
478 u64 bno = node->object.block_nr;
479 struct apfs_ephemeral_object_info *eph_info = NULL, *eph_info_end = NULL;
480 int err;
481
482 switch (type) {
483 case APFS_QUERY_CAT:
484 err = apfs_free_queue_insert(sb, bno, 1);
485 if (err) {
486 apfs_err(sb, "free queue insertion failed for 0x%llx", bno);
487 return err;
488 }
489 err = apfs_delete_omap_rec(sb, oid);
490 if (err) {
491 apfs_err(sb, "omap rec deletion failed (0x%llx)", oid);
492 return err;
493 }
494 vsb_raw = APFS_SB(sb)->s_vsb_raw;
495 apfs_assert_in_transaction(sb, &vsb_raw->apfs_o);
496 le64_add_cpu(&vsb_raw->apfs_fs_alloc_count, -1);
497 le64_add_cpu(&vsb_raw->apfs_total_blocks_freed, 1);
498 return 0;
499 case APFS_QUERY_OMAP:
500 case APFS_QUERY_EXTENTREF:
501 case APFS_QUERY_SNAP_META:
502 err = apfs_free_queue_insert(sb, bno, 1);
503 if (err) {
504 apfs_err(sb, "free queue insertion failed for 0x%llx", bno);
505 return err;
506 }
507 /* We don't write to the container's omap */
508 vsb_raw = APFS_SB(sb)->s_vsb_raw;
509 apfs_assert_in_transaction(sb, &vsb_raw->apfs_o);
510 le64_add_cpu(&vsb_raw->apfs_fs_alloc_count, -1);
511 le64_add_cpu(&vsb_raw->apfs_total_blocks_freed, 1);
512 return 0;
513 case APFS_QUERY_FREE_QUEUE:
514 eph_info_end = &nxi->nx_eph_list[nxi->nx_eph_count];
515 eph_info = apfs_ephemeral_object_lookup(sb, node->object.oid);
516 if (IS_ERR(eph_info)) {
517 apfs_alert(sb, "can't find ephemeral object to delete");
518 return PTR_ERR(eph_info);
519 }
520 kfree(eph_info->object);
521 eph_info->object = NULL;
522 memmove(eph_info, eph_info + 1, (char *)eph_info_end - (char *)(eph_info + 1));
523 eph_info_end->object = NULL;
524 --nxi->nx_eph_count;
525 return 0;
526 default:
527 apfs_alert(sb, "new query type must implement node deletion (%d)", type);
528 return -EOPNOTSUPP;
529 }
530 }
531
532 /**
533 * apfs_update_node - Update an existing node header
534 * @node: the modified in-memory node
535 */
536 void apfs_update_node(struct apfs_node *node)
537 {
538 struct super_block *sb = node->object.sb;
539 struct buffer_head *bh = node->object.o_bh;
540 struct apfs_btree_node_phys *raw = (void *)node->object.data;
541 struct apfs_nloc *free_head;
542 u32 tflags, type;
543 int toc_off;
544
545 apfs_assert_in_transaction(sb, &raw->btn_o);
546
547 raw->btn_o.o_oid = cpu_to_le64(node->object.oid);
548
549 /* The node may no longer be a root, so update the object type */
550 tflags = le32_to_cpu(raw->btn_o.o_type) & APFS_OBJECT_TYPE_FLAGS_MASK;
551 type = (node->flags & APFS_BTNODE_ROOT) ? APFS_OBJECT_TYPE_BTREE :
552 APFS_OBJECT_TYPE_BTREE_NODE;
553 raw->btn_o.o_type = cpu_to_le32(type | tflags);
554 raw->btn_o.o_subtype = cpu_to_le32(node->tree_type);
555
556 raw->btn_flags = cpu_to_le16(node->flags);
557 raw->btn_nkeys = cpu_to_le32(node->records);
558
559 toc_off = sizeof(*raw) + le16_to_cpu(raw->btn_table_space.off);
560 raw->btn_table_space.len = cpu_to_le16(node->key - toc_off);
561 raw->btn_free_space.off = cpu_to_le16(node->free - node->key);
562 raw->btn_free_space.len = cpu_to_le16(node->val - node->free);
563
564 /* Reset the lists on zero length, a defragmentation is taking place */
565 free_head = &raw->btn_key_free_list;
566 free_head->len = cpu_to_le16(node->key_free_list_len);
567 if (!free_head->len)
568 free_head->off = cpu_to_le16(APFS_BTOFF_INVALID);
569 free_head = &raw->btn_val_free_list;
570 free_head->len = cpu_to_le16(node->val_free_list_len);
571 if (!free_head->len)
572 free_head->off = cpu_to_le16(APFS_BTOFF_INVALID);
573
574 if (bh) {
575 ASSERT(buffer_trans(bh));
576 ASSERT(buffer_csum(bh));
577 }
578 }
579
580 /**
581 * apfs_node_locate_key - Locate the key of a node record
582 * @node: node to be searched
583 * @index: number of the entry to locate
584 * @off: on return will hold the offset in the block
585 *
586 * Returns the length of the key, or 0 in case of failure. The function checks
587 * that this length fits within the block; callers must use it to make sure
588 * they never operate outside its bounds.
589 */
590 int apfs_node_locate_key(struct apfs_node *node, int index, int *off)
591 {
592 struct super_block *sb = node->object.sb;
593 struct apfs_btree_node_phys *raw;
594 int len;
595
596 if (index >= node->records) {
597 apfs_err(sb, "index out of bounds (%d of %d)", index, node->records);
598 return 0;
599 }
600
601 raw = (struct apfs_btree_node_phys *)node->object.data;
602 if (apfs_node_has_fixed_kv_size(node)) {
603 struct apfs_kvoff *entry;
604
605 entry = (struct apfs_kvoff *)raw->btn_data + index;
606
607 /* TODO: it would be cleaner to read this stuff from disk */
608 if (node->tree_type == APFS_OBJECT_TYPE_OMAP_SNAPSHOT)
609 len = 8;
610 else
611 len = 16;
612
613 /* Translate offset in key area to offset in block */
614 *off = node->key + le16_to_cpu(entry->k);
615 } else {
616 /* These node types have variable length keys and values */
617 struct apfs_kvloc *entry;
618
619 entry = (struct apfs_kvloc *)raw->btn_data + index;
620 len = le16_to_cpu(entry->k.len);
621 /* Translate offset in key area to offset in block */
622 *off = node->key + le16_to_cpu(entry->k.off);
623 }
624
625 if (*off + len > sb->s_blocksize) {
626 apfs_err(sb, "key out of bounds (%d-%d)", *off, len);
627 return 0;
628 }
629 return len;
630 }
631
632 /**
633 * apfs_node_locate_value - Locate the value of a node record
634 * @node: node to be searched
635 * @index: number of the entry to locate
636 * @off: on return will hold the offset in the block
637 *
638 * Returns the length of the value, which may be 0 in case of corruption or if
639 * the record is a ghost. The function checks that this length fits within the
640 * block; callers must use it to make sure they never operate outside its
641 * bounds.
642 */
643 static int apfs_node_locate_value(struct apfs_node *node, int index, int *off)
644 {
645 struct super_block *sb = node->object.sb;
646 struct apfs_btree_node_phys *raw;
647 int len;
648
649 if (index >= node->records) {
650 apfs_err(sb, "index out of bounds (%d of %d)", index, node->records);
651 return 0;
652 }
653
654 raw = (struct apfs_btree_node_phys *)node->object.data;
655 if (apfs_node_has_fixed_kv_size(node)) {
656 /* These node types have fixed length keys and values */
657 struct apfs_kvoff *entry;
658
659 entry = (struct apfs_kvoff *)raw->btn_data + index;
660 if (node->tree_type == APFS_OBJECT_TYPE_SPACEMAN_FREE_QUEUE) {
661 /* A free-space queue record may have no value */
662 if (le16_to_cpu(entry->v) == APFS_BTOFF_INVALID) {
663 *off = 0;
664 return 0;
665 }
666 len = 8;
667 } else {
668 /* This is an omap or omap snapshots node */
669 len = apfs_node_is_leaf(node) ? 16 : 8;
670 }
671 /*
672 * Value offsets are counted backwards from the end of the
673 * block, or from the beginning of the footer when it exists
674 */
675 if (apfs_node_is_root(node)) /* has footer */
676 *off = sb->s_blocksize - sizeof(struct apfs_btree_info)
677 - le16_to_cpu(entry->v);
678 else
679 *off = sb->s_blocksize - le16_to_cpu(entry->v);
680 } else {
681 /* These node types have variable length keys and values */
682 struct apfs_kvloc *entry;
683
684 entry = (struct apfs_kvloc *)raw->btn_data + index;
685 len = le16_to_cpu(entry->v.len);
686 /*
687 * Value offsets are counted backwards from the end of the
688 * block, or from the beginning of the footer when it exists
689 */
690 if (apfs_node_is_root(node)) /* has footer */
691 *off = sb->s_blocksize - sizeof(struct apfs_btree_info)
692 - le16_to_cpu(entry->v.off);
693 else
694 *off = sb->s_blocksize - le16_to_cpu(entry->v.off);
695 }
696
697 if (*off < 0 || *off + len > sb->s_blocksize) {
698 apfs_err(sb, "value out of bounds (%d-%d)", *off, len);
699 return 0;
700 }
701 return len;
702 }
703
704 /**
705 * apfs_create_toc_entry - Create the table-of-contents entry for a record
706 * @query: query pointing to the record
707 *
708 * Creates a toc entry for the record at index @query->index and increases
709 * @node->records. The caller must ensure enough space in the table.
710 */
711 static void apfs_create_toc_entry(struct apfs_query *query)
712 {
713 struct apfs_node *node = query->node;
714 struct super_block *sb = node->object.sb;
715 struct apfs_btree_node_phys *raw = (void *)node->object.data;
716 int value_end;
717 int recs = node->records;
718 int index = query->index;
719
720 value_end = sb->s_blocksize;
721 if (apfs_node_is_root(node))
722 value_end -= sizeof(struct apfs_btree_info);
723
724 if (apfs_node_has_fixed_kv_size(node)) {
725 struct apfs_kvoff *kvoff;
726
727 kvoff = (struct apfs_kvoff *)raw->btn_data + query->index;
728 memmove(kvoff + 1, kvoff, (recs - index) * sizeof(*kvoff));
729
730 if (!query->len) /* Ghost record */
731 kvoff->v = cpu_to_le16(APFS_BTOFF_INVALID);
732 else
733 kvoff->v = cpu_to_le16(value_end - query->off);
734 kvoff->k = cpu_to_le16(query->key_off - node->key);
735 } else {
736 struct apfs_kvloc *kvloc;
737
738 kvloc = (struct apfs_kvloc *)raw->btn_data + query->index;
739 memmove(kvloc + 1, kvloc, (recs - index) * sizeof(*kvloc));
740
741 kvloc->v.off = cpu_to_le16(value_end - query->off);
742 kvloc->v.len = cpu_to_le16(query->len);
743 kvloc->k.off = cpu_to_le16(query->key_off - node->key);
744 kvloc->k.len = cpu_to_le16(query->key_len);
745 }
746 node->records++;
747 }
748
749 /**
750 * apfs_key_from_query - Read the current key from a query structure
751 * @query: the query, with @query->key_off and @query->key_len already set
752 * @key: return parameter for the key
753 *
754 * Reads the key into @key and performs some basic sanity checks as a
755 * protection against crafted filesystems. Returns 0 on success or a
756 * negative error code otherwise.
757 */
758 static int apfs_key_from_query(struct apfs_query *query, struct apfs_key *key)
759 {
760 struct super_block *sb = query->node->object.sb;
761 char *raw = query->node->object.data;
762 void *raw_key = (void *)(raw + query->key_off);
763 bool hashed;
764 int err = 0;
765
766 switch (query->flags & APFS_QUERY_TREE_MASK) {
767 case APFS_QUERY_CAT:
768 hashed = apfs_is_normalization_insensitive(sb);
769 err = apfs_read_cat_key(raw_key, query->key_len, key, hashed);
770 break;
771 case APFS_QUERY_OMAP:
772 err = apfs_read_omap_key(raw_key, query->key_len, key);
773 break;
774 case APFS_QUERY_FREE_QUEUE:
775 err = apfs_read_free_queue_key(raw_key, query->key_len, key);
776 break;
777 case APFS_QUERY_EXTENTREF:
778 err = apfs_read_extentref_key(raw_key, query->key_len, key);
779 break;
780 case APFS_QUERY_FEXT:
781 err = apfs_read_fext_key(raw_key, query->key_len, key);
782 break;
783 case APFS_QUERY_SNAP_META:
784 err = apfs_read_snap_meta_key(raw_key, query->key_len, key);
785 break;
786 case APFS_QUERY_OMAP_SNAP:
787 err = apfs_read_omap_snap_key(raw_key, query->key_len, key);
788 break;
789 default:
790 apfs_alert(sb, "new query type must implement key reads (%d)", query->flags & APFS_QUERY_TREE_MASK);
791 err = -EOPNOTSUPP;
792 break;
793 }
794 if (err)
795 apfs_err(sb, "bad node key in block 0x%llx", query->node->object.block_nr);
796
797 /* A multiple query must ignore some of these fields */
798 if (query->flags & APFS_QUERY_ANY_NAME)
799 key->name = NULL;
800 if (query->flags & APFS_QUERY_ANY_NUMBER)
801 key->number = 0;
802
803 return err;
804 }
805
806 /**
807 * apfs_node_prev - Find the previous record in the current node
808 * @sb: filesystem superblock
809 * @query: query in execution
810 *
811 * Returns 0 on success, -EAGAIN if the previous record is in another node,
812 * -ENODATA if no more records exist, or another negative error code in case
813 * of failure.
814 *
815 * The meaning of "next" and "previous" is reverted here, because regular
816 * multiple always start with the final record, and then they go backwards.
817 * TODO: consider renaming this for clarity.
818 */
819 static int apfs_node_prev(struct super_block *sb, struct apfs_query *query)
820 {
821 struct apfs_node *node = query->node;
822
823 if (query->index + 1 == node->records) {
824 /* The next record may be in another node */
825 return -EAGAIN;
826 }
827 ++query->index;
828
829 query->key_len = apfs_node_locate_key(node, query->index, &query->key_off);
830 if (query->key_len == 0) {
831 apfs_err(sb, "bad key for index %d", query->index);
832 return -EFSCORRUPTED;
833 }
834 query->len = apfs_node_locate_value(node, query->index, &query->off);
835 if (query->len == 0) {
836 apfs_err(sb, "bad value for index %d", query->index);
837 return -EFSCORRUPTED;
838 }
839 return 0;
840 }
841
842 /**
843 * apfs_node_next - Find the next matching record in the current node
844 * @sb: filesystem superblock
845 * @query: multiple query in execution
846 *
847 * Returns 0 on success, -EAGAIN if the next record is in another node,
848 * -ENODATA if no more matching records exist, or another negative error
849 * code in case of failure.
850 */
851 static int apfs_node_next(struct super_block *sb, struct apfs_query *query)
852 {
853 struct apfs_node *node = query->node;
854 struct apfs_key curr_key;
855 int cmp, err;
856
857 if (query->flags & APFS_QUERY_DONE)
858 /* Nothing left to search; the query failed */
859 return -ENODATA;
860
861 if (!query->index) /* The next record may be in another node */
862 return -EAGAIN;
863 --query->index;
864
865 query->key_len = apfs_node_locate_key(node, query->index,
866 &query->key_off);
867 err = apfs_key_from_query(query, &curr_key);
868 if (err) {
869 apfs_err(sb, "bad key for index %d", query->index);
870 return err;
871 }
872
873 cmp = apfs_keycmp(&curr_key, &query->key);
874
875 if (cmp > 0) {
876 apfs_err(sb, "records are out of order");
877 return -EFSCORRUPTED;
878 }
879
880 if (cmp != 0 && apfs_node_is_leaf(node) &&
881 query->flags & APFS_QUERY_EXACT)
882 return -ENODATA;
883
884 query->len = apfs_node_locate_value(node, query->index, &query->off);
885 if (query->len == 0) {
886 apfs_err(sb, "bad value for index %d", query->index);
887 return -EFSCORRUPTED;
888 }
889
890 if (cmp != 0) {
891 /*
892 * This is the last entry that can be relevant in this node.
893 * Keep searching the children, but don't return to this level.
894 */
895 query->flags |= APFS_QUERY_DONE;
896 }
897
898 return 0;
899 }
900
901 /**
902 * apfs_node_query - Execute a query on a single node
903 * @sb: filesystem superblock
904 * @query: the query to execute
905 *
906 * The search will start at index @query->index, looking for the key that comes
907 * right before @query->key, according to the order given by apfs_keycmp().
908 *
909 * The @query->index will be updated to the last index checked. This is
910 * important when searching for multiple entries, since the query may need
911 * to remember where it was on this level. If we are done with this node, the
912 * query will be flagged as APFS_QUERY_DONE, and the search will end in failure
913 * as soon as we return to this level. The function may also return -EAGAIN,
914 * to signal that the search should go on in a different branch.
915 *
916 * On success returns 0; the offset of the value within the block will be saved
917 * in @query->off, and its length in @query->len. The function checks that this
918 * length fits within the block; callers must use the returned value to make
919 * sure they never operate outside its bounds.
920 *
921 * -ENODATA will be returned if no appropriate entry was found, -EFSCORRUPTED
922 * in case of corruption.
923 */
924 int apfs_node_query(struct super_block *sb, struct apfs_query *query)
925 {
926 struct apfs_node *node = query->node;
927 int left, right;
928 int cmp;
929 int err;
930
931 if (query->flags & APFS_QUERY_PREV)
932 return apfs_node_prev(sb, query);
933 if (query->flags & APFS_QUERY_NEXT)
934 return apfs_node_next(sb, query);
935
936 /* Search by bisection */
937 cmp = 1;
938 left = 0;
939 do {
940 struct apfs_key curr_key;
941
942 if (cmp > 0) {
943 right = query->index - 1;
944 if (right < left) {
945 query->index = -1;
946 return -ENODATA;
947 }
948 query->index = (left + right) / 2;
949 } else {
950 left = query->index;
951 query->index = DIV_ROUND_UP(left + right, 2);
952 }
953
954 query->key_len = apfs_node_locate_key(node, query->index,
955 &query->key_off);
956 err = apfs_key_from_query(query, &curr_key);
957 if (err) {
958 apfs_err(sb, "bad key for index %d", query->index);
959 return err;
960 }
961
962 cmp = apfs_keycmp(&curr_key, &query->key);
963 if (cmp == 0 && !(query->flags & APFS_QUERY_MULTIPLE))
964 break;
965 } while (left != right);
966
967 if (cmp > 0) {
968 query->index = -1;
969 return -ENODATA;
970 }
971
972 if (cmp != 0 && apfs_node_is_leaf(query->node) &&
973 query->flags & APFS_QUERY_EXACT)
974 return -ENODATA;
975
976 if (query->flags & APFS_QUERY_MULTIPLE) {
977 if (cmp != 0) /* Last relevant entry in level */
978 query->flags |= APFS_QUERY_DONE;
979 query->flags |= APFS_QUERY_NEXT;
980 }
981
982 query->len = apfs_node_locate_value(node, query->index, &query->off);
983 return 0;
984 }
985
986 /**
987 * apfs_node_query_first - Find the first record in a node
988 * @query: on return this query points to the record
989 */
990 void apfs_node_query_first(struct apfs_query *query)
991 {
992 struct apfs_node *node = query->node;
993
994 query->index = 0;
995 query->key_len = apfs_node_locate_key(node, query->index, &query->key_off);
996 query->len = apfs_node_locate_value(node, query->index, &query->off);
997 }
998
999 /**
1000 * apfs_omap_map_from_query - Read the mapping found by a successful omap query
1001 * @query: the query that found the record
1002 * @map: Return parameter. The mapping found.
1003 *
1004 * Returns -EOPNOTSUPP if the object doesn't fit in one block, and -EFSCORRUPTED
1005 * if the filesystem appears to be malicious. Otherwise, reads the mapping info
1006 * in the omap record into @map and returns 0.
1007 */
1008 int apfs_omap_map_from_query(struct apfs_query *query, struct apfs_omap_map *map)
1009 {
1010 struct super_block *sb = query->node->object.sb;
1011 struct apfs_omap_key *key = NULL;
1012 struct apfs_omap_val *val = NULL;
1013 char *raw = query->node->object.data;
1014
1015 if (query->len != sizeof(*val) || query->key_len != sizeof(*key)) {
1016 apfs_err(sb, "bad length of key (%d) or value (%d)", query->key_len, query->len);
1017 return -EFSCORRUPTED;
1018 }
1019 key = (struct apfs_omap_key *)(raw + query->key_off);
1020 val = (struct apfs_omap_val *)(raw + query->off);
1021
1022 /* TODO: support objects with multiple blocks */
1023 if (le32_to_cpu(val->ov_size) != sb->s_blocksize) {
1024 apfs_err(sb, "object size doesn't match block size");
1025 return -EOPNOTSUPP;
1026 }
1027
1028 map->xid = le64_to_cpu(key->ok_xid);
1029 map->bno = le64_to_cpu(val->ov_paddr);
1030 map->flags = le32_to_cpu(val->ov_flags);
1031 return 0;
1032 }
1033
1034 /**
1035 * apfs_btree_inc_height - Increase the height of a b-tree
1036 * @query: query pointing to the root node
1037 *
1038 * On success returns 0, and @query is left pointing to the same record.
1039 * Returns a negative error code in case of failure.
1040 */
1041 static int apfs_btree_inc_height(struct apfs_query *query)
1042 {
1043 struct apfs_query *root_query;
1044 struct apfs_node *root = query->node;
1045 struct apfs_node *new_node;
1046 struct super_block *sb = root->object.sb;
1047 struct apfs_btree_node_phys *root_raw;
1048 struct apfs_btree_node_phys *new_raw;
1049 struct apfs_btree_info *info;
1050 __le64 *raw_oid;
1051 u32 storage = apfs_query_storage(query);
1052
1053 root_raw = (void *)root->object.data;
1054 apfs_assert_in_transaction(sb, &root_raw->btn_o);
1055
1056 if (query->parent || query->depth) {
1057 apfs_err(sb, "invalid root query");
1058 return -EFSCORRUPTED;
1059 }
1060
1061 /* Create a new child node */
1062 new_node = apfs_create_node(sb, storage);
1063 if (IS_ERR(new_node)) {
1064 apfs_err(sb, "node creation failed");
1065 return PTR_ERR(new_node);
1066 }
1067 new_node->flags = root->flags & ~APFS_BTNODE_ROOT;
1068 new_node->tree_type = root->tree_type;
1069
1070 /* Move all records into the child node; get rid of the info footer */
1071 new_node->records = root->records;
1072 new_node->key = root->key;
1073 new_node->free = root->free;
1074 new_node->val = root->val + sizeof(*info);
1075 new_node->key_free_list_len = root->key_free_list_len;
1076 new_node->val_free_list_len = root->val_free_list_len;
1077 new_raw = (void *)new_node->object.data;
1078 /* Don't copy the object header, already set by apfs_create_node() */
1079 memcpy((void *)new_raw + sizeof(new_raw->btn_o),
1080 (void *)root_raw + sizeof(root_raw->btn_o),
1081 root->free - sizeof(new_raw->btn_o));
1082 memcpy((void *)new_raw + new_node->val,
1083 (void *)root_raw + root->val,
1084 sb->s_blocksize - new_node->val);
1085 query->off += sizeof(*info);
1086 apfs_update_node(new_node);
1087
1088 /* Add a new level to the query chain */
1089 root_query = query->parent = apfs_alloc_query(root, NULL /* parent */);
1090 if (!query->parent) {
1091 apfs_node_free(new_node);
1092 return -ENOMEM;
1093 }
1094 root_query->key = query->key;
1095 root_query->flags = query->flags;
1096 query->node = new_node;
1097 query->depth = 1;
1098
1099 /* Now assemble the new root with only the first key */
1100 root_query->key_len = apfs_node_locate_key(root, 0 /* index */,
1101 &root_query->key_off);
1102 if (!root_query->key_len) {
1103 apfs_err(sb, "bad key for index %d", 0);
1104 return -EFSCORRUPTED;
1105 }
1106 root->key = sizeof(*root_raw) +
1107 apfs_node_min_table_size(sb, root->tree_type, root->flags & ~APFS_BTNODE_LEAF);
1108 memmove((void *)root_raw + root->key,
1109 (void *)root_raw + root_query->key_off, root_query->key_len);
1110 root_query->key_off = root->key;
1111 root->free = root->key + root_query->key_len;
1112
1113 /* The new root is a nonleaf node; the record value is the child id */
1114 root->flags &= ~APFS_BTNODE_LEAF;
1115 root->val = sb->s_blocksize - sizeof(*info) - sizeof(*raw_oid);
1116 raw_oid = (void *)root_raw + root->val;
1117 *raw_oid = cpu_to_le64(new_node->object.oid);
1118 root_query->off = root->val;
1119 root_query->len = sizeof(*raw_oid);
1120
1121 /* With the key and value in place, set the table-of-contents */
1122 root->records = 0;
1123 root_query->index = 0;
1124 apfs_create_toc_entry(root_query);
1125
1126 /* There is no internal fragmentation */
1127 root->key_free_list_len = 0;
1128 root->val_free_list_len = 0;
1129
1130 /* Finally, update the node count in the info footer */
1131 apfs_btree_change_node_count(root_query, 1 /* change */);
1132
1133 le16_add_cpu(&root_raw->btn_level, 1); /* TODO: move to update_node() */
1134 apfs_update_node(root);
1135 return 0;
1136 }
1137
1138 /**
1139 * apfs_copy_record_range - Copy a range of records to an empty node
1140 * @dest_node: destination node
1141 * @src_node: source node
1142 * @start: index of first record in range
1143 * @end: index of first record after the range
1144 *
1145 * Doesn't modify the info footer of root nodes. Returns 0 on success or a
1146 * negative error code in case of failure.
1147 */
1148 static int apfs_copy_record_range(struct apfs_node *dest_node,
1149 struct apfs_node *src_node,
1150 int start, int end)
1151 {
1152 struct super_block *sb = dest_node->object.sb;
1153 struct apfs_btree_node_phys *dest_raw;
1154 struct apfs_btree_node_phys *src_raw;
1155 struct apfs_query *query = NULL;
1156 int toc_size, toc_entry_size;
1157 int err;
1158 int i;
1159
1160 dest_raw = (void *)dest_node->object.data;
1161 src_raw = (void *)src_node->object.data;
1162
1163 ASSERT(!dest_node->records);
1164 apfs_assert_in_transaction(sb, &dest_raw->btn_o);
1165
1166 /* Resize the table of contents so that all the records fit */
1167 if (apfs_node_has_fixed_kv_size(src_node))
1168 toc_entry_size = sizeof(struct apfs_kvoff);
1169 else
1170 toc_entry_size = sizeof(struct apfs_kvloc);
1171 toc_size = apfs_node_min_table_size(sb, src_node->tree_type, src_node->flags);
1172 if (toc_size < toc_entry_size * (end - start))
1173 toc_size = toc_entry_size * round_up(end - start, APFS_BTREE_TOC_ENTRY_INCREMENT);
1174 dest_node->key = sizeof(*dest_raw) + toc_size;
1175 dest_node->free = dest_node->key;
1176 dest_node->val = sb->s_blocksize;
1177 if (apfs_node_is_root(dest_node))
1178 dest_node->val -= sizeof(struct apfs_btree_info);
1179
1180 /* We'll use a temporary query structure to move the records around */
1181 query = apfs_alloc_query(dest_node, NULL /* parent */);
1182 if (!query) {
1183 err = -ENOMEM;
1184 goto fail;
1185 }
1186
1187 err = -EFSCORRUPTED;
1188 for (i = start; i < end; ++i) {
1189 int len, off;
1190
1191 len = apfs_node_locate_key(src_node, i, &off);
1192 if (dest_node->free + len > sb->s_blocksize) {
1193 apfs_err(sb, "key of length %d doesn't fit", len);
1194 goto fail;
1195 }
1196 memcpy((char *)dest_raw + dest_node->free,
1197 (char *)src_raw + off, len);
1198 query->key_off = dest_node->free;
1199 query->key_len = len;
1200 dest_node->free += len;
1201
1202 len = apfs_node_locate_value(src_node, i, &off);
1203 dest_node->val -= len;
1204 if (dest_node->val < 0) {
1205 apfs_err(sb, "value of length %d doesn't fit", len);
1206 goto fail;
1207 }
1208 memcpy((char *)dest_raw + dest_node->val,
1209 (char *)src_raw + off, len);
1210 query->off = dest_node->val;
1211 query->len = len;
1212
1213 query->index = i - start;
1214 apfs_create_toc_entry(query);
1215 }
1216 err = 0;
1217
1218 fail:
1219 apfs_free_query(query);
1220 return err;
1221 }
1222
1223 /**
1224 * apfs_attach_child - Attach a new node to its parent
1225 * @query: query pointing to the previous record in the parent
1226 * @child: the new child node to attach
1227 *
1228 * Returns 0 on success or a negative error code in case of failure (which may
1229 * be -EAGAIN if a node split has happened and the caller must refresh and
1230 * retry).
1231 */
1232 static int apfs_attach_child(struct apfs_query *query, struct apfs_node *child)
1233 {
1234 struct apfs_object *object = &child->object;
1235 struct apfs_btree_node_phys *raw = (void *)object->data;
1236 int key_len, key_off;
1237 __le64 raw_oid = cpu_to_le64(object->oid);
1238
1239 key_len = apfs_node_locate_key(child, 0, &key_off);
1240 if (!key_len) {
1241 /* This should never happen: @child was made by us */
1242 apfs_alert(object->sb, "bad key for index %d", 0);
1243 return -EFSCORRUPTED;
1244 }
1245
1246 return __apfs_btree_insert(query, (void *)raw + key_off, key_len, &raw_oid, sizeof(raw_oid));
1247 }
1248
1249 /**
1250 * apfs_node_temp_dup - Make an in-memory duplicate of a node
1251 * @original: node to duplicate
1252 * @duplicate: on success, the duplicate node
1253 *
1254 * Returns 0 on success or a negative error code in case of failure.
1255 */
1256 static int apfs_node_temp_dup(const struct apfs_node *original, struct apfs_node **duplicate)
1257 {
1258 struct super_block *sb = original->object.sb;
1259 struct apfs_node *dup = NULL;
1260 char *buffer = NULL;
1261
1262 dup = kmalloc(sizeof(*dup), GFP_KERNEL);
1263 if (!dup)
1264 return -ENOMEM;
1265 *dup = *original;
1266 dup->object.o_bh = NULL;
1267 dup->object.data = NULL;
1268 dup->object.ephemeral = false;
1269
1270 buffer = kmalloc(sb->s_blocksize, GFP_KERNEL);
1271 if (!buffer) {
1272 kfree(dup);
1273 return -ENOMEM;
1274 }
1275 memcpy(buffer, original->object.data, sb->s_blocksize);
1276 dup->object.data = buffer;
1277
1278 *duplicate = dup;
1279 return 0;
1280 }
1281
1282 /**
1283 * apfs_node_split - Split a b-tree node in two
1284 * @query: query pointing to the node
1285 *
1286 * On success returns 0, and @query is left pointing to the same record on the
1287 * tip; to simplify the implementation, @query->parent is set to NULL. Returns
1288 * a negative error code in case of failure, which may be -EAGAIN if a node
1289 * split has happened and the caller must refresh and retry.
1290 */
1291 int apfs_node_split(struct apfs_query *query)
1292 {
1293 struct super_block *sb = query->node->object.sb;
1294 struct apfs_node *old_node = NULL, *new_node = NULL, *tmp_node = NULL;
1295 struct apfs_btree_node_phys *new_raw = NULL, *old_raw = NULL;
1296 u32 storage = apfs_query_storage(query);
1297 int record_count, new_rec_count, old_rec_count;
1298 int err;
1299
1300 apfs_assert_query_is_valid(query);
1301
1302 if (apfs_node_is_root(query->node)) {
1303 err = apfs_btree_inc_height(query);
1304 if (err) {
1305 apfs_err(sb, "failed to increase tree height");
1306 return err;
1307 }
1308 } else if (!query->parent) {
1309 apfs_err(sb, "nonroot node with no parent");
1310 return -EFSCORRUPTED;
1311 }
1312 old_node = query->node;
1313
1314 old_raw = (void *)old_node->object.data;
1315 apfs_assert_in_transaction(sb, &old_raw->btn_o);
1316
1317 /*
1318 * To defragment the original node, we put all records in a temporary
1319 * in-memory node before dealing them out.
1320 */
1321 err = apfs_node_temp_dup(old_node, &tmp_node);
1322 if (err)
1323 return err;
1324
1325 record_count = old_node->records;
1326 if (record_count == 1) {
1327 apfs_alert(sb, "splitting node with a single record");
1328 err = -EFSCORRUPTED;
1329 goto out;
1330 }
1331 new_rec_count = record_count / 2;
1332 old_rec_count = record_count - new_rec_count;
1333
1334 /*
1335 * The second half of the records go into a new node. This is done
1336 * before the first half to avoid committing to any actual changes
1337 * until we know for sure that no ancestor splits are expected.
1338 */
1339
1340 new_node = apfs_create_node(sb, storage);
1341 if (IS_ERR(new_node)) {
1342 apfs_err(sb, "node creation failed");
1343 err = PTR_ERR(new_node);
1344 new_node = NULL;
1345 goto out;
1346 }
1347 new_node->tree_type = old_node->tree_type;
1348 new_node->flags = old_node->flags;
1349 new_node->records = 0;
1350 new_node->key_free_list_len = 0;
1351 new_node->val_free_list_len = 0;
1352 err = apfs_copy_record_range(new_node, tmp_node, old_rec_count, record_count);
1353 if (err) {
1354 apfs_err(sb, "record copy failed");
1355 goto out;
1356 }
1357 new_raw = (void *)new_node->object.data;
1358 apfs_assert_in_transaction(sb, &new_raw->btn_o);
1359 new_raw->btn_level = old_raw->btn_level;
1360 apfs_update_node(new_node);
1361
1362 err = apfs_attach_child(query->parent, new_node);
1363 if (err) {
1364 if (err != -EAGAIN) {
1365 apfs_err(sb, "child attachment failed");
1366 goto out;
1367 }
1368 err = apfs_delete_node(new_node, query->flags & APFS_QUERY_TREE_MASK);
1369 if (err) {
1370 apfs_err(sb, "node cleanup failed for query retry");
1371 goto out;
1372 }
1373 err = -EAGAIN;
1374 goto out;
1375 }
1376 apfs_assert_query_is_valid(query->parent);
1377 apfs_btree_change_node_count(query->parent, 1 /* change */);
1378
1379 /*
1380 * No more risk of ancestor splits, now actual changes can be made. The
1381 * first half of the records go into the original node.
1382 */
1383
1384 old_node->records = 0;
1385 old_node->key_free_list_len = 0;
1386 old_node->val_free_list_len = 0;
1387 err = apfs_copy_record_range(old_node, tmp_node, 0, old_rec_count);
1388 if (err) {
1389 apfs_err(sb, "record copy failed");
1390 goto out;
1391 }
1392 apfs_update_node(old_node);
1393
1394 /* Point the query back to the original record */
1395 if (query->index >= old_rec_count) {
1396 /* The record got moved to the new node */
1397 apfs_node_free(query->node);
1398 query->node = new_node;
1399 new_node = NULL;
1400 query->index -= old_rec_count;
1401 }
1402
1403 /*
1404 * This could be avoided in most cases, and queries could get refreshed
1405 * only when really orphaned. But refreshing queries is probably not a
1406 * bottleneck, and trying to be clever with this stuff has caused me a
1407 * lot of trouble already.
1408 */
1409 apfs_free_query(query->parent);
1410 query->parent = NULL; /* The caller only gets the leaf */
1411
1412 out:
1413 apfs_node_free(new_node);
1414 apfs_node_free(tmp_node);
1415 return err;
1416 }
1417
1418 /* TODO: the following 4 functions could be reused elsewhere */
1419
1420 /**
1421 * apfs_off_to_val_off - Translate offset in node to offset in value area
1422 * @node: the node
1423 * @off: offset in the node
1424 */
1425 static u16 apfs_off_to_val_off(struct apfs_node *node, u16 off)
1426 {
1427 struct super_block *sb = node->object.sb;
1428 u16 val_end;
1429
1430 val_end = sb->s_blocksize;
1431 if (apfs_node_is_root(node)) /* has footer */
1432 val_end -= sizeof(struct apfs_btree_info);
1433 return val_end - off;
1434 }
1435
1436 /**
1437 * apfs_val_off_to_off - Translate offset in value area to offset in node
1438 * @node: the node
1439 * @off: offset in the value area
1440 */
1441 static u16 apfs_val_off_to_off(struct apfs_node *node, u16 off)
1442 {
1443 return apfs_off_to_val_off(node, off);
1444 }
1445
1446 /**
1447 * apfs_off_to_key_off - Translate offset in node to offset in key area
1448 * @node: the node
1449 * @off: offset in the node
1450 */
1451 static u16 apfs_off_to_key_off(struct apfs_node *node, u16 off)
1452 {
1453 return off - node->key;
1454 }
1455
1456 /**
1457 * apfs_key_off_to_off - Translate offset in key area to offset in node
1458 * @node: the node
1459 * @off: offset in the key area
1460 */
1461 static u16 apfs_key_off_to_off(struct apfs_node *node, u16 off)
1462 {
1463 return off + node->key;
1464 }
1465
1466 /* The type of the previous four functions, used for node offset calculations */
1467 typedef u16 (*offcalc)(struct apfs_node *, u16);
1468
1469 /**
1470 * apfs_node_free_list_add - Add a free node segment to the proper free list
1471 * @node: node for the segment
1472 * @off: offset of the segment to add
1473 * @len: length of the segment to add
1474 *
1475 * The caller must ensure that the freed segment fits in the node.
1476 */
1477 static void apfs_node_free_list_add(struct apfs_node *node, u16 off, u16 len)
1478 {
1479 struct super_block *sb = node->object.sb;
1480 struct apfs_btree_node_phys *node_raw = (void *)node->object.data;
1481 struct apfs_nloc *head, *new;
1482 offcalc off_to_rel;
1483
1484 apfs_assert_in_transaction(sb, &node_raw->btn_o);
1485
1486 if (off >= node->val) { /* Value area */
1487 off_to_rel = apfs_off_to_val_off;
1488 head = &node_raw->btn_val_free_list;
1489 node->val_free_list_len += len;
1490 } else { /* Key area */
1491 off_to_rel = apfs_off_to_key_off;
1492 head = &node_raw->btn_key_free_list;
1493 node->key_free_list_len += len;
1494 }
1495
1496 /* Very small segments are leaked until defragmentation */
1497 if (len < sizeof(*new))
1498 return;
1499
1500 /* The free list doesn't seem to be kept in any particular order */
1501 new = (void *)node_raw + off;
1502 new->off = head->off;
1503 new->len = cpu_to_le16(len);
1504 head->off = cpu_to_le16(off_to_rel(node, off));
1505 }
1506
1507 /**
1508 * apfs_node_free_range - Free space from a node's key or value areas
1509 * @node: the node
1510 * @off: offset to free
1511 * @len: length to free
1512 *
1513 * Returns 0 on success or a negative error code in case of failure.
1514 */
1515 void apfs_node_free_range(struct apfs_node *node, u16 off, u16 len)
1516 {
1517 struct super_block *sb = node->object.sb;
1518 struct apfs_btree_node_phys *raw = (void *)node->object.data;
1519
1520 apfs_assert_in_transaction(sb, &raw->btn_o);
1521
1522 if (off == node->val)
1523 node->val += len;
1524 else if (off + len == node->free)
1525 node->free -= len;
1526 else
1527 apfs_node_free_list_add(node, off, len);
1528 }
1529
1530 /**
1531 * apfs_node_free_list_unlink - Unlink an entry from a node's free list
1532 * @prev: previous entry
1533 * @curr: entry to unlink
1534 */
1535 static void apfs_node_free_list_unlink(struct apfs_nloc *prev, struct apfs_nloc *curr)
1536 {
1537 prev->off = curr->off;
1538 }
1539
1540 /**
1541 * apfs_node_free_list_alloc - Allocate a free segment from a free list
1542 * @node: the node
1543 * @len: length to allocate
1544 * @value: true to allocate in the value area, false for the key area
1545 *
1546 * Returns the offset in the node on success, or a negative error code in case
1547 * of failure, which may be -ENOSPC if the node seems full.
1548 */
1549 static int apfs_node_free_list_alloc(struct apfs_node *node, u16 len, bool value)
1550 {
1551 struct super_block *sb = node->object.sb;
1552 struct apfs_btree_node_phys *node_raw = (void *)node->object.data;
1553 struct apfs_nloc *head, *curr, *prev;
1554 offcalc rel_to_off;
1555 int *list_len;
1556 int bound = sb->s_blocksize;
1557
1558 apfs_assert_in_transaction(sb, &node_raw->btn_o);
1559
1560 if (value) { /* Value area */
1561 rel_to_off = apfs_val_off_to_off;
1562 head = &node_raw->btn_val_free_list;
1563 list_len = &node->val_free_list_len;
1564 } else { /* Key area */
1565 rel_to_off = apfs_key_off_to_off;
1566 head = &node_raw->btn_key_free_list;
1567 list_len = &node->key_free_list_len;
1568 }
1569
1570 if (*list_len < len)
1571 return -ENOSPC;
1572
1573 prev = head;
1574 while (bound--) {
1575 u16 curr_off = le16_to_cpu(prev->off);
1576 u16 abs_off = rel_to_off(node, curr_off);
1577 u16 curr_len;
1578
1579 if (curr_off == APFS_BTOFF_INVALID)
1580 return -ENOSPC;
1581 if (abs_off + sizeof(*curr) > sb->s_blocksize) {
1582 apfs_err(sb, "nloc out of bounds (%d-%d)", abs_off, (int)sizeof(*curr));
1583 return -EFSCORRUPTED;
1584 }
1585 curr = (void *)node_raw + abs_off;
1586
1587 curr_len = le16_to_cpu(curr->len);
1588 if (curr_len >= len) {
1589 if (abs_off + curr_len > sb->s_blocksize) {
1590 apfs_err(sb, "entry out of bounds (%d-%d)", abs_off, curr_len);
1591 return -EFSCORRUPTED;
1592 }
1593 *list_len -= curr_len;
1594 apfs_node_free_list_unlink(prev, curr);
1595 apfs_node_free_list_add(node, abs_off + len, curr_len - len);
1596 return abs_off;
1597 }
1598
1599 prev = curr;
1600 }
1601
1602 /* Don't loop forever if the free list is corrupted and doesn't end */
1603 apfs_err(sb, "free list never ends");
1604 return -EFSCORRUPTED;
1605 }
1606
1607 /**
1608 * apfs_node_alloc_key - Allocated free space for a new key
1609 * @node: the node to search
1610 * @len: wanted key length
1611 *
1612 * Returns the offset in the node on success, or a negative error code in case
1613 * of failure, which may be -ENOSPC if the node seems full.
1614 */
1615 static int apfs_node_alloc_key(struct apfs_node *node, u16 len)
1616 {
1617 int off;
1618
1619 if (node->free + len <= node->val) {
1620 off = node->free;
1621 node->free += len;
1622 return off;
1623 }
1624 return apfs_node_free_list_alloc(node, len, false /* value */);
1625 }
1626
1627 /**
1628 * apfs_node_alloc_val - Allocated free space for a new value
1629 * @node: the node to search
1630 * @len: wanted value length
1631 *
1632 * Returns the offset in the node on success, or a negative error code in case
1633 * of failure, which may be -ENOSPC if the node seems full.
1634 */
1635 static int apfs_node_alloc_val(struct apfs_node *node, u16 len)
1636 {
1637 int off;
1638
1639 if (node->free + len <= node->val) {
1640 off = node->val - len;
1641 node->val -= len;
1642 return off;
1643 }
1644 return apfs_node_free_list_alloc(node, len, true /* value */);
1645 }
1646
1647 /**
1648 * apfs_node_total_room - Total free space in a node
1649 * @node: the node
1650 */
1651 static int apfs_node_total_room(struct apfs_node *node)
1652 {
1653 return node->val - node->free + node->key_free_list_len + node->val_free_list_len;
1654 }
1655
1656 /**
1657 * apfs_node_has_room - Check if a node has room for insertion or replacement
1658 * @node: node to check
1659 * @length: length of the needed space (may be negative on replace)
1660 * @replace: are we replacing a record?
1661 */
1662 bool apfs_node_has_room(struct apfs_node *node, int length, bool replace)
1663 {
1664 struct apfs_btree_node_phys *node_raw = (void *)node->object.data;
1665 int toc_entry_size, needed_room;
1666
1667 if (apfs_node_has_fixed_kv_size(node))
1668 toc_entry_size = sizeof(struct apfs_kvoff);
1669 else
1670 toc_entry_size = sizeof(struct apfs_kvloc);
1671
1672 needed_room = length;
1673 if (!replace) {
1674 if (sizeof(*node_raw) + (node->records + 1) * toc_entry_size > node->key)
1675 needed_room += APFS_BTREE_TOC_ENTRY_INCREMENT * toc_entry_size;
1676 }
1677
1678 return apfs_node_total_room(node) >= needed_room;
1679 }
1680
1681 /**
1682 * apfs_defragment_node - Make all free space in a node contiguous
1683 * @node: node to defragment
1684 *
1685 * Returns 0 on success or a negative error code in case of failure.
1686 */
1687 static int apfs_defragment_node(struct apfs_node *node)
1688 {
1689 struct super_block *sb = node->object.sb;
1690 struct apfs_btree_node_phys *node_raw = (void *)node->object.data;
1691 struct apfs_node *tmp_node = NULL;
1692 int record_count, err;
1693
1694 apfs_assert_in_transaction(sb, &node_raw->btn_o);
1695
1696 /* Put all records in a temporary in-memory node and deal them out */
1697 err = apfs_node_temp_dup(node, &tmp_node);
1698 if (err)
1699 return err;
1700 record_count = node->records;
1701 node->records = 0;
1702 node->key_free_list_len = 0;
1703 node->val_free_list_len = 0;
1704 err = apfs_copy_record_range(node, tmp_node, 0, record_count);
1705 if (err) {
1706 apfs_err(sb, "record copy failed");
1707 goto fail;
1708 }
1709 apfs_update_node(node);
1710 fail:
1711 apfs_node_free(tmp_node);
1712 return err;
1713 }
1714
1715 /**
1716 * apfs_node_update_toc_entry - Update a table of contents entry in place
1717 * @query: query pointing to the toc entry
1718 *
1719 * The toc entry gets updated with the length and offset for the key/value
1720 * provided by @query. Don't call this function for nodes with fixed length
1721 * key/values, those never need to update their toc entries.
1722 */
1723 static void apfs_node_update_toc_entry(struct apfs_query *query)
1724 {
1725 struct super_block *sb = NULL;
1726 struct apfs_node *node = NULL;
1727 struct apfs_btree_node_phys *node_raw = NULL;
1728 struct apfs_kvloc *kvloc = NULL;
1729 int value_end;
1730
1731 node = query->node;
1732 ASSERT(!apfs_node_has_fixed_kv_size(node));
1733 sb = node->object.sb;
1734 node_raw = (void *)node->object.data;
1735
1736 value_end = sb->s_blocksize;
1737 if (apfs_node_is_root(node))
1738 value_end -= sizeof(struct apfs_btree_info);
1739
1740 kvloc = (struct apfs_kvloc *)node_raw->btn_data + query->index;
1741 kvloc->v.off = cpu_to_le16(value_end - query->off);
1742 kvloc->v.len = cpu_to_le16(query->len);
1743 kvloc->k.off = cpu_to_le16(query->key_off - node->key);
1744 kvloc->k.len = cpu_to_le16(query->key_len);
1745 }
1746
1747 /**
1748 * apfs_node_replace - Replace a record in a node that has enough room
1749 * @query: exact query that found the record
1750 * @key: new on-disk record key (NULL if unchanged)
1751 * @key_len: length of @key
1752 * @val: new on-disk record value (NULL if unchanged)
1753 * @val_len: length of @val
1754 *
1755 * Returns 0 on success, and @query is left pointing to the same record. Returns
1756 * a negative error code in case of failure.
1757 */
1758 int apfs_node_replace(struct apfs_query *query, void *key, int key_len, void *val, int val_len)
1759 {
1760 struct apfs_node *node = query->node;
1761 struct super_block *sb = node->object.sb;
1762 struct apfs_btree_node_phys *node_raw = (void *)node->object.data;
1763 int key_off = 0, val_off = 0, err = 0;
1764 bool defragged = false;
1765 int qtree = query->flags & APFS_QUERY_TREE_MASK;
1766
1767 apfs_assert_in_transaction(sb, &node_raw->btn_o);
1768
1769 /*
1770 * Free queues are weird because their tables of contents don't report
1771 * record lengths, as if they were fixed, but some of the leaf values
1772 * are actually "ghosts", that is, zero-length. Supporting replace of
1773 * such records would require some changes, and so far I've had no need
1774 * for it.
1775 */
1776 (void)qtree;
1777 ASSERT(!(qtree == APFS_QUERY_FREE_QUEUE && apfs_node_is_leaf(node)));
1778
1779 retry:
1780 if (key) {
1781 if (key_len <= query->key_len) {
1782 u16 end = query->key_off + key_len;
1783 u16 diff = query->key_len - key_len;
1784
1785 apfs_node_free_range(node, end, diff);
1786 key_off = query->key_off;
1787 } else {
1788 apfs_node_free_range(node, query->key_off, query->key_len);
1789 key_off = apfs_node_alloc_key(node, key_len);
1790 if (key_off < 0) {
1791 if (key_off == -ENOSPC)
1792 goto defrag;
1793 return key_off;
1794 }
1795 }
1796 }
1797
1798 if (val) {
1799 if (val_len <= query->len) {
1800 u16 end = query->off + val_len;
1801 u16 diff = query->len - val_len;
1802
1803 apfs_node_free_range(node, end, diff);
1804 val_off = query->off;
1805 } else {
1806 apfs_node_free_range(node, query->off, query->len);
1807 val_off = apfs_node_alloc_val(node, val_len);
1808 if (val_off < 0) {
1809 if (val_off == -ENOSPC)
1810 goto defrag;
1811 return val_off;
1812 }
1813 }
1814 }
1815
1816 if (key) {
1817 query->key_off = key_off;
1818 query->key_len = key_len;
1819 memcpy((void *)node_raw + key_off, key, key_len);
1820 }
1821 if (val) {
1822 query->off = val_off;
1823 query->len = val_len;
1824 memcpy((void *)node_raw + val_off, val, val_len);
1825 }
1826
1827 /* If the key or value were resized, update the table of contents */
1828 if (!apfs_node_has_fixed_kv_size(node))
1829 apfs_node_update_toc_entry(query);
1830
1831 apfs_update_node(node);
1832 return 0;
1833
1834 defrag:
1835 if (defragged) {
1836 apfs_alert(sb, "no room in defragged node");
1837 return -EFSCORRUPTED;
1838 }
1839
1840 /* Crush the replaced entry, so that defragmentation is complete */
1841 if (apfs_node_has_fixed_kv_size(node)) {
1842 apfs_alert(sb, "failed to replace a fixed size record");
1843 return -EFSCORRUPTED;
1844 }
1845 if (key)
1846 query->key_len = 0;
1847 if (val)
1848 query->len = 0;
1849 apfs_node_update_toc_entry(query);
1850
1851 err = apfs_defragment_node(node);
1852 if (err) {
1853 apfs_err(sb, "failed to defragment node");
1854 return err;
1855 }
1856 defragged = true;
1857
1858 /* The record to replace probably moved around */
1859 query->len = apfs_node_locate_value(query->node, query->index, &query->off);
1860 query->key_len = apfs_node_locate_key(query->node, query->index, &query->key_off);
1861 goto retry;
1862 }
1863
1864 /**
1865 * apfs_node_insert - Insert a new record in a node that has enough room
1866 * @query: query run to search for the record
1867 * @key: on-disk record key
1868 * @key_len: length of @key
1869 * @val: on-disk record value (NULL for ghost records)
1870 * @val_len: length of @val (0 for ghost records)
1871 *
1872 * The new record is placed right after the one found by @query. On success,
1873 * returns 0 and sets @query to the new record. In case of failure, returns a
1874 * negative error code and leaves @query pointing to the same record.
1875 */
1876 int apfs_node_insert(struct apfs_query *query, void *key, int key_len, void *val, int val_len)
1877 {
1878 struct apfs_node *node = query->node;
1879 struct super_block *sb = node->object.sb;
1880 struct apfs_btree_node_phys *node_raw = (void *)node->object.data;
1881 int toc_entry_size;
1882 int key_off, val_off, err;
1883 bool defragged = false;
1884
1885 apfs_assert_in_transaction(sb, &node_raw->btn_o);
1886
1887 retry:
1888 if (apfs_node_has_fixed_kv_size(node))
1889 toc_entry_size = sizeof(struct apfs_kvoff);
1890 else
1891 toc_entry_size = sizeof(struct apfs_kvloc);
1892
1893 /* Expand the table of contents if necessary */
1894 if (sizeof(*node_raw) + (node->records + 1) * toc_entry_size > node->key) {
1895 int new_key_base = node->key;
1896 int new_free_base = node->free;
1897 int inc;
1898
1899 inc = APFS_BTREE_TOC_ENTRY_INCREMENT * toc_entry_size;
1900
1901 new_key_base += inc;
1902 new_free_base += inc;
1903 if (new_free_base > node->val)
1904 goto defrag;
1905 memmove((void *)node_raw + new_key_base,
1906 (void *)node_raw + node->key, node->free - node->key);
1907
1908 node->key = new_key_base;
1909 node->free = new_free_base;
1910 query->key_off += inc;
1911 }
1912
1913 key_off = apfs_node_alloc_key(node, key_len);
1914 if (key_off < 0) {
1915 if (key_off == -ENOSPC)
1916 goto defrag;
1917 return key_off;
1918 }
1919
1920 if (val) {
1921 val_off = apfs_node_alloc_val(node, val_len);
1922 if (val_off < 0) {
1923 if (val_off == -ENOSPC) {
1924 /*
1925 * There is no need for an update of the on-disk
1926 * node before the defrag, since only in-memory
1927 * data should be used there...
1928 */
1929 goto defrag;
1930 }
1931 return val_off;
1932 }
1933 }
1934
1935 query->key_len = key_len;
1936 query->key_off = key_off;
1937 memcpy((void *)node_raw + key_off, key, key_len);
1938
1939 query->len = val_len;
1940 if (val) {
1941 query->off = val_off;
1942 memcpy((void *)node_raw + val_off, val, val_len);
1943 } else {
1944 query->off = 0;
1945 }
1946
1947 query->index++; /* The query returned the record right before @key */
1948
1949 /* Add the new entry to the table of contents */
1950 apfs_create_toc_entry(query);
1951
1952 apfs_update_node(node);
1953 return 0;
1954
1955 defrag:
1956 if (defragged) {
1957 apfs_err(sb, "node reports incorrect free space");
1958 return -EFSCORRUPTED;
1959 }
1960 err = apfs_defragment_node(node);
1961 if (err) {
1962 apfs_err(sb, "failed to defragment node");
1963 return err;
1964 }
1965 defragged = true;
1966 goto retry;
1967 }
1968
1969 /**
1970 * apfs_create_single_rec_node - Creates a new node with a single record
1971 * @query: query run to search for the record
1972 * @key: on-disk record key
1973 * @key_len: length of @key
1974 * @val: on-disk record value
1975 * @val_len: length of @val
1976 *
1977 * The new node is placed right after the one found by @query, which must have
1978 * a single record. On success, returns 0 and sets @query to the new record;
1979 * returns a negative error code in case of failure, which may be -EAGAIN if a
1980 * node split has happened and the caller must refresh and retry.
1981 */
1982 int apfs_create_single_rec_node(struct apfs_query *query, void *key, int key_len, void *val, int val_len)
1983 {
1984 struct super_block *sb = NULL;
1985 struct apfs_node *new_node = NULL, *prev_node = NULL;
1986 struct apfs_btree_node_phys *prev_raw = NULL;
1987 struct apfs_btree_node_phys *new_raw = NULL;
1988 int err;
1989
1990 prev_node = query->node;
1991 sb = prev_node->object.sb;
1992
1993 ASSERT(query->parent);
1994 ASSERT(prev_node->records == 1);
1995 ASSERT(val && val_len);
1996
1997 /* This function should only be needed for huge catalog records */
1998 if (prev_node->tree_type != APFS_OBJECT_TYPE_FSTREE) {
1999 apfs_err(sb, "huge node records in the wrong tree");
2000 return -EFSCORRUPTED;
2001 }
2002
2003 /*
2004 * This will only be called for leaf nodes because it's the values that
2005 * can get huge, not the keys. It will also never be called for root,
2006 * because the catalog always has more than a single record.
2007 */
2008 if (apfs_node_is_root(prev_node) || !apfs_node_is_leaf(prev_node)) {
2009 apfs_err(sb, "huge record in index node");
2010 return -EFSCORRUPTED;
2011 }
2012
2013 new_node = apfs_create_node(sb, apfs_query_storage(query));
2014 if (IS_ERR(new_node)) {
2015 apfs_err(sb, "node creation failed");
2016 return PTR_ERR(new_node);
2017 }
2018 new_node->tree_type = prev_node->tree_type;
2019 new_node->flags = prev_node->flags;
2020 new_node->records = 0;
2021 new_node->key_free_list_len = 0;
2022 new_node->val_free_list_len = 0;
2023 new_node->key = new_node->free = sizeof(*new_raw);
2024 new_node->val = sb->s_blocksize; /* Nonroot */
2025
2026 prev_raw = (void *)prev_node->object.data;
2027 new_raw = (void *)new_node->object.data;
2028 apfs_assert_in_transaction(sb, &new_raw->btn_o);
2029 new_raw->btn_level = prev_raw->btn_level;
2030 apfs_update_node(new_node);
2031
2032 query->node = new_node;
2033 new_node = NULL;
2034 query->index = -1;
2035 err = apfs_node_insert(query, key, key_len, val, val_len);
2036 if (err) {
2037 apfs_err(sb, "node record insertion failed");
2038 goto fail;
2039 }
2040
2041 err = apfs_attach_child(query->parent, query->node);
2042 if (err) {
2043 if (err != -EAGAIN) {
2044 apfs_err(sb, "child attachment failed");
2045 goto fail;
2046 }
2047 err = apfs_delete_node(query->node, query->flags & APFS_QUERY_TREE_MASK);
2048 if (err) {
2049 apfs_err(sb, "node cleanup failed for query retry");
2050 goto fail;
2051 }
2052
2053 /*
2054 * The query must remain pointing to the original node for the
2055 * refresh to take place. The index will not matter though.
2056 */
2057 new_node = query->node;
2058 query->node = prev_node;
2059 prev_node = NULL;
2060 err = -EAGAIN;
2061 goto fail;
2062 }
2063 apfs_btree_change_node_count(query->parent, 1 /* change */);
2064
2065 fail:
2066 apfs_node_free(prev_node);
2067 apfs_node_free(new_node);
2068 return err;
2069 }