Debian Codegraph @

spaceman.c

raw symbols SCIP
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * Copyright (C) 2019 Ernesto A. Fernández <[email protected]>
4 */
5
6 #include <linux/buffer_head.h>
7 #include <linux/fs.h>
8 #include <linux/slab.h>
9 #include "apfs.h"
10
11 /**
12 * apfs_spaceman_read_cib_addr - Get the address of a cib from the spaceman
13 * @sb: superblock structure
14 * @index: index of the chunk-info block
15 *
16 * Returns the block number for the chunk-info block.
17 *
18 * This is not described in the official documentation; credit for figuring it
19 * out should go to Joachim Metz: <https://github.com/libyal/libfsapfs>.
20 */
21 static u64 apfs_spaceman_read_cib_addr(struct super_block *sb, int index)
22 {
23 struct apfs_spaceman *sm = APFS_SM(sb);
24 struct apfs_spaceman_phys *sm_raw = sm->sm_raw;
25 u32 offset;
26 __le64 *addr_p;
27
28 offset = sm->sm_addr_offset + index * sizeof(*addr_p);
29 addr_p = (void *)sm_raw + offset;
30 return le64_to_cpup(addr_p);
31 }
32
33 /**
34 * apfs_spaceman_write_cib_addr - Store the address of a cib in the spaceman
35 * @sb: superblock structure
36 * @index: index of the chunk-info block
37 * @addr: address of the chunk-info block
38 */
39 static void apfs_spaceman_write_cib_addr(struct super_block *sb,
40 int index, u64 addr)
41 {
42 struct apfs_spaceman *sm = APFS_SM(sb);
43 struct apfs_spaceman_phys *sm_raw = sm->sm_raw;
44 u32 offset;
45 __le64 *addr_p;
46
47 apfs_assert_in_transaction(sb, &sm_raw->sm_o);
48
49 offset = sm->sm_addr_offset + index * sizeof(*addr_p);
50 addr_p = (void *)sm_raw + offset;
51 *addr_p = cpu_to_le64(addr);
52 }
53
54 /**
55 * apfs_max_chunks_per_cib - Find the maximum chunk count for a chunk-info block
56 * @sb: superblock structure
57 */
58 static inline int apfs_max_chunks_per_cib(struct super_block *sb)
59 {
60 return (sb->s_blocksize - sizeof(struct apfs_chunk_info_block)) /
61 sizeof(struct apfs_chunk_info);
62 }
63
64 /**
65 * apfs_read_spaceman_dev - Read a space manager device structure
66 * @sb: superblock structure
67 * @dev: on-disk device structure
68 *
69 * Initializes the in-memory spaceman fields related to the main device; fusion
70 * drives are not yet supported. Returns 0 on success, or a negative error code
71 * in case of failure.
72 */
73 static int apfs_read_spaceman_dev(struct super_block *sb,
74 struct apfs_spaceman_device *dev)
75 {
76 struct apfs_spaceman *spaceman = APFS_SM(sb);
77
78 if (dev->sm_cab_count) {
79 apfs_err(sb, "large devices are not supported");
80 return -EINVAL;
81 }
82
83 spaceman->sm_block_count = le64_to_cpu(dev->sm_block_count);
84 spaceman->sm_chunk_count = le64_to_cpu(dev->sm_chunk_count);
85 spaceman->sm_cib_count = le32_to_cpu(dev->sm_cib_count);
86 spaceman->sm_free_count = le64_to_cpu(dev->sm_free_count);
87 spaceman->sm_addr_offset = le32_to_cpu(dev->sm_addr_offset);
88
89 /* Check that all the cib addresses fit in the spaceman object */
90 if ((long long)spaceman->sm_addr_offset +
91 (long long)spaceman->sm_cib_count * sizeof(u64) > spaceman->sm_size) {
92 apfs_err(sb, "too many cibs (%u)", spaceman->sm_cib_count);
93 return -EFSCORRUPTED;
94 }
95
96 return 0;
97 }
98
99 /**
100 * apfs_spaceman_get_16 - Get a 16-bit value from an offset in the spaceman
101 * @sb: superblock structure
102 * @off: offset for the value
103 *
104 * Returns a pointer to the value, or NULL if it doesn't fit.
105 */
106 static __le16 *apfs_spaceman_get_16(struct super_block *sb, size_t off)
107 {
108 struct apfs_spaceman *spaceman = APFS_SM(sb);
109 struct apfs_spaceman_phys *sm_raw = spaceman->sm_raw;
110
111 if (off > spaceman->sm_size)
112 return NULL;
113 if (off + sizeof(__le16) > spaceman->sm_size)
114 return NULL;
115 return (void *)sm_raw + off;
116 }
117
118 /**
119 * apfs_spaceman_get_64 - Get a 64-bit value from an offset in the spaceman
120 * @sb: superblock structure
121 * @off: offset for the value
122 *
123 * Returns a pointer to the value, or NULL if it doesn't fit.
124 */
125 static __le64 *apfs_spaceman_get_64(struct super_block *sb, size_t off)
126 {
127 struct apfs_spaceman *spaceman = APFS_SM(sb);
128 struct apfs_spaceman_phys *sm_raw = spaceman->sm_raw;
129
130 if (off > spaceman->sm_size)
131 return NULL;
132 if (off + sizeof(__le64) > spaceman->sm_size)
133 return NULL;
134 return (void *)sm_raw + off;
135 }
136
137 /**
138 * apfs_allocate_ip_bitmap - Allocate a free ip bitmap block
139 * @sb: filesystem superblock
140 * @offset_p: on return, the offset from sm_ip_bm_base of the allocated block
141 *
142 * Returns 0 on success or a negative error code in case of failure.
143 */
144 static int apfs_allocate_ip_bitmap(struct super_block *sb, u16 *offset_p)
145 {
146 struct apfs_spaceman *spaceman = NULL;
147 struct apfs_spaceman_phys *sm_raw = NULL;
148 u32 free_next_offset, old_head_off;
149 u16 free_head, blkcnt;
150 __le16 *old_head_p = NULL;
151
152 spaceman = APFS_SM(sb);
153 sm_raw = spaceman->sm_raw;
154 free_next_offset = le32_to_cpu(sm_raw->sm_ip_bm_free_next_offset);
155 free_head = le16_to_cpu(sm_raw->sm_ip_bm_free_head);
156 blkcnt = (u16)le32_to_cpu(sm_raw->sm_ip_bm_block_count);
157
158 /*
159 * The "free_next" array is a linked list of free blocks that starts
160 * with the "free_head". Allocate this head then, and make the next
161 * block into the new head.
162 */
163 old_head_off = free_next_offset + free_head * sizeof(*old_head_p);
164 old_head_p = apfs_spaceman_get_16(sb, old_head_off);
165 if (!old_head_p) {
166 apfs_err(sb, "free_next head offset out of bounds (%u)", old_head_off);
167 return -EFSCORRUPTED;
168 }
169 *offset_p = free_head;
170 free_head = le16_to_cpup(old_head_p);
171 sm_raw->sm_ip_bm_free_head = *old_head_p;
172 /* No longer free, no longer part of the linked list */
173 *old_head_p = cpu_to_le16(APFS_SPACEMAN_IP_BM_INDEX_INVALID);
174
175 /* Just a little sanity check because I've messed this up before */
176 if (free_head >= blkcnt || *offset_p >= blkcnt) {
177 apfs_err(sb, "free next list seems empty or corrupt");
178 return -EFSCORRUPTED;
179 }
180
181 return 0;
182 }
183
184 /**
185 * apfs_free_ip_bitmap - Free a used ip bitmap block
186 * @sb: filesystem superblock
187 * @offset: the offset from sm_ip_bm_base of the block to free
188 *
189 * Returns 0 on success or a negative error code in case of failure.
190 */
191 static int apfs_free_ip_bitmap(struct super_block *sb, u16 offset)
192 {
193 struct apfs_spaceman *spaceman = NULL;
194 struct apfs_spaceman_phys *sm_raw = NULL;
195 u32 free_next_offset, old_tail_off;
196 u16 free_tail;
197 __le16 *old_tail_p = NULL;
198
199 spaceman = APFS_SM(sb);
200 sm_raw = spaceman->sm_raw;
201 free_next_offset = le32_to_cpu(sm_raw->sm_ip_bm_free_next_offset);
202 free_tail = le16_to_cpu(sm_raw->sm_ip_bm_free_tail);
203
204 /*
205 * The "free_next" array is a linked list of free blocks that ends
206 * with the "free_tail". The block getting freed will become the new
207 * tail of the list.
208 */
209 old_tail_off = free_next_offset + free_tail * sizeof(*old_tail_p);
210 old_tail_p = apfs_spaceman_get_16(sb, old_tail_off);
211 if (!old_tail_p) {
212 apfs_err(sb, "free_next tail offset out of bounds (%u)", old_tail_off);
213 return -EFSCORRUPTED;
214 }
215 *old_tail_p = cpu_to_le16(offset);
216 sm_raw->sm_ip_bm_free_tail = cpu_to_le16(offset);
217 free_tail = offset;
218
219 return 0;
220 }
221
222 /**
223 * apfs_reallocate_ip_bitmap - Find a new block for an ip bitmap
224 * @sb: filesystem superblock
225 * @offset_p: the offset from sm_ip_bm_base of the block to free
226 *
227 * On success returns 0 and updates @offset_p to the new offset allocated for
228 * the ip bitmap. Since blocks are allocated at the head of the list and freed
229 * at the tail, there is no risk of reuse by future reallocations within the
230 * same transaction (under there is some serious corruption, of course).
231 *
232 * Returns a negative error code in case of failure.
233 */
234 static int apfs_reallocate_ip_bitmap(struct super_block *sb, __le16 *offset_p)
235 {
236 int err;
237 u16 offset;
238
239 offset = le16_to_cpup(offset_p);
240
241 err = apfs_free_ip_bitmap(sb, offset);
242 if (err) {
243 apfs_err(sb, "failed to free ip bitmap %u", offset);
244 return err;
245 }
246 err = apfs_allocate_ip_bitmap(sb, &offset);
247 if (err) {
248 apfs_err(sb, "failed to allocate a new ip bitmap block");
249 return err;
250 }
251
252 *offset_p = cpu_to_le16(offset);
253 return 0;
254 }
255
256 /**
257 * apfs_write_single_ip_bitmap - Write a single ip bitmap to disk
258 * @sb: filesystem superblock
259 * @bitmap: bitmap to write
260 * @idx: index of the ip bitmap to write
261 *
262 * Returns 0 on success or a negative error code in case of failure.
263 */
264 static int apfs_write_single_ip_bitmap(struct super_block *sb, char *bitmap, u32 idx)
265 {
266 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
267 struct apfs_spaceman *spaceman = APFS_SM(sb);
268 struct apfs_spaceman_phys *sm_raw = spaceman->sm_raw;
269 struct buffer_head *bh = NULL;
270 u64 ip_bm_base, ip_bitmap_bno;
271 u32 xid_off, ip_bitmap_off;
272 __le64 *xid_p = NULL;
273 __le16 *ip_bitmap_p = NULL;
274 int err;
275
276 ip_bm_base = le64_to_cpu(sm_raw->sm_ip_bm_base);
277
278 /* First update the xid, which is kept in a separate array */
279 xid_off = le32_to_cpu(sm_raw->sm_ip_bm_xid_offset) + idx * sizeof(*xid_p);
280 xid_p = apfs_spaceman_get_64(sb, xid_off);
281 if (!xid_p) {
282 apfs_err(sb, "xid out of bounds (%u)", xid_off);
283 return -EFSCORRUPTED;
284 }
285 *xid_p = cpu_to_le64(nxi->nx_xid);
286
287 /* Now get find new location for the ip bitmap (and free the old one) */
288 ip_bitmap_off = le32_to_cpu(sm_raw->sm_ip_bitmap_offset) + idx * sizeof(*ip_bitmap_p);
289 ip_bitmap_p = apfs_spaceman_get_16(sb, ip_bitmap_off);
290 if (!ip_bitmap_p) {
291 apfs_err(sb, "bmap offset out of bounds (%u)", ip_bitmap_off);
292 return -EFSCORRUPTED;
293 }
294 err = apfs_reallocate_ip_bitmap(sb, ip_bitmap_p);
295 if (err) {
296 apfs_err(sb, "failed to reallocate ip bitmap %u", le16_to_cpup(ip_bitmap_p));
297 return err;
298 }
299
300 /* Finally, write the dirty bitmap to the new location */
301 ip_bitmap_bno = ip_bm_base + le16_to_cpup(ip_bitmap_p);
302 bh = apfs_getblk(sb, ip_bitmap_bno);
303 if (!bh) {
304 apfs_err(sb, "failed to map block for CoW (0x%llx)", ip_bitmap_bno);
305 return -EIO;
306 }
307 memcpy(bh->b_data, bitmap, sb->s_blocksize);
308 err = apfs_transaction_join(sb, bh);
309 if (err)
310 goto fail;
311 bh = NULL;
312
313 spaceman->sm_ip_bmaps[idx].dirty = false;
314 return 0;
315
316 fail:
317 brelse(bh);
318 bh = NULL;
319 return err;
320 }
321
322 /**
323 * apfs_write_ip_bitmaps - Write all dirty ip bitmaps to disk
324 * @sb: superblock structure
325 *
326 * Returns 0 on success or a negative error code in case of failure.
327 */
328 int apfs_write_ip_bitmaps(struct super_block *sb)
329 {
330 struct apfs_spaceman *spaceman = APFS_SM(sb);
331 struct apfs_spaceman_phys *sm_raw = spaceman->sm_raw;
332 struct apfs_ip_bitmap_block_info *info = NULL;
333 u32 bmaps_count = spaceman->sm_ip_bmaps_count;
334 int err;
335 u32 i;
336
337 apfs_assert_in_transaction(sb, &sm_raw->sm_o);
338
339 for (i = 0; i < bmaps_count; ++i) {
340 info = &spaceman->sm_ip_bmaps[i];
341 if (!info->dirty)
342 continue;
343 err = apfs_write_single_ip_bitmap(sb, info->block, i);
344 if (err) {
345 apfs_err(sb, "failed to rotate ip bitmap %u", i);
346 return err;
347 }
348 }
349 return 0;
350 }
351
352 /**
353 * apfs_read_single_ip_bitmap - Read a single ip bitmap to memory
354 * @sb: filesystem superblock
355 * @idx: index of the ip bitmap to read
356 *
357 * Returns 0 on success or a negative error code in case of failure.
358 */
359 static int apfs_read_single_ip_bitmap(struct super_block *sb, u32 idx)
360 {
361 struct apfs_spaceman *spaceman = APFS_SM(sb);
362 struct apfs_spaceman_phys *sm_raw = spaceman->sm_raw;
363 struct buffer_head *bh = NULL;
364 char *bitmap = NULL;
365 u64 ip_bm_base, ip_bitmap_bno;
366 u32 ip_bitmap_off;
367 __le16 *ip_bitmap_p = NULL;
368 int err;
369
370 ip_bm_base = le64_to_cpu(sm_raw->sm_ip_bm_base);
371
372 ip_bitmap_off = le32_to_cpu(sm_raw->sm_ip_bitmap_offset) + idx * sizeof(*ip_bitmap_p);
373 ip_bitmap_p = apfs_spaceman_get_16(sb, ip_bitmap_off);
374 if (!ip_bitmap_p) {
375 apfs_err(sb, "bmap offset out of bounds (%u)", ip_bitmap_off);
376 return -EFSCORRUPTED;
377 }
378
379 bitmap = kmalloc(sb->s_blocksize, GFP_KERNEL);
380 if (!bitmap)
381 return -ENOMEM;
382
383 ip_bitmap_bno = ip_bm_base + le16_to_cpup(ip_bitmap_p);
384 bh = apfs_sb_bread(sb, ip_bitmap_bno);
385 if (!bh) {
386 apfs_err(sb, "failed to read ip bitmap (0x%llx)", ip_bitmap_bno);
387 err = -EIO;
388 goto fail;
389 }
390 memcpy(bitmap, bh->b_data, sb->s_blocksize);
391 brelse(bh);
392 bh = NULL;
393
394 spaceman->sm_ip_bmaps[idx].dirty = false;
395 spaceman->sm_ip_bmaps[idx].block = bitmap;
396 bitmap = NULL;
397 return 0;
398
399 fail:
400 kfree(bitmap);
401 bitmap = NULL;
402 return err;
403 }
404
405 /**
406 * apfs_read_ip_bitmaps - Read all the ip bitmaps to memory
407 * @sb: superblock structure
408 *
409 * Returns 0 on success or a negative error code in case of failure.
410 */
411 static int apfs_read_ip_bitmaps(struct super_block *sb)
412 {
413 struct apfs_spaceman *spaceman = APFS_SM(sb);
414 u32 bmaps_count = spaceman->sm_ip_bmaps_count;
415 int err;
416 u32 i;
417
418 for (i = 0; i < bmaps_count; ++i) {
419 err = apfs_read_single_ip_bitmap(sb, i);
420 if (err) {
421 apfs_err(sb, "failed to read ip bitmap %u", i);
422 return err;
423 }
424 }
425 return 0;
426 }
427
428 /*
429 * Free queue record data
430 */
431 struct apfs_fq_rec {
432 u64 xid;
433 u64 bno;
434 u64 len;
435 };
436
437 /**
438 * apfs_fq_rec_from_query - Read the free queue record found by a query
439 * @query: the query that found the record
440 * @fqrec: on return, the free queue record
441 *
442 * Reads the free queue record into @fqrec and performs some basic sanity
443 * checks as a protection against crafted filesystems. Returns 0 on success
444 * or -EFSCORRUPTED otherwise.
445 */
446 static int apfs_fq_rec_from_query(struct apfs_query *query, struct apfs_fq_rec *fqrec)
447 {
448 char *raw = query->node->object.data;
449 struct apfs_spaceman_free_queue_key *key;
450
451 if (query->key_len != sizeof(*key)) {
452 apfs_err(query->node->object.sb, "bad key length (%d)", query->key_len);
453 return -EFSCORRUPTED;
454 }
455 key = (struct apfs_spaceman_free_queue_key *)(raw + query->key_off);
456
457 fqrec->xid = le64_to_cpu(key->sfqk_xid);
458 fqrec->bno = le64_to_cpu(key->sfqk_paddr);
459
460 if (query->len == 0) {
461 fqrec->len = 1; /* Ghost record */
462 return 0;
463 } else if (query->len == sizeof(__le64)) {
464 fqrec->len = le64_to_cpup((__le64 *)(raw + query->off));
465 return 0;
466 }
467 apfs_err(query->node->object.sb, "bad value length (%d)", query->len);
468 return -EFSCORRUPTED;
469 }
470
471 /**
472 * apfs_block_in_ip - Does this block belong to the internal pool?
473 * @sm: in-memory spaceman structure
474 * @bno: block number to check
475 */
476 static inline bool apfs_block_in_ip(struct apfs_spaceman *sm, u64 bno)
477 {
478 struct apfs_spaceman_phys *sm_raw = sm->sm_raw;
479 u64 start = le64_to_cpu(sm_raw->sm_ip_base);
480 u64 end = start + le64_to_cpu(sm_raw->sm_ip_block_count);
481
482 return bno >= start && bno < end;
483 }
484
485 /**
486 * apfs_ip_mark_free - Mark a block in the internal pool as free
487 * @sb: superblock structure
488 * @bno: block number (must belong to the ip)
489 */
490 static int apfs_ip_mark_free(struct super_block *sb, u64 bno)
491 {
492 struct apfs_spaceman *sm = APFS_SM(sb);
493 struct apfs_spaceman_phys *sm_raw = sm->sm_raw;
494 struct apfs_ip_bitmap_block_info *info = NULL;
495
496 bno -= le64_to_cpu(sm_raw->sm_ip_base);
497 info = &sm->sm_ip_bmaps[bno >> sm->sm_ip_bmaps_shift];
498 __clear_bit_le(bno & sm->sm_ip_bmaps_mask, info->block);
499 info->dirty = true;
500
501 return 0;
502 }
503
504 /*
505 * apfs_main_free - Mark a regular block as free
506 */
507 static int apfs_main_free(struct super_block *sb, u64 bno);
508
509 /**
510 * apfs_flush_fq_rec - Delete a single fq record and mark its blocks as free
511 * @root: free queue root node
512 * @xid: transaction to target
513 * @len: on return, the number of freed blocks
514 *
515 * Returns 0 on success, or a negative error code in case of failure. -ENODATA
516 * in particular means that there are no matching records left.
517 */
518 static int apfs_flush_fq_rec(struct apfs_node *root, u64 xid, u64 *len)
519 {
520 struct super_block *sb = root->object.sb;
521 struct apfs_spaceman *sm = APFS_SM(sb);
522 struct apfs_query *query = NULL;
523 struct apfs_fq_rec fqrec = {0};
524 u64 bno;
525 int err;
526
527 query = apfs_alloc_query(root, NULL /* parent */);
528 if (!query)
529 return -ENOMEM;
530 apfs_init_free_queue_key(xid, 0 /* paddr */, &query->key);
531 query->flags |= APFS_QUERY_FREE_QUEUE | APFS_QUERY_ANY_NUMBER | APFS_QUERY_EXACT;
532
533 err = apfs_btree_query(sb, &query);
534 if (err) {
535 if (err != -ENODATA)
536 apfs_err(sb, "query failed for xid 0x%llx, paddr 0x%llx", xid, 0ULL);
537 goto fail;
538 }
539 err = apfs_fq_rec_from_query(query, &fqrec);
540 if (err) {
541 apfs_err(sb, "bad free queue rec for xid 0x%llx", xid);
542 goto fail;
543 }
544
545 for (bno = fqrec.bno; bno < fqrec.bno + fqrec.len; ++bno) {
546 if (apfs_block_in_ip(sm, bno))
547 err = apfs_ip_mark_free(sb, bno);
548 else
549 err = apfs_main_free(sb, bno);
550 if (err) {
551 apfs_err(sb, "freeing block 0x%llx failed (%d)", (unsigned long long)bno, err);
552 goto fail;
553 }
554 }
555 err = apfs_btree_remove(query);
556 if (err) {
557 apfs_err(sb, "removal failed for xid 0x%llx", xid);
558 goto fail;
559 }
560 *len = fqrec.len;
561
562 fail:
563 apfs_free_query(query);
564 return err;
565 }
566
567 /**
568 * apfs_free_queue_oldest_xid - Find the oldest xid among the free queue records
569 * @root: free queue root node
570 */
571 static u64 apfs_free_queue_oldest_xid(struct apfs_node *root)
572 {
573 struct apfs_spaceman_free_queue_key *key;
574 char *raw = root->object.data;
575 int len, off;
576
577 if (root->records == 0)
578 return 0;
579 len = apfs_node_locate_key(root, 0, &off);
580 if (len != sizeof(*key)) {
581 /* TODO: abort transaction */
582 apfs_err(root->object.sb, "bad key length (%d)", len);
583 return 0;
584 }
585 key = (struct apfs_spaceman_free_queue_key *)(raw + off);
586 return le64_to_cpu(key->sfqk_xid);
587 }
588
589 /**
590 * apfs_flush_free_queue - Free ip blocks queued by old transactions
591 * @sb: superblock structure
592 * @qid: queue to be freed
593 *
594 * Returns 0 on success or a negative error code in case of failure.
595 */
596 static int apfs_flush_free_queue(struct super_block *sb, unsigned int qid)
597 {
598 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
599 struct apfs_spaceman *sm = APFS_SM(sb);
600 struct apfs_spaceman_phys *sm_raw = sm->sm_raw;
601 struct apfs_spaceman_free_queue *fq = &sm_raw->sm_fq[qid];
602 struct apfs_node *fq_root;
603 struct apfs_btree_info *fq_info = NULL;
604 u64 oldest = le64_to_cpu(fq->sfq_oldest_xid);
605 int err;
606
607 fq_root = apfs_read_node(sb, le64_to_cpu(fq->sfq_tree_oid),
608 APFS_OBJ_EPHEMERAL, true /* write */);
609 if (IS_ERR(fq_root)) {
610 apfs_err(sb, "failed to read fq root 0x%llx", le64_to_cpu(fq->sfq_tree_oid));
611 return PTR_ERR(fq_root);
612 }
613
614 while (oldest) {
615 /*
616 * Blocks freed in the current transaction can't be reused
617 * safely until after the commit, but I don't think there is
618 * any point in preserving old transacions. I'm guessing the
619 * official driver keeps multiple transactions going at the
620 * same time, that must be why they need a free queue.
621 */
622 if (oldest == nxi->nx_xid)
623 break;
624
625 while (true) {
626 u64 count = 0;
627
628 /* Probably not very efficient... */
629 err = apfs_flush_fq_rec(fq_root, oldest, &count);
630 if (err == -ENODATA) {
631 err = 0;
632 break;
633 } else if (err) {
634 apfs_err(sb, "failed to flush fq");
635 goto fail;
636 } else {
637 le64_add_cpu(&fq->sfq_count, -count);
638 }
639 }
640 oldest = apfs_free_queue_oldest_xid(fq_root);
641 fq->sfq_oldest_xid = cpu_to_le64(oldest);
642 }
643
644 if (qid == APFS_SFQ_MAIN) {
645 fq_info = (void *)fq_root->object.data + sb->s_blocksize - sizeof(*fq_info);
646 sm->sm_main_fq_nodes = le64_to_cpu(fq_info->bt_node_count);
647 if (sm->sm_main_fq_nodes != 1) {
648 apfs_alert(sb, "main queue wasn't flushed in full - bug!");
649 err = -EFSCORRUPTED;
650 goto fail;
651 }
652 }
653
654 fail:
655 apfs_node_free(fq_root);
656 return err;
657 }
658
659 /**
660 * apfs_allocate_spaceman - Allocate an in-memory spaceman struct, if needed
661 * @sb: superblock structure
662 * @raw: on-disk spaceman struct
663 * @size: size of the on-disk spaceman
664 *
665 * Returns the spaceman and sets it in the superblock info. Also performs all
666 * initializations for the internal pool, including reading all the ip bitmaps.
667 * This is a bit out of place here, but it's convenient because it has to
668 * happen only once.
669 *
670 * On failure, returns an error pointer.
671 */
672 static struct apfs_spaceman *apfs_allocate_spaceman(struct super_block *sb, struct apfs_spaceman_phys *raw, u32 size)
673 {
674 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
675 struct apfs_spaceman *spaceman = NULL;
676 int blk_bitcnt = sb->s_blocksize * 8;
677 size_t sm_size;
678 u32 bmap_cnt;
679 int err;
680
681 if (nxi->nx_spaceman)
682 return nxi->nx_spaceman;
683
684 /* We don't expect filesystems this big, it would be like 260 TiB */
685 bmap_cnt = le32_to_cpu(raw->sm_ip_bm_size_in_blocks);
686 if (bmap_cnt > 200) {
687 apfs_err(sb, "too many ip bitmap blocks (%u)", bmap_cnt);
688 return ERR_PTR(-EFSCORRUPTED);
689 }
690 sm_size = sizeof(*spaceman) + bmap_cnt * sizeof(spaceman->sm_ip_bmaps[0]);
691
692 spaceman = nxi->nx_spaceman = kzalloc(sm_size, GFP_KERNEL);
693 if (!spaceman)
694 return ERR_PTR(-ENOMEM);
695 spaceman->sm_nxi = nxi;
696 /*
697 * These two fields must be set before reading the ip bitmaps, since
698 * that stuff involves several variable-length arrays inside the
699 * spaceman object itself.
700 */
701 spaceman->sm_raw = raw;
702 spaceman->sm_size = size;
703
704 spaceman->sm_ip_bmaps_count = bmap_cnt;
705 spaceman->sm_ip_bmaps_mask = blk_bitcnt - 1;
706 spaceman->sm_ip_bmaps_shift = order_base_2(blk_bitcnt);
707
708 /* This must happen only once, so it's easier to just leave it here */
709 err = apfs_read_ip_bitmaps(sb);
710 if (err) {
711 apfs_err(sb, "failed to read the ip bitmaps");
712 kfree(spaceman);
713 nxi->nx_spaceman = spaceman = NULL;
714 return ERR_PTR(err);
715 }
716
717 return nxi->nx_spaceman;
718 }
719
720 /**
721 * apfs_read_spaceman - Find and read the space manager
722 * @sb: superblock structure
723 *
724 * Reads the space manager structure from disk and initializes its in-memory
725 * counterpart; returns 0 on success, or a negative error code in case of
726 * failure.
727 */
728 int apfs_read_spaceman(struct super_block *sb)
729 {
730 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
731 struct apfs_nx_superblock *raw_sb = nxi->nx_raw;
732 struct apfs_spaceman *spaceman = NULL;
733 struct apfs_ephemeral_object_info *sm_eph_info = NULL;
734 struct apfs_spaceman_phys *sm_raw;
735 u32 sm_flags;
736 u64 oid = le64_to_cpu(raw_sb->nx_spaceman_oid);
737 int err;
738
739 if (sb->s_flags & SB_RDONLY) /* The space manager won't be needed */
740 return 0;
741
742 sm_eph_info = apfs_ephemeral_object_lookup(sb, oid);
743 if (IS_ERR(sm_eph_info)) {
744 apfs_err(sb, "no spaceman object for oid 0x%llx", oid);
745 return PTR_ERR(sm_eph_info);
746 }
747 sm_raw = (struct apfs_spaceman_phys *)sm_eph_info->object;
748 sm_raw->sm_o.o_xid = cpu_to_le64(nxi->nx_xid);
749
750 spaceman = apfs_allocate_spaceman(sb, sm_raw, sm_eph_info->size);
751 if (IS_ERR(spaceman)) {
752 apfs_err(sb, "failed to allocate spaceman");
753 err = PTR_ERR(spaceman);
754 goto fail;
755 }
756
757 spaceman->sm_free_cache_base = spaceman->sm_free_cache_blkcnt = 0;
758
759 sm_flags = le32_to_cpu(sm_raw->sm_flags);
760 /* Undocumented feature, but it's too common to refuse to mount */
761 if (sm_flags & APFS_SM_FLAG_VERSIONED)
762 pr_warn_once("APFS: space manager is versioned\n");
763
764 /* Only read the main device; fusion drives are not yet supported */
765 err = apfs_read_spaceman_dev(sb, &sm_raw->sm_dev[APFS_SD_MAIN]);
766 if (err) {
767 apfs_err(sb, "failed to read main device");
768 goto fail;
769 }
770
771 spaceman->sm_blocks_per_chunk =
772 le32_to_cpu(sm_raw->sm_blocks_per_chunk);
773 spaceman->sm_chunks_per_cib = le32_to_cpu(sm_raw->sm_chunks_per_cib);
774 if (spaceman->sm_chunks_per_cib > apfs_max_chunks_per_cib(sb)) {
775 apfs_err(sb, "too many chunks per cib (%u)", spaceman->sm_chunks_per_cib);
776 err = -EFSCORRUPTED;
777 goto fail;
778 }
779
780 /*
781 * We flush free queues whole when each transaction begins, to make it
782 * harder for the btrees to become too unbalanced.
783 */
784 err = apfs_flush_free_queue(sb, APFS_SFQ_IP);
785 if (err) {
786 apfs_err(sb, "failed to flush ip fq");
787 goto fail;
788 }
789 err = apfs_flush_free_queue(sb, APFS_SFQ_MAIN);
790 if (err) {
791 apfs_err(sb, "failed to flush main fq");
792 goto fail;
793 }
794 return 0;
795
796 fail:
797 spaceman->sm_raw = NULL;
798 return err;
799 }
800
801 /**
802 * apfs_write_spaceman - Write the in-memory spaceman fields to the disk buffer
803 * @sm: in-memory spaceman structure
804 *
805 * Copies the updated in-memory fields of the space manager into the on-disk
806 * structure; the buffer is not dirtied.
807 */
808 static void apfs_write_spaceman(struct apfs_spaceman *sm)
809 {
810 struct apfs_spaceman_phys *sm_raw = sm->sm_raw;
811 struct apfs_spaceman_device *dev_raw = &sm_raw->sm_dev[APFS_SD_MAIN];
812 struct apfs_nxsb_info *nxi;
813
814 nxi = sm->sm_nxi;
815 ASSERT(le64_to_cpu(sm_raw->sm_o.o_xid) == nxi->nx_xid);
816
817 dev_raw->sm_free_count = cpu_to_le64(sm->sm_free_count);
818 }
819
820 /**
821 * apfs_ip_find_free - Find a free block inside the internal pool
822 * @sb: superblock structure
823 *
824 * Returns the block number for a free block, or 0 in case of corruption.
825 */
826 static u64 apfs_ip_find_free(struct super_block *sb)
827 {
828 struct apfs_spaceman *sm = APFS_SM(sb);
829 struct apfs_spaceman_phys *sm_raw = sm->sm_raw;
830 int blk_bitcnt = sb->s_blocksize * 8;
831 u64 full_bitcnt = le64_to_cpu(sm_raw->sm_ip_block_count);
832 u32 i;
833
834 for (i = 0; i < sm->sm_ip_bmaps_count; ++i) {
835 char *bitmap = sm->sm_ip_bmaps[i].block;
836 u64 off_in_bmap_blk, off_in_ip;
837
838 off_in_bmap_blk = find_next_zero_bit_le(bitmap, blk_bitcnt, 0 /* offset */);
839 if (off_in_bmap_blk >= blk_bitcnt) /* No space in this chunk */
840 continue;
841
842 /* We found something, confirm that it's not outside the ip */
843 off_in_ip = (i << sm->sm_ip_bmaps_shift) + off_in_bmap_blk;
844 if (off_in_ip >= full_bitcnt)
845 break;
846 return le64_to_cpu(sm_raw->sm_ip_base) + off_in_ip;
847 }
848 apfs_err(sb, "internal pool seems full");
849 return 0;
850 }
851
852 /**
853 * apfs_chunk_find_free - Find a free block inside a chunk
854 * @sb: superblock structure
855 * @bitmap: allocation bitmap for the chunk, which should have free blocks
856 * @addr: number of the first block in the chunk
857 *
858 * Returns the block number for a free block, or 0 in case of corruption.
859 */
860 static u64 apfs_chunk_find_free(struct super_block *sb, char *bitmap, u64 addr)
861 {
862 int bitcount = sb->s_blocksize * 8;
863 u64 bno;
864
865 bno = find_next_zero_bit_le(bitmap, bitcount, 0 /* offset */);
866 if (bno >= bitcount)
867 return 0;
868 return addr + bno;
869 }
870
871 /**
872 * apfs_ip_mark_used - Mark a block in the internal pool as used
873 * @sb: superblock strucuture
874 * @bno: block number (must belong to the ip)
875 */
876 static void apfs_ip_mark_used(struct super_block *sb, u64 bno)
877 {
878 struct apfs_spaceman *sm = APFS_SM(sb);
879 struct apfs_spaceman_phys *sm_raw = sm->sm_raw;
880 struct apfs_ip_bitmap_block_info *info = NULL;
881
882 bno -= le64_to_cpu(sm_raw->sm_ip_base);
883 info = &sm->sm_ip_bmaps[bno >> sm->sm_ip_bmaps_shift];
884 __set_bit_le(bno & sm->sm_ip_bmaps_mask, info->block);
885 info->dirty = true;
886 }
887
888 /**
889 * apfs_chunk_mark_used - Mark a block inside a chunk as used
890 * @sb: superblock structure
891 * @bitmap: allocation bitmap for the chunk
892 * @bno: block number (must belong to the chunk)
893 */
894 static inline void apfs_chunk_mark_used(struct super_block *sb, char *bitmap,
895 u64 bno)
896 {
897 int bitcount = sb->s_blocksize * 8;
898
899 __set_bit_le(bno & (bitcount - 1), bitmap);
900 }
901
902 /**
903 * apfs_chunk_mark_free - Mark a block inside a chunk as free
904 * @sb: superblock structure
905 * @bitmap: allocation bitmap for the chunk
906 * @bno: block number (must belong to the chunk)
907 */
908 static inline int apfs_chunk_mark_free(struct super_block *sb, char *bitmap,
909 u64 bno)
910 {
911 int bitcount = sb->s_blocksize * 8;
912
913 return __test_and_clear_bit_le(bno & (bitcount - 1), bitmap);
914 }
915
916 /**
917 * apfs_free_queue_try_insert - Try to add a block range to its free queue
918 * @sb: superblock structure
919 * @bno: first block number to free
920 * @count: number of consecutive blocks to free
921 *
922 * Same as apfs_free_queue_insert_nocache(), except that this one can also fail
923 * with -ENOSPC if there is no room for the new record.
924 */
925 static int apfs_free_queue_try_insert(struct super_block *sb, u64 bno, u64 count)
926 {
927 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
928 struct apfs_spaceman *sm = APFS_SM(sb);
929 struct apfs_spaceman_phys *sm_raw = sm->sm_raw;
930 struct apfs_spaceman_free_queue *fq;
931 struct apfs_node *fq_root = NULL;
932 struct apfs_btree_info *fq_info = NULL;
933 struct apfs_query *query = NULL;
934 struct apfs_spaceman_free_queue_key raw_key;
935 bool ghost = count == 1;
936 int needed_room;
937 __le64 raw_val;
938 u64 node_count;
939 u16 node_limit;
940 unsigned int qid;
941 int err;
942
943 qid = apfs_block_in_ip(sm, bno) ? APFS_SFQ_IP : APFS_SFQ_MAIN;
944 fq = &sm_raw->sm_fq[qid];
945
946 fq_root = apfs_read_node(sb, le64_to_cpu(fq->sfq_tree_oid),
947 APFS_OBJ_EPHEMERAL, true /* write */);
948 if (IS_ERR(fq_root)) {
949 apfs_err(sb, "failed to read fq root 0x%llx", le64_to_cpu(fq->sfq_tree_oid));
950 return PTR_ERR(fq_root);
951 }
952
953 query = apfs_alloc_query(fq_root, NULL /* parent */);
954 if (!query) {
955 err = -ENOMEM;
956 goto fail;
957 }
958 apfs_init_free_queue_key(nxi->nx_xid, bno, &query->key);
959 query->flags |= APFS_QUERY_FREE_QUEUE;
960
961 err = apfs_btree_query(sb, &query);
962 if (err && err != -ENODATA) {
963 apfs_err(sb, "query failed for xid 0x%llx, paddr 0x%llx", nxi->nx_xid, bno);
964 goto fail;
965 }
966
967 fq_info = (void *)fq_root->object.data + sb->s_blocksize - sizeof(*fq_info);
968 node_count = le64_to_cpu(fq_info->bt_node_count);
969 node_limit = le16_to_cpu(fq->sfq_tree_node_limit);
970 if (node_count == node_limit) {
971 needed_room = sizeof(raw_key) + (ghost ? 0 : sizeof(raw_val));
972 if (!apfs_node_has_room(query->node, needed_room, false /* replace */)) {
973 err = -ENOSPC;
974 goto fail;
975 }
976 }
977
978 raw_key.sfqk_xid = cpu_to_le64(nxi->nx_xid);
979 raw_key.sfqk_paddr = cpu_to_le64(bno);
980 if (ghost) {
981 /* A lack of value (ghost record) means single-block extent */
982 err = apfs_btree_insert(query, &raw_key, sizeof(raw_key), NULL /* val */, 0 /* val_len */);
983 } else {
984 raw_val = cpu_to_le64(count);
985 err = apfs_btree_insert(query, &raw_key, sizeof(raw_key), &raw_val, sizeof(raw_val));
986 }
987 if (err) {
988 apfs_err(sb, "insertion failed for xid 0x%llx, paddr 0x%llx", nxi->nx_xid, bno);
989 goto fail;
990 }
991
992 if (!fq->sfq_oldest_xid)
993 fq->sfq_oldest_xid = cpu_to_le64(nxi->nx_xid);
994 le64_add_cpu(&fq->sfq_count, count);
995
996 if (qid == APFS_SFQ_MAIN)
997 sm->sm_main_fq_nodes = le64_to_cpu(fq_info->bt_node_count);
998
999 fail:
1000 apfs_free_query(query);
1001 apfs_node_free(fq_root);
1002 return err;
1003 }
1004
1005 /**
1006 * apfs_free_queue_insert_nocache - Add a block range to its free queue
1007 * @sb: superblock structure
1008 * @bno: first block number to free
1009 * @count: number of consecutive blocks to free
1010 *
1011 * Same as apfs_free_queue_insert(), but writes to the free queue directly,
1012 * bypassing the cache of the latest freed block range.
1013 *
1014 * Returns 0 on success or a negative error code in case of failure.
1015 */
1016 int apfs_free_queue_insert_nocache(struct super_block *sb, u64 bno, u64 count)
1017 {
1018 unsigned int qid;
1019 int err;
1020
1021 err = apfs_free_queue_try_insert(sb, bno, count);
1022 if (err == -ENOSPC) {
1023 qid = apfs_block_in_ip(APFS_SM(sb), bno) ? APFS_SFQ_IP : APFS_SFQ_MAIN;
1024 apfs_alert(sb, "free queue (%u) seems full - bug!", qid);
1025 err = -EFSCORRUPTED;
1026 }
1027 if (err) {
1028 apfs_err(sb, "fq insert failed (0x%llx-0x%llx)", bno, count);
1029 return err;
1030 }
1031 return 0;
1032 }
1033
1034 /**
1035 * apfs_free_queue_insert - Add a block range to its free queue
1036 * @sb: superblock structure
1037 * @bno: first block number to free
1038 * @count: number of consecutive blocks to free
1039 *
1040 * Uses a cache to delay the actual tree operations as much as possible.
1041 *
1042 * Returns 0 on success or a negative error code in case of failure.
1043 */
1044 int apfs_free_queue_insert(struct super_block *sb, u64 bno, u64 count)
1045 {
1046 struct apfs_spaceman *sm = APFS_SM(sb);
1047 int err;
1048
1049 if (sm->sm_free_cache_base == 0) {
1050 /* Nothing yet cached */
1051 sm->sm_free_cache_base = bno;
1052 sm->sm_free_cache_blkcnt = count;
1053 return 0;
1054 }
1055
1056 /*
1057 * First attempt to extend the cache of freed blocks, but never cache
1058 * a range that doesn't belong to a single free queue.
1059 */
1060 if (apfs_block_in_ip(sm, bno) == apfs_block_in_ip(sm, sm->sm_free_cache_base)) {
1061 if (bno == sm->sm_free_cache_base + sm->sm_free_cache_blkcnt) {
1062 sm->sm_free_cache_blkcnt += count;
1063 return 0;
1064 }
1065 if (bno + count == sm->sm_free_cache_base) {
1066 sm->sm_free_cache_base -= count;
1067 sm->sm_free_cache_blkcnt += count;
1068 return 0;
1069 }
1070 }
1071
1072 /* Failed to extend the cache, so flush it and replace it */
1073 err = apfs_free_queue_insert_nocache(sb, sm->sm_free_cache_base, sm->sm_free_cache_blkcnt);
1074 if (err) {
1075 apfs_err(sb, "fq cache flush failed (0x%llx-0x%llx)", sm->sm_free_cache_base, sm->sm_free_cache_blkcnt);
1076 return err;
1077 }
1078 sm->sm_free_cache_base = bno;
1079 sm->sm_free_cache_blkcnt = count;
1080 return 0;
1081 }
1082
1083 /**
1084 * apfs_chunk_alloc_free - Allocate or free block in given CIB and chunk
1085 * @sb: superblock structure
1086 * @cib_bh: buffer head for the chunk-info block
1087 * @index: index of this chunk's info structure inside @cib
1088 * @bno: block number
1089 * @is_alloc: true to allocate, false to free
1090 */
1091 static int apfs_chunk_alloc_free(struct super_block *sb,
1092 struct buffer_head **cib_bh,
1093 int index, u64 *bno, bool is_alloc)
1094 {
1095 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
1096 struct apfs_spaceman *sm = APFS_SM(sb);
1097 struct apfs_chunk_info_block *cib;
1098 struct apfs_chunk_info *ci;
1099 struct buffer_head *bmap_bh = NULL;
1100 char *bmap = NULL;
1101 bool old_cib = false;
1102 bool old_bmap = false;
1103 int err = 0;
1104
1105 cib = (struct apfs_chunk_info_block *)(*cib_bh)->b_data;
1106 ci = &cib->cib_chunk_info[index];
1107
1108 /* Cibs and bitmaps from old transactions can't be modified in place */
1109 if (le64_to_cpu(cib->cib_o.o_xid) < nxi->nx_xid)
1110 old_cib = true;
1111 if (le64_to_cpu(ci->ci_xid) < nxi->nx_xid)
1112 old_bmap = true;
1113 if (is_alloc && le32_to_cpu(ci->ci_free_count) < 1)
1114 return -ENOSPC;
1115
1116 /* Read the current bitmap, or allocate it if necessary */
1117 if (!ci->ci_bitmap_addr) {
1118 u64 bmap_bno;
1119
1120 if (!is_alloc) {
1121 apfs_err(sb, "attempt to free block in all-free chunk");
1122 return -EFSCORRUPTED;
1123 }
1124
1125 /* All blocks in this chunk are free */
1126 bmap_bno = apfs_ip_find_free(sb);
1127 if (!bmap_bno) {
1128 apfs_err(sb, "no free blocks in ip");
1129 return -EFSCORRUPTED;
1130 }
1131 bmap_bh = apfs_sb_bread(sb, bmap_bno);
1132 } else {
1133 bmap_bh = apfs_sb_bread(sb, le64_to_cpu(ci->ci_bitmap_addr));
1134 }
1135 if (!bmap_bh) {
1136 apfs_err(sb, "failed to read bitmap block");
1137 return -EIO;
1138 }
1139 bmap = bmap_bh->b_data;
1140 if (!ci->ci_bitmap_addr) {
1141 memset(bmap, 0, sb->s_blocksize);
1142 old_bmap = false;
1143 }
1144
1145 /* Write the bitmap to its location for the next transaction */
1146 if (old_bmap) {
1147 struct buffer_head *new_bmap_bh;
1148 u64 new_bmap_bno;
1149
1150 new_bmap_bno = apfs_ip_find_free(sb);
1151 if (!new_bmap_bno) {
1152 apfs_err(sb, "no free blocks in ip");
1153 err = -EFSCORRUPTED;
1154 goto fail;
1155 }
1156
1157 new_bmap_bh = apfs_getblk(sb, new_bmap_bno);
1158 if (!new_bmap_bh) {
1159 apfs_err(sb, "failed to map new bmap block (0x%llx)", new_bmap_bno);
1160 err = -EIO;
1161 goto fail;
1162 }
1163 memcpy(new_bmap_bh->b_data, bmap, sb->s_blocksize);
1164 err = apfs_free_queue_insert(sb, bmap_bh->b_blocknr, 1);
1165 brelse(bmap_bh);
1166 bmap_bh = new_bmap_bh;
1167 if (err) {
1168 apfs_err(sb, "free queue insertion failed");
1169 goto fail;
1170 }
1171 bmap = bmap_bh->b_data;
1172 }
1173 apfs_ip_mark_used(sb, bmap_bh->b_blocknr);
1174
1175 /* Write the cib to its location for the next transaction */
1176 if (old_cib) {
1177 struct buffer_head *new_cib_bh;
1178 u64 new_cib_bno;
1179
1180 new_cib_bno = apfs_ip_find_free(sb);
1181 if (!new_cib_bno) {
1182 apfs_err(sb, "no free blocks in ip");
1183 err = -EFSCORRUPTED;
1184 goto fail;
1185 }
1186
1187 new_cib_bh = apfs_getblk(sb, new_cib_bno);
1188 if (!new_cib_bh) {
1189 apfs_err(sb, "failed to map new cib block (0x%llx)", new_cib_bno);
1190 err = -EIO;
1191 goto fail;
1192 }
1193 memcpy(new_cib_bh->b_data, (*cib_bh)->b_data, sb->s_blocksize);
1194 err = apfs_free_queue_insert(sb, (*cib_bh)->b_blocknr, 1);
1195 brelse(*cib_bh);
1196 *cib_bh = new_cib_bh;
1197 if (err) {
1198 apfs_err(sb, "free queue insertion failed");
1199 goto fail;
1200 }
1201
1202 err = apfs_transaction_join(sb, *cib_bh);
1203 if (err)
1204 goto fail;
1205
1206 cib = (struct apfs_chunk_info_block *)(*cib_bh)->b_data;
1207 ci = &cib->cib_chunk_info[index];
1208 cib->cib_o.o_oid = cpu_to_le64(new_cib_bno);
1209 cib->cib_o.o_xid = cpu_to_le64(nxi->nx_xid);
1210
1211 apfs_ip_mark_used(sb, new_cib_bno);
1212 }
1213
1214 /* The chunk info can be updated now */
1215 apfs_assert_in_transaction(sb, &cib->cib_o);
1216 ci->ci_xid = cpu_to_le64(nxi->nx_xid);
1217 le32_add_cpu(&ci->ci_free_count, is_alloc ? -1 : 1);
1218 ci->ci_bitmap_addr = cpu_to_le64(bmap_bh->b_blocknr);
1219 ASSERT(buffer_trans(*cib_bh));
1220 set_buffer_csum(*cib_bh);
1221
1222 /* Finally, allocate / free the actual block that was requested */
1223 if (is_alloc) {
1224 *bno = apfs_chunk_find_free(sb, bmap, le64_to_cpu(ci->ci_addr));
1225 if (!*bno) {
1226 apfs_err(sb, "no free blocks in chunk");
1227 err = -EFSCORRUPTED;
1228 goto fail;
1229 }
1230 apfs_chunk_mark_used(sb, bmap, *bno);
1231 sm->sm_free_count -= 1;
1232 } else {
1233 if (!apfs_chunk_mark_free(sb, bmap, *bno)) {
1234 apfs_err(sb, "block already marked as free (0x%llx)", *bno);
1235 le32_add_cpu(&ci->ci_free_count, -1);
1236 set_buffer_csum(*cib_bh);
1237 err = -EFSCORRUPTED;
1238 } else
1239 sm->sm_free_count += 1;
1240 }
1241 mark_buffer_dirty(bmap_bh);
1242
1243 fail:
1244 brelse(bmap_bh);
1245 return err;
1246 }
1247
1248 /**
1249 * apfs_chunk_allocate_block - Allocate a single block from a chunk
1250 * @sb: superblock structure
1251 * @cib_bh: buffer head for the chunk-info block
1252 * @index: index of this chunk's info structure inside @cib
1253 * @bno: on return, the allocated block number
1254 *
1255 * Finds a free block in the chunk and marks it as used; the buffer at @cib_bh
1256 * may be replaced if needed for copy-on-write. Returns 0 on success, or a
1257 * negative error code in case of failure.
1258 */
1259 static int apfs_chunk_allocate_block(struct super_block *sb,
1260 struct buffer_head **cib_bh,
1261 int index, u64 *bno)
1262 {
1263 return apfs_chunk_alloc_free(sb, cib_bh, index, bno, true);
1264 }
1265
1266 /**
1267 * apfs_cib_allocate_block - Allocate a single block from a cib
1268 * @sb: superblock structure
1269 * @cib_bh: buffer head for the chunk-info block
1270 * @bno: on return, the allocated block number
1271 * @backwards: start the search on the last chunk
1272 *
1273 * Finds a free block among all the chunks in the cib and marks it as used; the
1274 * buffer at @cib_bh may be replaced if needed for copy-on-write. Returns 0 on
1275 * success, or a negative error code in case of failure.
1276 */
1277 static int apfs_cib_allocate_block(struct super_block *sb,
1278 struct buffer_head **cib_bh, u64 *bno, bool backwards)
1279 {
1280 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
1281 struct apfs_spaceman *sm = APFS_SM(sb);
1282 struct apfs_chunk_info_block *cib;
1283 u32 chunk_count;
1284 int i;
1285
1286 cib = (struct apfs_chunk_info_block *)(*cib_bh)->b_data;
1287 if (nxi->nx_flags & APFS_CHECK_NODES && !apfs_obj_verify_csum(sb, *cib_bh)) {
1288 apfs_err(sb, "bad checksum for chunk-info block");
1289 return -EFSBADCRC;
1290 }
1291
1292 /* Avoid out-of-bounds operations on corrupted cibs */
1293 chunk_count = le32_to_cpu(cib->cib_chunk_info_count);
1294 if (chunk_count > sm->sm_chunks_per_cib) {
1295 apfs_err(sb, "too many chunks in cib (%u)", chunk_count);
1296 return -EFSCORRUPTED;
1297 }
1298
1299 for (i = 0; i < chunk_count; ++i) {
1300 int index;
1301 int err;
1302
1303 index = backwards ? chunk_count - 1 - i : i;
1304
1305 err = apfs_chunk_allocate_block(sb, cib_bh, index, bno);
1306 if (err == -ENOSPC) /* This chunk is full */
1307 continue;
1308 if (err)
1309 apfs_err(sb, "error during allocation");
1310 return err;
1311 }
1312 return -ENOSPC;
1313 }
1314
1315 /**
1316 * apfs_spaceman_allocate_block - Allocate a single on-disk block
1317 * @sb: superblock structure
1318 * @bno: on return, the allocated block number
1319 * @backwards: start the search on the last chunk
1320 *
1321 * Finds a free block among the spaceman bitmaps and marks it as used. Returns
1322 * 0 on success, or a negative error code in case of failure.
1323 */
1324 int apfs_spaceman_allocate_block(struct super_block *sb, u64 *bno, bool backwards)
1325 {
1326 struct apfs_spaceman *sm = APFS_SM(sb);
1327 int i;
1328
1329 for (i = 0; i < sm->sm_cib_count; ++i) {
1330 struct buffer_head *cib_bh;
1331 u64 cib_bno;
1332 int index;
1333 int err;
1334
1335 /* Keep extents and metadata separate to limit fragmentation */
1336 index = backwards ? sm->sm_cib_count - 1 - i : i;
1337
1338 cib_bno = apfs_spaceman_read_cib_addr(sb, index);
1339 cib_bh = apfs_sb_bread(sb, cib_bno);
1340 if (!cib_bh) {
1341 apfs_err(sb, "failed to read cib");
1342 return -EIO;
1343 }
1344
1345 err = apfs_cib_allocate_block(sb, &cib_bh, bno, backwards);
1346 if (!err) {
1347 /* The cib may have been moved */
1348 apfs_spaceman_write_cib_addr(sb, index, cib_bh->b_blocknr);
1349 /* The free block count has changed */
1350 apfs_write_spaceman(sm);
1351 }
1352 brelse(cib_bh);
1353 if (err == -ENOSPC) /* This cib is full */
1354 continue;
1355 if (err)
1356 apfs_err(sb, "error during allocation");
1357 return err;
1358 }
1359 /*
1360 * We checked the free space before starting the transaction, so this
1361 * isn't expected to happen.
1362 */
1363 apfs_err(sb, "ran out of space during transaction");
1364 return -ENOSPC;
1365 }
1366
1367 /**
1368 * apfs_chunk_free - Mark a regular block as free given CIB and chunk
1369 * @sb: superblock structure
1370 * @cib_bh: buffer head for the chunk-info block
1371 * @index: index of this chunk's info structure inside @cib
1372 * @bno: block number (must not belong to the ip)
1373 */
1374 static int apfs_chunk_free(struct super_block *sb,
1375 struct buffer_head **cib_bh,
1376 int index, u64 bno)
1377 {
1378 return apfs_chunk_alloc_free(sb, cib_bh, index, &bno, false);
1379 }
1380
1381 /**
1382 * apfs_main_free - Mark a regular block as free
1383 * @sb: superblock structure
1384 * @bno: block number (must not belong to the ip)
1385 */
1386 static int apfs_main_free(struct super_block *sb, u64 bno)
1387 {
1388 struct apfs_spaceman *sm = APFS_SM(sb);
1389 struct apfs_spaceman_phys *sm_raw = sm->sm_raw;
1390 struct apfs_sb_info *sbi = NULL;
1391 u64 cib_idx, chunk_idx;
1392 struct buffer_head *cib_bh;
1393 u64 cib_bno;
1394 int err, orphan_err;
1395
1396 if (!sm_raw->sm_blocks_per_chunk || !sm_raw->sm_chunks_per_cib) {
1397 apfs_err(sb, "block or chunk count not set");
1398 return -EINVAL;
1399 }
1400 /* TODO: use bitshifts instead of do_div() */
1401 chunk_idx = bno;
1402 do_div(chunk_idx, sm->sm_blocks_per_chunk);
1403 cib_idx = chunk_idx;
1404 chunk_idx = do_div(cib_idx, sm->sm_chunks_per_cib);
1405
1406 cib_bno = apfs_spaceman_read_cib_addr(sb, cib_idx);
1407 cib_bh = apfs_sb_bread(sb, cib_bno);
1408 if (!cib_bh) {
1409 apfs_err(sb, "failed to read cib");
1410 return -EIO;
1411 }
1412
1413 err = apfs_chunk_free(sb, &cib_bh, chunk_idx, bno);
1414 if (!err) {
1415 /* The cib may have been moved */
1416 apfs_spaceman_write_cib_addr(sb, cib_idx, cib_bh->b_blocknr);
1417 /* The free block count has changed */
1418 apfs_write_spaceman(sm);
1419 }
1420 brelse(cib_bh);
1421 if (err) {
1422 apfs_err(sb, "error during free");
1423 return err;
1424 }
1425
1426 /* It may be time to resume orphan cleanups, if we made enough room */
1427 sbi = APFS_SB(sb);
1428 orphan_err = atomic_read(&sbi->s_orphan_cleanup_err);
1429 if (orphan_err == -ENOSPC && sm->sm_free_count >= 2 * APFS_DEL_ROOM) {
1430 atomic_set(&sbi->s_orphan_cleanup_err, 0);
1431 apfs_schedule_orphan_cleanup(sb);
1432 }
1433
1434 return err;
1435 }
1436
1437 /**
1438 * apfs_spaceman_get_free_blkcnt - Calculate the total number of free blocks
1439 * @sb: filesystem superblock
1440 * @blkcnt: on return, the total number of free blocks for all devices
1441 *
1442 * Can be called even if the spaceman has not been read (for example, on a
1443 * read-only mount). Returns 0 on success, or a negative error code in case of
1444 * failure.
1445 */
1446 int apfs_spaceman_get_free_blkcnt(struct super_block *sb, u64 *blkcnt)
1447 {
1448 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
1449 struct apfs_nx_superblock *raw_sb = NULL;
1450 struct apfs_spaceman_phys *sm_raw = NULL;
1451 struct apfs_ephemeral_object_info *sm_eph_info = NULL;
1452 struct apfs_spaceman_device *dev = NULL;
1453 u64 oid;
1454 int err;
1455
1456 if (!nxi->nx_eph_list) {
1457 err = apfs_read_ephemeral_objects(sb);
1458 if (err) {
1459 apfs_err(sb, "failed to read the ephemeral objects");
1460 return err;
1461 }
1462 }
1463
1464 raw_sb = nxi->nx_raw;
1465 oid = le64_to_cpu(raw_sb->nx_spaceman_oid);
1466 sm_eph_info = apfs_ephemeral_object_lookup(sb, oid);
1467 if (IS_ERR(sm_eph_info)) {
1468 apfs_err(sb, "no spaceman object for oid 0x%llx", oid);
1469 return PTR_ERR(sm_eph_info);
1470 }
1471 sm_raw = (struct apfs_spaceman_phys *)sm_eph_info->object;
1472
1473 *blkcnt = 0;
1474 dev = &sm_raw->sm_dev[APFS_SD_MAIN];
1475 *blkcnt += le64_to_cpu(dev->sm_free_count);
1476 dev = &sm_raw->sm_dev[APFS_SD_TIER2];
1477 *blkcnt += le64_to_cpu(dev->sm_free_count);
1478 return 0;
1479 }