Debian Codegraph @

super.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/backing-dev.h>
7 #include <linux/blkdev.h>
8 #include <linux/module.h>
9 #include <linux/fs.h>
10 #include <linux/magic.h>
11 #include <linux/slab.h>
12 #include <linux/parser.h>
13 #include <linux/buffer_head.h>
14 #include <linux/statfs.h>
15 #include <linux/seq_file.h>
16 #include "apfs.h"
17 #include "version.h"
18 #if LINUX_VERSION_CODE >= KERNEL_VERSION(7, 0, 0)
19 #include <linux/fs_context.h>
20 #include <linux/fs_parser.h>
21 #endif
22
23 #define APFS_MODULE_ID_STRING "linux-apfs by eafer (" GIT_COMMIT ")"
24
25 #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 16, 0) /* iversion came in 4.16 */
26 #include <linux/iversion.h>
27 #endif
28
29 /* Keep a list of mounted containers, so that their volumes can share them */
30 static LIST_HEAD(nxs);
31 /*
32 * The main purpose of this mutex is to protect the list of containers and
33 * their reference counts, but it also has other uses during mounts/unmounts:
34 * - it prevents new mounts from starting while an unmount is updating the
35 * backup superblock (apfs_attach_nxi vs apfs_make_super_copy)
36 * - it prevents a new container superblock read from starting while another
37 * is taking place, which could cause leaks and other issues if both
38 * containers are the same (apfs_read_main_super vs itself)
39 * - it protects the list of volumes for each container, and keeps it
40 * consistent with the reference count
41 * - it prevents two different snapshots for a single volume from trying to
42 * do the first read of their shared omap at the same time
43 * (apfs_first_read_omap vs itself)
44 * - it protects the reference count for that shared omap, keeping it
45 * consistent with the number of volumes that are set with that omap
46 * - it protects the container mount flags, so that they can only be set by
47 * the first volume mount to attempt it (apfs_set_nx_flags vs itself)
48 */
49 DEFINE_MUTEX(nxs_mutex);
50
51 /**
52 * apfs_nx_find_by_dev - Search for a device in the list of mounted containers
53 * @dev: device number of block device for the wanted container
54 *
55 * Returns a pointer to the container structure in the list, or NULL if the
56 * container isn't currently mounted.
57 */
58 static struct apfs_nxsb_info *apfs_nx_find_by_dev(dev_t dev)
59 {
60 struct apfs_nxsb_info *curr;
61
62 lockdep_assert_held(&nxs_mutex);
63 list_for_each_entry(curr, &nxs, nx_list) {
64 struct block_device *curr_bdev = curr->nx_blkdev_info->blki_bdev;
65
66 if (curr_bdev->bd_dev == dev)
67 return curr;
68 }
69 return NULL;
70 }
71
72 /**
73 * apfs_blkdev_set_blocksize - Set the blocksize for a block device
74 * @info: info struct for the block device
75 * @size: size to set
76 *
77 * Returns 0 on success, or a negative error code in case of failure.
78 */
79 static int apfs_blkdev_set_blocksize(struct apfs_blkdev_info *info, int size)
80 {
81 #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 10, 0)
82 return set_blocksize(info->blki_bdev_file, size);
83 #else
84 return set_blocksize(info->blki_bdev, size);
85 #endif
86 }
87
88 /**
89 * apfs_sb_set_blocksize - Set the block size for the container's device
90 * @sb: superblock structure
91 * @size: size to set
92 *
93 * This is like sb_set_blocksize(), but it uses the container's device instead
94 * of the nonexistent volume device.
95 */
96 static int apfs_sb_set_blocksize(struct super_block *sb, int size)
97 {
98 if (apfs_blkdev_set_blocksize(APFS_NXI(sb)->nx_blkdev_info, size))
99 return 0;
100 sb->s_blocksize = size;
101 sb->s_blocksize_bits = blksize_bits(size);
102 return sb->s_blocksize;
103 }
104
105 /**
106 * apfs_read_super_copy - Read the copy of the container superblock in block 0
107 * @sb: superblock structure
108 *
109 * Returns a pointer to the buffer head, or an error pointer in case of failure.
110 */
111 static struct buffer_head *apfs_read_super_copy(struct super_block *sb)
112 {
113 struct buffer_head *bh;
114 struct apfs_nx_superblock *msb_raw;
115 int blocksize;
116 int err = -EINVAL;
117
118 /*
119 * For now assume a small blocksize, we only need it so that we can
120 * read the actual blocksize from disk.
121 */
122 if (!apfs_sb_set_blocksize(sb, APFS_NX_DEFAULT_BLOCK_SIZE)) {
123 apfs_err(sb, "unable to set blocksize");
124 return ERR_PTR(err);
125 }
126 bh = apfs_sb_bread(sb, APFS_NX_BLOCK_NUM);
127 if (!bh) {
128 apfs_err(sb, "unable to read superblock");
129 return ERR_PTR(err);
130 }
131 msb_raw = (struct apfs_nx_superblock *)bh->b_data;
132 blocksize = le32_to_cpu(msb_raw->nx_block_size);
133
134 sb->s_magic = le32_to_cpu(msb_raw->nx_magic);
135 if (sb->s_magic != APFS_NX_MAGIC) {
136 apfs_warn(sb, "not an apfs container - are you mounting the right partition?");
137 goto fail;
138 }
139
140 if (sb->s_blocksize != blocksize) {
141 brelse(bh);
142
143 if (!apfs_sb_set_blocksize(sb, blocksize)) {
144 apfs_err(sb, "bad blocksize %d", blocksize);
145 return ERR_PTR(err);
146 }
147 bh = apfs_sb_bread(sb, APFS_NX_BLOCK_NUM);
148 if (!bh) {
149 apfs_err(sb, "unable to read superblock 2nd time");
150 return ERR_PTR(err);
151 }
152 msb_raw = (struct apfs_nx_superblock *)bh->b_data;
153 }
154
155 if (!apfs_obj_verify_csum(sb, bh))
156 apfs_notice(sb, "backup superblock seems corrupted");
157 return bh;
158
159 fail:
160 brelse(bh);
161 return ERR_PTR(err);
162 }
163
164 /**
165 * apfs_make_super_copy - Write a copy of the checkpoint superblock to block 0
166 * @sb: superblock structure
167 */
168 static void apfs_make_super_copy(struct super_block *sb)
169 {
170 struct apfs_sb_info *sbi = APFS_SB(sb);
171 struct apfs_nxsb_info *nxi = sbi->s_nxi;
172 struct buffer_head *bh;
173
174 if (!(nxi->nx_flags & APFS_READWRITE))
175 return;
176
177 /*
178 * Only update the backup when the last volume is getting unmounted.
179 * Of course a new mounter could still come along before we actually
180 * release the nxi.
181 */
182 mutex_lock(&nxs_mutex);
183 if (nxi->nx_refcnt > 1)
184 goto out_unlock;
185
186 bh = apfs_sb_bread(sb, APFS_NX_BLOCK_NUM);
187 if (!bh) {
188 apfs_err(sb, "failed to write block zero");
189 goto out_unlock;
190 }
191 memcpy(bh->b_data, nxi->nx_raw, sb->s_blocksize);
192 mark_buffer_dirty(bh);
193 brelse(bh);
194 out_unlock:
195 mutex_unlock(&nxs_mutex);
196 }
197
198 static int apfs_check_nx_features(struct super_block *sb);
199 static void apfs_set_trans_buffer_limit(struct super_block *sb);
200
201 #if LINUX_VERSION_CODE < KERNEL_VERSION(5, 7, 0)
202 static inline void import_uuid(uuid_t *dst, const __u8 *src)
203 {
204 memcpy(dst, src, sizeof(uuid_t));
205 }
206 #endif
207
208 /**
209 * apfs_check_fusion_uuid - Verify that the main and tier 2 devices match
210 * @sb: filesystem superblock
211 *
212 * Returns 0 on success, or a negative error code in case of failure.
213 */
214 static int apfs_check_fusion_uuid(struct super_block *sb)
215 {
216 struct apfs_nxsb_info *nxi = NULL;
217 struct apfs_nx_superblock *main_raw = NULL, *tier2_raw = NULL;
218 uuid_t main_uuid, tier2_uuid;
219 struct buffer_head *bh = NULL;
220
221 nxi = APFS_NXI(sb);
222 main_raw = nxi->nx_raw;
223 if (!main_raw) {
224 apfs_alert(sb, "fusion uuid checks are misplaced");
225 return -EINVAL;
226 }
227 import_uuid(&main_uuid, main_raw->nx_fusion_uuid);
228 main_raw = NULL;
229
230 if (!nxi->nx_tier2_info) {
231 /* Not a fusion drive */
232 if (!uuid_is_null(&main_uuid)) {
233 apfs_err(sb, "fusion uuid on a regular drive");
234 return -EFSCORRUPTED;
235 }
236 return 0;
237 }
238 if (uuid_is_null(&main_uuid)) {
239 apfs_err(sb, "no fusion uuid on fusion drive");
240 return -EFSCORRUPTED;
241 }
242
243 /* Tier 2 also has a copy of the superblock in block zero */
244 bh = apfs_sb_bread(sb, nxi->nx_tier2_bno);
245 if (IS_ERR(bh))
246 return PTR_ERR(bh);
247 tier2_raw = (struct apfs_nx_superblock *)bh->b_data;
248 import_uuid(&tier2_uuid, tier2_raw->nx_fusion_uuid);
249 brelse(bh);
250 bh = NULL;
251 tier2_raw = NULL;
252
253 /*
254 * The only difference between both superblocks (other than the
255 * checksum) is this one bit here, so it can be used to tell which is
256 * main and which is tier 2. By the way, the reference seems to have
257 * this backwards.
258 */
259 if (main_uuid.b[15] & 0x01) {
260 apfs_warn(sb, "bad bit on main device - are you mixing up main and tier 2?");
261 return -EINVAL;
262 }
263 if (!(tier2_uuid.b[15] & 0x01)) {
264 apfs_warn(sb, "bad bit on tier 2 device - are you mixing up main and tier 2?");
265 return -EINVAL;
266 }
267 tier2_uuid.b[15] &= ~0x01;
268 if (!uuid_equal(&main_uuid, &tier2_uuid)) {
269 apfs_warn(sb, "the devices are not part of the same fusion drive");
270 return -EINVAL;
271 }
272 return 0;
273 }
274
275 /**
276 * apfs_read_main_super - Find the container superblock and read it into memory
277 * @sb: superblock structure
278 *
279 * Returns a negative error code in case of failure. On success, returns 0
280 * and sets the nx_raw and nx_xid fields of APFS_NXI(@sb).
281 */
282 static int apfs_read_main_super(struct super_block *sb)
283 {
284 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
285 struct buffer_head *bh = NULL;
286 struct buffer_head *desc_bh = NULL;
287 struct apfs_nx_superblock *msb_raw;
288 u64 xid, bno = APFS_NX_BLOCK_NUM;
289 u64 desc_base;
290 u32 desc_blocks;
291 int err = -EINVAL;
292 int i;
293
294 mutex_lock(&nxs_mutex);
295
296 if (nxi->nx_blocksize) {
297 /* It's already mapped */
298 sb->s_blocksize = nxi->nx_blocksize;
299 sb->s_blocksize_bits = nxi->nx_blocksize_bits;
300 sb->s_magic = le32_to_cpu(nxi->nx_raw->nx_magic);
301 err = 0;
302 goto out;
303 }
304
305 /*
306 * We won't know the block size until we read the backup superblock,
307 * so we can't set this up correctly yet. But we do know that the
308 * backup superblock itself is always in the main device.
309 */
310 nxi->nx_tier2_bno = APFS_NX_BLOCK_NUM + 1;
311
312 /* Read the superblock from the last clean unmount */
313 bh = apfs_read_super_copy(sb);
314 if (IS_ERR(bh)) {
315 err = PTR_ERR(bh);
316 bh = NULL;
317 goto out;
318 }
319 msb_raw = (struct apfs_nx_superblock *)bh->b_data;
320
321 /*
322 * Now that we confirmed the block size, we can set this up for real.
323 * It's important to do this early because I don't know which mount
324 * objects could get moved to tier 2.
325 */
326 nxi->nx_tier2_bno = APFS_FUSION_TIER2_DEVICE_BYTE_ADDR >> sb->s_blocksize_bits;
327
328 /* We want to mount the latest valid checkpoint among the descriptors */
329 desc_base = le64_to_cpu(msb_raw->nx_xp_desc_base);
330 if (desc_base >> 63 != 0) {
331 /* The highest bit is set when checkpoints are not contiguous */
332 apfs_err(sb, "checkpoint descriptor tree not yet supported");
333 goto out;
334 }
335 desc_blocks = le32_to_cpu(msb_raw->nx_xp_desc_blocks);
336 if (desc_blocks > 10000) { /* Arbitrary loop limit, is it enough? */
337 apfs_err(sb, "too many checkpoint descriptors?");
338 err = -EFSCORRUPTED;
339 goto out;
340 }
341
342 /* Now we go through the checkpoints one by one */
343 xid = le64_to_cpu(msb_raw->nx_o.o_xid);
344 for (i = 0; i < desc_blocks; ++i) {
345 struct apfs_nx_superblock *desc_raw;
346
347 brelse(desc_bh);
348 desc_bh = apfs_sb_bread(sb, desc_base + i);
349 if (!desc_bh) {
350 apfs_err(sb, "unable to read checkpoint descriptor");
351 goto out;
352 }
353 desc_raw = (struct apfs_nx_superblock *)desc_bh->b_data;
354
355 if (le32_to_cpu(desc_raw->nx_magic) != APFS_NX_MAGIC)
356 continue; /* Not a superblock */
357 if (le64_to_cpu(desc_raw->nx_o.o_xid) <= xid)
358 continue; /* Old */
359 if (!apfs_obj_verify_csum(sb, desc_bh))
360 continue; /* Corrupted */
361
362 xid = le64_to_cpu(desc_raw->nx_o.o_xid);
363 msb_raw = desc_raw;
364 bno = desc_base + i;
365 brelse(bh);
366 bh = desc_bh;
367 desc_bh = NULL;
368 }
369
370 nxi->nx_raw = kmalloc(sb->s_blocksize, GFP_KERNEL);
371 if (!nxi->nx_raw) {
372 err = -ENOMEM;
373 goto out;
374 }
375 memcpy(nxi->nx_raw, bh->b_data, sb->s_blocksize);
376 nxi->nx_bno = bno;
377 nxi->nx_xid = xid;
378
379 /* For now we only support blocksize < PAGE_SIZE */
380 nxi->nx_blocksize = sb->s_blocksize;
381 nxi->nx_blocksize_bits = sb->s_blocksize_bits;
382 apfs_set_trans_buffer_limit(sb);
383
384 err = apfs_check_nx_features(sb);
385 if (err)
386 goto out;
387
388 /*
389 * This check is technically too late: if main and tier 2 are backwards
390 * then we have already attempted (and failed) to read the checkpoint
391 * from tier 2. This may lead to a confusing error message if tier 2
392 * is absurdly tiny, not a big deal.
393 */
394 err = apfs_check_fusion_uuid(sb);
395 if (err)
396 goto out;
397
398 out:
399 brelse(bh);
400 mutex_unlock(&nxs_mutex);
401 return err;
402 }
403
404 /**
405 * apfs_update_software_info - Write the module info to a modified volume
406 * @sb: superblock structure
407 *
408 * Writes this module's information to index zero of the apfs_modified_by
409 * array, shifting the rest of the entries to the right.
410 */
411 static void apfs_update_software_info(struct super_block *sb)
412 {
413 struct apfs_sb_info *sbi = APFS_SB(sb);
414 struct apfs_superblock *raw = sbi->s_vsb_raw;
415 struct apfs_modified_by *mod_by;
416
417 ASSERT(sbi->s_vsb_raw);
418 apfs_assert_in_transaction(sb, &raw->apfs_o);
419 ASSERT(strlen(APFS_MODULE_ID_STRING) < APFS_MODIFIED_NAMELEN);
420 mod_by = raw->apfs_modified_by;
421
422 memmove(mod_by + 1, mod_by, (APFS_MAX_HIST - 1) * sizeof(*mod_by));
423 memset(mod_by->id, 0, sizeof(mod_by->id));
424 strscpy(mod_by->id, APFS_MODULE_ID_STRING, sizeof(mod_by->id));
425 mod_by->timestamp = cpu_to_le64(ktime_get_real_ns());
426 mod_by->last_xid = cpu_to_le64(APFS_NXI(sb)->nx_xid);
427 }
428
429 static struct file_system_type apfs_fs_type;
430
431 /**
432 * apfs_blkdev_cleanup - Clean up after a block device
433 * @info: info struct to clean up
434 */
435 static void apfs_blkdev_cleanup(struct apfs_blkdev_info *info)
436 {
437 if (!info)
438 return;
439
440 #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 9, 0) || RHEL_VERSION_GE(9, 5)
441 fput(info->blki_bdev_file);
442 info->blki_bdev_file = NULL;
443 #elif LINUX_VERSION_CODE >= KERNEL_VERSION(6, 8, 0)
444 bdev_release(info->blki_bdev_handle);
445 info->blki_bdev_handle = NULL;
446 #elif LINUX_VERSION_CODE >= KERNEL_VERSION(6, 5, 0) || RHEL_VERSION_GE(9, 4)
447 blkdev_put(info->blki_bdev, &apfs_fs_type);
448 #else
449 blkdev_put(info->blki_bdev, info->blki_mode);
450 #endif
451 info->blki_bdev = NULL;
452
453 kfree(info->blki_path);
454 info->blki_path = NULL;
455 kfree(info);
456 }
457
458 /**
459 * apfs_free_main_super - Clean up apfs_read_main_super()
460 * @sbi: in-memory superblock info
461 *
462 * It also cleans up after apfs_attach_nxi(), so the name is no longer accurate.
463 */
464 static inline void apfs_free_main_super(struct apfs_sb_info *sbi)
465 {
466 struct apfs_nxsb_info *nxi = sbi->s_nxi;
467 struct apfs_ephemeral_object_info *eph_list = NULL;
468 struct apfs_spaceman *sm = NULL;
469 u32 bmap_idx;
470 int i;
471
472 if (!nxi)
473 return;
474
475 mutex_lock(&nxs_mutex);
476
477 list_del(&sbi->list);
478 if (--nxi->nx_refcnt)
479 goto out;
480
481 /* Clean up all the ephemeral objects in memory */
482 eph_list = nxi->nx_eph_list;
483 if (eph_list) {
484 for (i = 0; i < nxi->nx_eph_count; ++i) {
485 kfree(eph_list[i].object);
486 eph_list[i].object = NULL;
487 }
488 kfree(eph_list);
489 eph_list = nxi->nx_eph_list = NULL;
490 nxi->nx_eph_count = 0;
491 }
492
493 kfree(nxi->nx_raw);
494 nxi->nx_raw = NULL;
495
496 apfs_blkdev_cleanup(nxi->nx_blkdev_info);
497 nxi->nx_blkdev_info = NULL;
498 apfs_blkdev_cleanup(nxi->nx_tier2_info);
499 nxi->nx_tier2_info = NULL;
500
501 list_del(&nxi->nx_list);
502 sm = nxi->nx_spaceman;
503 if (sm) {
504 for (bmap_idx = 0; bmap_idx < sm->sm_ip_bmaps_count; ++bmap_idx) {
505 kfree(sm->sm_ip_bmaps[bmap_idx].block);
506 sm->sm_ip_bmaps[bmap_idx].block = NULL;
507 }
508 kfree(sm);
509 nxi->nx_spaceman = sm = NULL;
510 }
511 kfree(nxi);
512 out:
513 sbi->s_nxi = NULL;
514 mutex_unlock(&nxs_mutex);
515 }
516
517 /**
518 * apfs_map_volume_super_bno - Map a block containing a volume superblock
519 * @sb: superblock structure
520 * @bno: block to map
521 * @check: verify the checksum?
522 */
523 int apfs_map_volume_super_bno(struct super_block *sb, u64 bno, bool check)
524 {
525 struct apfs_sb_info *sbi = APFS_SB(sb);
526 struct apfs_superblock *vsb_raw = NULL;
527 struct buffer_head *bh = NULL;
528 int err;
529
530 bh = apfs_sb_bread(sb, bno);
531 if (!bh) {
532 apfs_err(sb, "unable to read volume superblock");
533 return -EINVAL;
534 }
535
536 vsb_raw = (struct apfs_superblock *)bh->b_data;
537 if (le32_to_cpu(vsb_raw->apfs_magic) != APFS_MAGIC) {
538 apfs_err(sb, "wrong magic in volume superblock");
539 err = -EINVAL;
540 goto fail;
541 }
542
543 /*
544 * XXX: apfs_omap_lookup_block() only runs this check when write
545 * is true, but it should always do it.
546 */
547 if (check && !apfs_obj_verify_csum(sb, bh)) {
548 apfs_err(sb, "inconsistent volume superblock");
549 err = -EFSBADCRC;
550 goto fail;
551 }
552
553 sbi->s_vsb_raw = vsb_raw;
554 sbi->s_vobject.sb = sb;
555 sbi->s_vobject.block_nr = bno;
556 sbi->s_vobject.oid = le64_to_cpu(vsb_raw->apfs_o.o_oid);
557 brelse(sbi->s_vobject.o_bh);
558 sbi->s_vobject.o_bh = bh;
559 sbi->s_vobject.data = bh->b_data;
560 return 0;
561
562 fail:
563 brelse(bh);
564 return err;
565 }
566
567 /**
568 * apfs_alloc_omap - Allocate and initialize an object map struct
569 *
570 * Returns the struct, or NULL in case of allocation failure.
571 */
572 static struct apfs_omap *apfs_alloc_omap(void)
573 {
574 struct apfs_omap *omap = NULL;
575 struct apfs_omap_cache *cache = NULL;
576
577 omap = kzalloc(sizeof(*omap), GFP_KERNEL);
578 if (!omap)
579 return NULL;
580 cache = &omap->omap_cache;
581 spin_lock_init(&cache->lock);
582 return omap;
583 }
584
585 /**
586 * apfs_map_volume_super - Find the volume superblock and map it into memory
587 * @sb: superblock structure
588 * @write: request write access?
589 *
590 * Returns a negative error code in case of failure. On success, returns 0
591 * and sets APFS_SB(@sb)->s_vsb_raw and APFS_SB(@sb)->s_vobject.
592 */
593 int apfs_map_volume_super(struct super_block *sb, bool write)
594 {
595 struct apfs_sb_info *sbi = APFS_SB(sb);
596 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
597 struct apfs_nx_superblock *msb_raw = nxi->nx_raw;
598 struct apfs_omap_phys *msb_omap_raw;
599 struct apfs_omap *omap = NULL;
600 struct apfs_node *vnode;
601 struct buffer_head *bh;
602 u64 vol_id;
603 u64 vsb;
604 int err;
605
606 ASSERT(msb_raw);
607
608 /* Get the id for the requested volume number */
609 if (sbi->s_vol_nr >= APFS_NX_MAX_FILE_SYSTEMS) {
610 apfs_err(sb, "volume number out of range");
611 return -EINVAL;
612 }
613 vol_id = le64_to_cpu(msb_raw->nx_fs_oid[sbi->s_vol_nr]);
614 if (vol_id == 0) {
615 apfs_err(sb, "requested volume does not exist");
616 return -EINVAL;
617 }
618
619 /* Get the container's object map */
620 bh = apfs_read_object_block(sb, le64_to_cpu(msb_raw->nx_omap_oid),
621 write, false /* preserve */);
622 if (IS_ERR(bh)) {
623 apfs_err(sb, "unable to read container object map");
624 return PTR_ERR(bh);
625 }
626 if (write) {
627 ASSERT(buffer_trans(bh));
628 msb_raw->nx_omap_oid = cpu_to_le64(bh->b_blocknr);
629 }
630 msb_omap_raw = (struct apfs_omap_phys *)bh->b_data;
631
632 /* Get the root node for the container's omap */
633 vnode = apfs_read_node(sb, le64_to_cpu(msb_omap_raw->om_tree_oid),
634 APFS_OBJ_PHYSICAL, write);
635 if (IS_ERR(vnode)) {
636 apfs_err(sb, "unable to read volume block");
637 err = PTR_ERR(vnode);
638 goto fail;
639 }
640 if (write) {
641 ASSERT(buffer_trans(bh));
642 msb_omap_raw->om_tree_oid = cpu_to_le64(vnode->object.block_nr);
643 }
644 msb_omap_raw = NULL;
645 brelse(bh);
646 bh = NULL;
647
648 omap = apfs_alloc_omap();
649 if (!omap) {
650 apfs_node_free(vnode);
651 return -ENOMEM;
652 }
653 omap->omap_root = vnode;
654
655 err = apfs_omap_lookup_block(sb, omap, vol_id, &vsb, write);
656 apfs_node_free(vnode);
657 vnode = NULL;
658 kfree(omap);
659 omap = NULL;
660 if (err) {
661 apfs_err(sb, "volume not found, likely corruption");
662 return err;
663 }
664
665 /*
666 * Snapshots could get mounted during a transaction, so the fletcher
667 * checksum doesn't have to be valid.
668 */
669 return apfs_map_volume_super_bno(sb, vsb, !write && !sbi->s_snap_name);
670
671 fail:
672 brelse(bh);
673 return err;
674 }
675
676 /**
677 * apfs_unmap_volume_super - Clean up apfs_map_volume_super()
678 * @sb: filesystem superblock
679 */
680 void apfs_unmap_volume_super(struct super_block *sb)
681 {
682 struct apfs_sb_info *sbi = APFS_SB(sb);
683 struct apfs_object *obj = &sbi->s_vobject;
684
685 obj->data = NULL;
686 brelse(obj->o_bh);
687 obj->o_bh = NULL;
688 }
689
690 /**
691 * apfs_get_omap - Get a reference to the omap, if it's already read
692 * @sb: filesystem superblock
693 *
694 * Returns the omap struct, or NULL on failure.
695 */
696 static struct apfs_omap *apfs_get_omap(struct super_block *sb)
697 {
698 struct apfs_sb_info *sbi = APFS_SB(sb);
699 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
700 struct apfs_sb_info *curr = NULL;
701 struct apfs_omap *omap = NULL;
702 struct apfs_omap_cache *cache = NULL;
703
704 lockdep_assert_held(&nxs_mutex);
705
706 list_for_each_entry(curr, &nxi->vol_list, list) {
707 if (curr == sbi)
708 continue;
709 if (curr->s_vol_nr == sbi->s_vol_nr) {
710 omap = curr->s_omap;
711 if (!omap) {
712 /*
713 * This volume has already gone through
714 * apfs_attach_nxi(), but its omap is either
715 * not yet read or already put.
716 */
717 continue;
718 }
719 cache = &omap->omap_cache;
720 ++omap->omap_refcnt;
721 /* Right now the cache can't be shared like this */
722 cache->disabled = true;
723 return omap;
724 }
725 }
726 return NULL;
727 }
728
729 /**
730 * apfs_read_omap - Find and read the omap root node
731 * @sb: superblock structure
732 * @write: request write access?
733 *
734 * On success, returns 0 and sets the fields of APFS_SB(@sb)->s_omap; on failure
735 * returns a negative error code.
736 */
737 int apfs_read_omap(struct super_block *sb, bool write)
738 {
739 struct apfs_sb_info *sbi = APFS_SB(sb);
740 struct apfs_superblock *vsb_raw = sbi->s_vsb_raw;
741 struct apfs_omap_phys *omap_raw;
742 struct apfs_node *omap_root;
743 struct apfs_omap *omap = NULL;
744 struct buffer_head *bh;
745 u64 omap_blk;
746 int err;
747
748 ASSERT(sbi->s_vsb_raw);
749
750 ASSERT(sbi->s_omap);
751 omap = sbi->s_omap;
752
753 /* Get the block holding the volume omap information */
754 omap_blk = le64_to_cpu(vsb_raw->apfs_omap_oid);
755 bh = apfs_read_object_block(sb, omap_blk, write, false /* preserve */);
756 if (IS_ERR(bh)) {
757 apfs_err(sb, "unable to read the volume object map");
758 return PTR_ERR(bh);
759 }
760 if (write) {
761 apfs_assert_in_transaction(sb, &vsb_raw->apfs_o);
762 vsb_raw->apfs_omap_oid = cpu_to_le64(bh->b_blocknr);
763 }
764 omap_raw = (struct apfs_omap_phys *)bh->b_data;
765
766 /* Get the volume's object map */
767 omap_root = apfs_read_node(sb, le64_to_cpu(omap_raw->om_tree_oid),
768 APFS_OBJ_PHYSICAL, write);
769 if (IS_ERR(omap_root)) {
770 apfs_err(sb, "unable to read the omap root node");
771 err = PTR_ERR(omap_root);
772 goto fail;
773 }
774 if (write) {
775 apfs_assert_in_transaction(sb, &omap_raw->om_o);
776 ASSERT(buffer_trans(bh));
777 omap_raw->om_tree_oid = cpu_to_le64(omap_root->object.block_nr);
778 }
779 omap->omap_latest_snap = le64_to_cpu(omap_raw->om_most_recent_snap);
780 omap_raw = NULL;
781 brelse(bh);
782
783 if (omap->omap_root)
784 apfs_node_free(omap->omap_root);
785 omap->omap_root = omap_root;
786 return 0;
787
788 fail:
789 brelse(bh);
790 return err;
791 }
792
793 /**
794 * apfs_first_read_omap - Find and read the omap root node during mount
795 * @sb: superblock structure
796 *
797 * On success, returns 0 and sets APFS_SB(@sb)->s_omap; on failure returns a
798 * negative error code.
799 */
800 static int apfs_first_read_omap(struct super_block *sb)
801 {
802 struct apfs_sb_info *sbi = NULL;
803 struct apfs_omap *omap = NULL;
804 int err;
805
806 /*
807 * For each volume, the first mount that gets here is responsible
808 * for reading the omap. Other mounts (for other snapshots) just
809 * go through the container's volume list to retrieve it. This results
810 * in coarse locking as usual: with some thought it would be possible
811 * to allow other volumes to read their own omaps at the same time,
812 * but I don't see the point.
813 */
814 mutex_lock(&nxs_mutex);
815
816 sbi = APFS_SB(sb);
817
818 /* The current transaction and all snapshots share a single omap */
819 omap = apfs_get_omap(sb);
820 if (omap) {
821 sbi->s_omap = omap;
822 err = 0;
823 goto out;
824 }
825
826 omap = apfs_alloc_omap();
827 if (!omap) {
828 err = -ENOMEM;
829 goto out;
830 }
831
832 sbi->s_omap = omap;
833 err = apfs_read_omap(sb, false /* write */);
834 if (err) {
835 kfree(omap);
836 sbi->s_omap = NULL;
837 goto out;
838 }
839
840 ++omap->omap_refcnt;
841 err = 0;
842 out:
843 mutex_unlock(&nxs_mutex);
844 return err;
845 }
846
847 /**
848 * apfs_unset_omap - Unset the object map in a superblock
849 * @sb: superblock structure
850 *
851 * Shrinks the omap reference, frees the omap if needed, and sets the field to
852 * NULL atomically in relation to apfs_first_read_omap(). So, no other mount
853 * can grab a new reference halfway through.
854 */
855 static void apfs_unset_omap(struct super_block *sb)
856 {
857 struct apfs_omap **omap_p = NULL;
858 struct apfs_omap *omap = NULL;
859
860 omap_p = &APFS_SB(sb)->s_omap;
861 omap = *omap_p;
862 if (!omap)
863 return;
864
865 mutex_lock(&nxs_mutex);
866
867 if (--omap->omap_refcnt != 0)
868 goto out;
869
870 apfs_node_free(omap->omap_root);
871 kfree(omap);
872 out:
873 *omap_p = NULL;
874 mutex_unlock(&nxs_mutex);
875 }
876
877 /**
878 * apfs_read_catalog - Find and read the catalog root node
879 * @sb: superblock structure
880 * @write: request write access?
881 *
882 * On success, returns 0 and sets APFS_SB(@sb)->s_cat_root; on failure returns
883 * a negative error code.
884 */
885 int apfs_read_catalog(struct super_block *sb, bool write)
886 {
887 struct apfs_sb_info *sbi = APFS_SB(sb);
888 struct apfs_superblock *vsb_raw = sbi->s_vsb_raw;
889 struct apfs_node *root_node;
890
891 ASSERT(sbi->s_omap && sbi->s_omap->omap_root);
892
893 root_node = apfs_read_node(sb, le64_to_cpu(vsb_raw->apfs_root_tree_oid),
894 APFS_OBJ_VIRTUAL, write);
895 if (IS_ERR(root_node)) {
896 apfs_err(sb, "unable to read catalog root node");
897 return PTR_ERR(root_node);
898 }
899
900 if (sbi->s_cat_root)
901 apfs_node_free(sbi->s_cat_root);
902 sbi->s_cat_root = root_node;
903 return 0;
904 }
905
906 static void apfs_put_super(struct super_block *sb)
907 {
908 struct apfs_sb_info *sbi = APFS_SB(sb);
909 struct apfs_nx_transaction *trans = NULL;
910
911 /* Cleanups won't reschedule themselves during unmount */
912 flush_work(&sbi->s_orphan_cleanup_work);
913
914 /* We are about to commit anyway */
915 trans = &APFS_NXI(sb)->nx_transaction;
916 cancel_delayed_work_sync(&trans->t_work);
917
918 /* Stop flushing orphans and update the volume as needed */
919 if (!(sb->s_flags & SB_RDONLY)) {
920 struct apfs_superblock *vsb_raw;
921 struct buffer_head *vsb_bh;
922 int err;
923
924 err = apfs_transaction_start(sb, APFS_TRANS_SYNC);
925 if (err) {
926 apfs_err(sb, "unmount transaction start failed (err:%d)", err);
927 goto fail;
928 }
929 vsb_raw = sbi->s_vsb_raw;
930 vsb_bh = sbi->s_vobject.o_bh;
931
932 apfs_assert_in_transaction(sb, &vsb_raw->apfs_o);
933 ASSERT(buffer_trans(vsb_bh));
934
935 apfs_update_software_info(sb);
936 vsb_raw->apfs_unmount_time = cpu_to_le64(ktime_get_real_ns());
937 set_buffer_csum(vsb_bh);
938
939 /* Guarantee commit */
940 sbi->s_nxi->nx_transaction.t_state |= APFS_NX_TRANS_FORCE_COMMIT;
941 err = apfs_transaction_commit(sb);
942 if (err) {
943 apfs_err(sb, "unmount transaction commit failed (err:%d)", err);
944 apfs_transaction_abort(sb);
945 goto fail;
946 }
947 }
948
949 /*
950 * Even if this particular volume/snapshot was read-only, the container
951 * may have changed and need an update here.
952 */
953 apfs_make_super_copy(sb);
954
955 fail:
956 /*
957 * This is essentially the cleanup for apfs_fill_super(). It goes here
958 * because generic_shutdown_super() only calls ->put_super() when the
959 * root dentry has been set, that is, when apfs_fill_super() succeeded.
960 * The rest of the mount cleanup is done directly by ->kill_sb().
961 */
962 iput(sbi->s_private_dir);
963 sbi->s_private_dir = NULL;
964 apfs_node_free(sbi->s_cat_root);
965 sbi->s_cat_root = NULL;
966 apfs_unset_omap(sb);
967 apfs_unmap_volume_super(sb);
968 }
969
970 static struct kmem_cache *apfs_inode_cachep;
971
972 static struct inode *apfs_alloc_inode(struct super_block *sb)
973 {
974 struct apfs_inode_info *ai;
975 struct apfs_dstream_info *dstream;
976
977 #if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 18, 0) || RHEL_VERSION_GE(9, 1)
978 ai = alloc_inode_sb(sb, apfs_inode_cachep, GFP_KERNEL);
979 #else
980 ai = kmem_cache_alloc(apfs_inode_cachep, GFP_KERNEL);
981 #endif
982 if (!ai)
983 return NULL;
984 dstream = &ai->i_dstream;
985 #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 16, 0) /* iversion came in 4.16 */
986 inode_set_iversion(&ai->vfs_inode, 1);
987 #else
988 ai->vfs_inode.i_version = 1;
989 #endif
990 dstream->ds_sb = sb;
991 dstream->ds_inode = &ai->vfs_inode;
992 dstream->ds_cached_ext.len = 0;
993 dstream->ds_ext_dirty = false;
994 ai->i_nchildren = 0;
995 INIT_LIST_HEAD(&ai->i_list);
996 ai->i_cleaned = false;
997 return &ai->vfs_inode;
998 }
999
1000 static void apfs_i_callback(struct rcu_head *head)
1001 {
1002 struct inode *inode = container_of(head, struct inode, i_rcu);
1003
1004 kmem_cache_free(apfs_inode_cachep, APFS_I(inode));
1005 }
1006
1007 static void apfs_destroy_inode(struct inode *inode)
1008 {
1009 call_rcu(&inode->i_rcu, apfs_i_callback);
1010 }
1011
1012 static void init_once(void *p)
1013 {
1014 struct apfs_inode_info *ai = (struct apfs_inode_info *)p;
1015 struct apfs_dstream_info *dstream = &ai->i_dstream;
1016
1017 spin_lock_init(&dstream->ds_ext_lock);
1018 inode_init_once(&ai->vfs_inode);
1019 }
1020
1021 #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 9, 0)
1022 #define SLAB_MEM_SPREAD 0
1023 #endif
1024
1025 static int __init init_inodecache(void)
1026 {
1027 apfs_inode_cachep = kmem_cache_create("apfs_inode_cache",
1028 sizeof(struct apfs_inode_info),
1029 0, (SLAB_RECLAIM_ACCOUNT|
1030 SLAB_MEM_SPREAD|SLAB_ACCOUNT),
1031 init_once);
1032 if (apfs_inode_cachep == NULL)
1033 return -ENOMEM;
1034 return 0;
1035 }
1036
1037 static int apfs_write_inode(struct inode *inode, struct writeback_control *wbc)
1038 {
1039 struct super_block *sb = inode->i_sb;
1040 struct apfs_nxsb_info *nxi = APFS_SB(sb)->s_nxi;
1041 int err;
1042
1043 err = apfs_transaction_start(sb, APFS_TRANS_REG);
1044 if (err)
1045 return err;
1046 err = apfs_update_inode(inode, NULL /* new_name */);
1047 if (err)
1048 goto fail;
1049 /* Don't commit yet, or the inode will get flushed again and lock up */
1050 nxi->nx_transaction.t_state |= APFS_NX_TRANS_DEFER_COMMIT;
1051 err = apfs_transaction_commit(sb);
1052 if (err)
1053 goto fail;
1054 return 0;
1055
1056 fail:
1057 apfs_transaction_abort(sb);
1058 return err;
1059 }
1060
1061 static void destroy_inodecache(void)
1062 {
1063 /*
1064 * Make sure all delayed rcu free inodes are flushed before we
1065 * destroy cache.
1066 */
1067 rcu_barrier();
1068 kmem_cache_destroy(apfs_inode_cachep);
1069 }
1070
1071 static int apfs_statfs(struct dentry *dentry, struct kstatfs *buf)
1072 {
1073 struct super_block *sb = dentry->d_sb;
1074 struct apfs_sb_info *sbi = APFS_SB(sb);
1075 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
1076 struct apfs_nx_superblock *msb_raw;
1077 struct apfs_superblock *vol;
1078 u64 fsid, free_blocks;
1079 int err;
1080
1081 down_read(&nxi->nx_big_sem);
1082 msb_raw = nxi->nx_raw;
1083 vol = sbi->s_vsb_raw;
1084
1085 buf->f_type = APFS_NX_MAGIC;
1086 /* Nodes are assumed to fit in a page, for now */
1087 buf->f_bsize = sb->s_blocksize;
1088
1089 /* Volumes share the whole disk space */
1090 buf->f_blocks = le64_to_cpu(msb_raw->nx_block_count);
1091 /*
1092 * It takes some work to retrieve the free block count because we
1093 * can't assume that the spaceman has been read yet. It would be
1094 * cleaner if we always did that on first mount (TODO).
1095 */
1096 err = apfs_spaceman_get_free_blkcnt(sb, &free_blocks);
1097 if (err)
1098 goto fail;
1099 buf->f_bfree = free_blocks;
1100 buf->f_bavail = free_blocks;
1101
1102 /* The file count is only for the mounted volume */
1103 buf->f_files = le64_to_cpu(vol->apfs_num_files) +
1104 le64_to_cpu(vol->apfs_num_directories) +
1105 le64_to_cpu(vol->apfs_num_symlinks) +
1106 le64_to_cpu(vol->apfs_num_other_fsobjects);
1107
1108 /*
1109 * buf->f_ffree is left undefined for now. Maybe it should report the
1110 * number of available cnids, like hfsplus attempts to do.
1111 */
1112
1113 buf->f_namelen = APFS_NAME_LEN;
1114
1115 /* There are no clear rules for the fsid, so we follow ext2 here */
1116 fsid = le64_to_cpup((void *)vol->apfs_vol_uuid) ^
1117 le64_to_cpup((void *)vol->apfs_vol_uuid + sizeof(u64));
1118 buf->f_fsid.val[0] = fsid & 0xFFFFFFFFUL;
1119 buf->f_fsid.val[1] = (fsid >> 32) & 0xFFFFFFFFUL;
1120
1121 fail:
1122 up_read(&nxi->nx_big_sem);
1123 return err;
1124 }
1125
1126 static int apfs_show_options(struct seq_file *seq, struct dentry *root)
1127 {
1128 struct apfs_sb_info *sbi = APFS_SB(root->d_sb);
1129 struct apfs_nxsb_info *nxi = APFS_NXI(root->d_sb);
1130
1131 if (sbi->s_vol_nr != 0)
1132 seq_printf(seq, ",vol=%u", sbi->s_vol_nr);
1133 if (sbi->s_snap_name)
1134 seq_printf(seq, ",snap=%s", sbi->s_snap_name);
1135 if (uid_valid(sbi->s_uid))
1136 seq_printf(seq, ",uid=%u", from_kuid(&init_user_ns,
1137 sbi->s_uid));
1138 if (gid_valid(sbi->s_gid))
1139 seq_printf(seq, ",gid=%u", from_kgid(&init_user_ns,
1140 sbi->s_gid));
1141 if (nxi->nx_flags & APFS_CHECK_NODES)
1142 seq_puts(seq, ",cknodes");
1143 if (nxi->nx_tier2_info)
1144 seq_printf(seq, ",tier2=%s", nxi->nx_tier2_info->blki_path);
1145
1146 return 0;
1147 }
1148
1149 int apfs_sync_fs(struct super_block *sb, int wait)
1150 {
1151 int err;
1152
1153 /* TODO: actually start the commit and return without waiting? */
1154 if (wait == 0)
1155 return 0;
1156
1157 err = apfs_transaction_start(sb, APFS_TRANS_SYNC);
1158 if (err)
1159 return err;
1160 APFS_SB(sb)->s_nxi->nx_transaction.t_state |= APFS_NX_TRANS_FORCE_COMMIT;
1161 err = apfs_transaction_commit(sb);
1162 if (err)
1163 apfs_transaction_abort(sb);
1164 return err;
1165 }
1166
1167 /* Only supports read-only remounts, everything else is silently ignored */
1168 static int apfs_remount(struct super_block *sb, int *flags, char *data)
1169 {
1170 int err = 0;
1171
1172 err = sync_filesystem(sb);
1173 if (err)
1174 return err;
1175
1176 /* TODO: race? Could a new transaction have started already? */
1177 if (*flags & SB_RDONLY)
1178 sb->s_flags |= SB_RDONLY;
1179
1180 /*
1181 * TODO: readwrite remounts seem simple enough, but I worry about
1182 * remounting aborted transactions. I would probably also need a
1183 * dry-run version of parse_options().
1184 */
1185 apfs_notice(sb, "all remounts can do is turn a volume read-only");
1186 return 0;
1187 }
1188
1189 static const struct super_operations apfs_sops = {
1190 .alloc_inode = apfs_alloc_inode,
1191 .destroy_inode = apfs_destroy_inode,
1192 .write_inode = apfs_write_inode,
1193 .evict_inode = apfs_evict_inode,
1194 .put_super = apfs_put_super,
1195 .sync_fs = apfs_sync_fs,
1196 .statfs = apfs_statfs,
1197 #if LINUX_VERSION_CODE < KERNEL_VERSION(7, 0, 0)
1198 .remount_fs = apfs_remount,
1199 #endif
1200 .show_options = apfs_show_options,
1201 };
1202
1203 enum {
1204 Opt_readwrite, Opt_cknodes, Opt_uid, Opt_gid, Opt_vol, Opt_snap, Opt_tier2, Opt_err,
1205 };
1206
1207 #if LINUX_VERSION_CODE < KERNEL_VERSION(7, 0, 0)
1208 static const match_table_t tokens = {
1209 {Opt_readwrite, "readwrite"},
1210 {Opt_cknodes, "cknodes"},
1211 {Opt_uid, "uid=%u"},
1212 {Opt_gid, "gid=%u"},
1213 {Opt_vol, "vol=%u"},
1214 {Opt_snap, "snap=%s"},
1215 {Opt_tier2, "tier2=%s"},
1216 {Opt_err, NULL}
1217 };
1218 #else
1219 static const struct fs_parameter_spec apfs_param_spec[] = {
1220 fsparam_flag ("readwrite", Opt_readwrite),
1221 fsparam_flag ("cknodes", Opt_cknodes),
1222 fsparam_uid ("uid", Opt_uid),
1223 fsparam_gid ("gid", Opt_gid),
1224 fsparam_u32 ("vol", Opt_vol),
1225 fsparam_string ("snap", Opt_snap),
1226 fsparam_string ("tier2", Opt_tier2),
1227 {}
1228 };
1229 #endif
1230
1231 /**
1232 * apfs_set_nx_flags - Set the mount flags for the container, if allowed
1233 * @sb: superblock structure
1234 * @flags: flags to set
1235 */
1236 static void apfs_set_nx_flags(struct super_block *sb, unsigned int flags)
1237 {
1238 struct apfs_nxsb_info *nxi = APFS_SB(sb)->s_nxi;
1239
1240 mutex_lock(&nxs_mutex);
1241
1242 /* The first mount thet gets here decides the flags for its container */
1243 flags |= APFS_FLAGS_SET;
1244 if (!(nxi->nx_flags & APFS_FLAGS_SET))
1245 nxi->nx_flags = flags;
1246 else if (flags != nxi->nx_flags)
1247 apfs_warn(sb, "ignoring mount flags - container already mounted");
1248
1249 mutex_unlock(&nxs_mutex);
1250 }
1251
1252 static void parse_options_set_flags(struct super_block *sb, struct apfs_sb_info *sbi,
1253 unsigned int nx_flags)
1254 {
1255 struct apfs_nxsb_info *nxi = sbi->s_nxi;
1256
1257 apfs_set_nx_flags(sb, nx_flags);
1258 if (!(sb->s_flags & SB_RDONLY)) {
1259 if (nxi->nx_flags & APFS_READWRITE) {
1260 apfs_notice(sb, "experimental write support is enabled");
1261 } else {
1262 apfs_warn(sb, "experimental writes disabled to avoid data loss");
1263 apfs_warn(sb, "if you really want them, check the README");
1264 sb->s_flags |= SB_RDONLY;
1265 }
1266 }
1267 }
1268
1269 /**
1270 * apfs_set_default_opts - Set the default mount options in the superblock
1271 * @sbi: in-memory superblock info
1272 */
1273 static void apfs_set_default_opts(struct apfs_sb_info *sbi)
1274 {
1275 sbi->s_vol_nr = 0;
1276 sbi->s_snap_name = NULL;
1277 sbi->s_tier2_path = NULL;
1278 sbi->s_mount_opt = 0;
1279 #ifdef CONFIG_APFS_RW_ALWAYS
1280 /* Still risky, but some packagers want writable mounts by default */
1281 sbi->s_mount_opt |= APFS_READWRITE;
1282 #endif
1283 sbi->s_uid = INVALID_UID;
1284 sbi->s_gid = INVALID_GID;
1285 }
1286
1287 #if LINUX_VERSION_CODE < KERNEL_VERSION(7, 0, 0)
1288
1289 /*
1290 * Many of the parse_options() functions in other file systems return 0
1291 * on error. This one returns an error code, and 0 on success.
1292 *
1293 * Note that even on failure, the caller is responsible for freeing all
1294 * superblock fields.
1295 */
1296 static int parse_options(struct apfs_sb_info *sbi, char *options)
1297 {
1298 char *p;
1299 substring_t args[MAX_OPT_ARGS];
1300 int option;
1301 int err = 0;
1302
1303 if (!options)
1304 return 0;
1305
1306 while ((p = strsep(&options, ",")) != NULL) {
1307 int token;
1308
1309 if (!*p)
1310 continue;
1311 token = match_token(p, tokens, args);
1312 switch (token) {
1313 case Opt_readwrite:
1314 /*
1315 * Write support is not safe yet, so keep it disabled
1316 * unless the user requests it explicitly.
1317 */
1318 sbi->s_mount_opt |= APFS_READWRITE;
1319 break;
1320 case Opt_cknodes:
1321 /*
1322 * Right now, node checksums are too costly to enable
1323 * by default. TODO: try to improve this.
1324 */
1325 sbi->s_mount_opt |= APFS_CHECK_NODES;
1326 break;
1327 case Opt_uid:
1328 err = match_int(&args[0], &option);
1329 if (err)
1330 return err;
1331 sbi->s_uid = make_kuid(current_user_ns(), option);
1332 if (!uid_valid(sbi->s_uid)) {
1333 apfs_err(NULL, "invalid uid");
1334 return -EINVAL;
1335 }
1336 break;
1337 case Opt_gid:
1338 err = match_int(&args[0], &option);
1339 if (err)
1340 return err;
1341 sbi->s_gid = make_kgid(current_user_ns(), option);
1342 if (!gid_valid(sbi->s_gid)) {
1343 apfs_err(NULL, "invalid gid");
1344 return -EINVAL;
1345 }
1346 break;
1347 case Opt_vol:
1348 err = match_int(&args[0], &sbi->s_vol_nr);
1349 if (err) {
1350 apfs_err(NULL, "invalid volume number");
1351 return -EINVAL;
1352 }
1353 break;
1354 case Opt_snap:
1355 kfree(sbi->s_snap_name);
1356 sbi->s_snap_name = match_strdup(&args[0]);
1357 if (!sbi->s_snap_name)
1358 return -ENOMEM;
1359 break;
1360 case Opt_tier2:
1361 kfree(sbi->s_tier2_path);
1362 sbi->s_tier2_path = match_strdup(&args[0]);
1363 if (!sbi->s_tier2_path)
1364 return -ENOMEM;
1365 break;
1366 default:
1367 apfs_warn(NULL, "invalid mount option %s", p);
1368 return -EINVAL;
1369 }
1370 }
1371 return 0;
1372 }
1373
1374 #else /* LINUX_VERSION_CODE < KERNEL_VERSION(7, 0, 0) */
1375
1376 static int apfs_parse_param(struct fs_context *fc, struct fs_parameter *param)
1377 {
1378 struct apfs_sb_info *sbi = fc->s_fs_info;
1379 int opt;
1380 struct fs_parse_result result;
1381
1382 opt = fs_parse(fc, apfs_param_spec, param, &result);
1383 if (opt < 0)
1384 return opt;
1385
1386 switch (opt) {
1387 case Opt_readwrite:
1388 /*
1389 * Write support is not safe yet, so keep it disabled
1390 * unless the user requests it explicitly.
1391 */
1392 sbi->s_mount_opt |= APFS_READWRITE;
1393 break;
1394 case Opt_cknodes:
1395 /*
1396 * Right now, node checksums are too costly to enable
1397 * by default. TODO: try to improve this.
1398 */
1399 sbi->s_mount_opt |= APFS_CHECK_NODES;
1400 break;
1401 case Opt_uid:
1402 sbi->s_uid = result.uid;
1403 break;
1404 case Opt_gid:
1405 sbi->s_gid = result.gid;
1406 break;
1407 case Opt_vol:
1408 sbi->s_vol_nr = result.uint_32;
1409 break;
1410 case Opt_snap:
1411 kfree(sbi->s_snap_name);
1412 sbi->s_snap_name = kstrdup(param->string, GFP_KERNEL);
1413 if (!sbi->s_snap_name)
1414 return -ENOMEM;
1415 break;
1416 case Opt_tier2:
1417 kfree(sbi->s_tier2_path);
1418 sbi->s_tier2_path = kstrdup(param->string, GFP_KERNEL);
1419 if (!sbi->s_tier2_path)
1420 return -ENOMEM;
1421 break;
1422 default:
1423 return -EINVAL;
1424 }
1425 return 0;
1426 }
1427
1428 #endif
1429
1430 /**
1431 * apfs_check_nx_features - Check for unsupported features in the container
1432 * @sb: superblock structure
1433 *
1434 * Returns -EINVAL if unsupported incompatible features are found, otherwise
1435 * returns 0.
1436 */
1437 static int apfs_check_nx_features(struct super_block *sb)
1438 {
1439 struct apfs_nx_superblock *msb_raw = NULL;
1440 u64 features;
1441 bool fusion;
1442
1443 msb_raw = APFS_NXI(sb)->nx_raw;
1444 if (!msb_raw) {
1445 apfs_alert(sb, "feature checks are misplaced");
1446 return -EINVAL;
1447 }
1448
1449 features = le64_to_cpu(msb_raw->nx_incompatible_features);
1450 if (features & ~APFS_NX_SUPPORTED_INCOMPAT_MASK) {
1451 apfs_warn(sb, "unknown incompatible container features (0x%llx)", features);
1452 return -EINVAL;
1453 }
1454
1455 fusion = features & APFS_NX_INCOMPAT_FUSION;
1456 if (fusion && !APFS_NXI(sb)->nx_tier2_info) {
1457 apfs_warn(sb, "fusion drive - please use the \"tier2\" mount option");
1458 return -EINVAL;
1459 }
1460 if (!fusion && APFS_NXI(sb)->nx_tier2_info) {
1461 apfs_warn(sb, "not a fusion drive - what's the second disk for?");
1462 return -EINVAL;
1463 }
1464 if (fusion) {
1465 if (!sb_rdonly(sb)) {
1466 apfs_warn(sb, "writes to fusion drives not yet supported");
1467 sb->s_flags |= SB_RDONLY;
1468 }
1469 }
1470
1471 features = le64_to_cpu(msb_raw->nx_readonly_compatible_features);
1472 if (features & ~APFS_NX_SUPPORTED_ROCOMPAT_MASK) {
1473 apfs_warn(sb, "unknown read-only compatible container features (0x%llx)", features);
1474 if (!sb_rdonly(sb)) {
1475 apfs_warn(sb, "container can't be mounted read-write");
1476 return -EINVAL;
1477 }
1478 }
1479 return 0;
1480 }
1481
1482 /**
1483 * apfs_check_vol_features - Check for unsupported features in the volume
1484 * @sb: superblock structure
1485 *
1486 * Returns -EINVAL if unsupported incompatible features are found, otherwise
1487 * returns 0.
1488 */
1489 static int apfs_check_vol_features(struct super_block *sb)
1490 {
1491 struct apfs_superblock *vsb_raw = NULL;
1492 u64 features;
1493
1494 vsb_raw = APFS_SB(sb)->s_vsb_raw;
1495 if (!vsb_raw) {
1496 apfs_alert(sb, "feature checks are misplaced");
1497 return -EINVAL;
1498 }
1499
1500 features = le64_to_cpu(vsb_raw->apfs_incompatible_features);
1501 if (features & ~APFS_SUPPORTED_INCOMPAT_MASK) {
1502 apfs_warn(sb, "unknown incompatible volume features (0x%llx)", features);
1503 return -EINVAL;
1504 }
1505 if (features & APFS_INCOMPAT_DATALESS_SNAPS) {
1506 /*
1507 * I haven't encountered dataless snapshots myself yet (TODO).
1508 * I'm not even sure what they are, so be safe.
1509 */
1510 if (!sb_rdonly(sb)) {
1511 apfs_warn(sb, "writes to volumes with dataless snapshots not yet supported");
1512 return -EINVAL;
1513 }
1514 apfs_warn(sb, "volume has dataless snapshots");
1515 }
1516 if (features & APFS_INCOMPAT_ENC_ROLLED) {
1517 apfs_warn(sb, "encrypted volumes are not supported");
1518 return -EINVAL;
1519 }
1520 if (features & APFS_INCOMPAT_INCOMPLETE_RESTORE) {
1521 apfs_warn(sb, "incomplete restore is not supported");
1522 return -EINVAL;
1523 }
1524 if (features & APFS_INCOMPAT_PFK) {
1525 apfs_warn(sb, "PFK is not supported");
1526 return -EINVAL;
1527 }
1528 if (features & APFS_INCOMPAT_SECONDARY_FSROOT) {
1529 apfs_warn(sb, "secondary fsroot is not supported");
1530 return -EINVAL;
1531 }
1532 if (features & APFS_INCOMPAT_SEALED_VOLUME) {
1533 if (!sb_rdonly(sb)) {
1534 apfs_warn(sb, "writes to sealed volumes are not yet supported");
1535 return -EINVAL;
1536 }
1537 apfs_info(sb, "volume is sealed");
1538 }
1539 /*
1540 * As far as I can see, all this feature seems to do is define a new
1541 * flag (which I call APFS_FILE_EXTENT_PREALLOCATED) for extents that
1542 * are fully after the end of their file. I don't get why this change
1543 * is incompatible instead of read-only compatible, so I fear I might
1544 * be missing something. I will never be certain though, so for now
1545 * allow the mount and hope for the best.
1546 */
1547 if (features & APFS_INCOMPAT_EXTENT_PREALLOC_FLAG)
1548 apfs_warn(sb, "extent prealloc flag is set");
1549
1550 features = le64_to_cpu(vsb_raw->apfs_fs_flags);
1551 /* Some encrypted volumes are readable anyway */
1552 if (!(features & APFS_FS_UNENCRYPTED))
1553 apfs_warn(sb, "volume is encrypted, may not be read correctly");
1554
1555 features = le64_to_cpu(vsb_raw->apfs_readonly_compatible_features);
1556 if (features & ~APFS_SUPPORTED_ROCOMPAT_MASK) {
1557 apfs_warn(sb, "unknown read-only compatible volume features (0x%llx)", features);
1558 if (!sb_rdonly(sb)) {
1559 apfs_warn(sb, "volume can't be mounted read-write");
1560 return -EINVAL;
1561 }
1562 }
1563 return 0;
1564 }
1565
1566 #if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 12, 0)
1567
1568 /**
1569 * apfs_setup_bdi - Set up the bdi for the superblock
1570 * @sb: superblock structure
1571 *
1572 * Returns 0 on success, or a negative error code in case of failure.
1573 */
1574 static int apfs_setup_bdi(struct super_block *sb)
1575 {
1576 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
1577 struct apfs_blkdev_info *bd_info = NULL;
1578 struct backing_dev_info *bdi_dev = NULL, *bdi_sb = NULL;
1579 int err;
1580
1581 bd_info = nxi->nx_blkdev_info;
1582 #if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 15, 0) || RHEL_VERSION_GE(9, 0)
1583 bdi_dev = bd_info->blki_bdev->bd_disk->bdi;
1584 #else
1585 bdi_dev = bd_info->blki_bdev->bd_bdi;
1586 #endif
1587
1588 err = super_setup_bdi(sb);
1589 if (err)
1590 return err;
1591 bdi_sb = sb->s_bdi;
1592
1593 bdi_sb->ra_pages = bdi_dev->ra_pages;
1594 bdi_sb->io_pages = bdi_dev->io_pages;
1595
1596 bdi_sb->capabilities = bdi_dev->capabilities;
1597 #if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 10, 0)
1598 bdi_sb->capabilities &= ~BDI_CAP_WRITEBACK;
1599 #else
1600 bdi_sb->capabilities |= BDI_CAP_NO_WRITEBACK | BDI_CAP_NO_ACCT_DIRTY;
1601 #endif
1602
1603 return 0;
1604 }
1605
1606 #else /* LINUX_VERSION_CODE >= KERNEL_VERSION(4, 12, 0) */
1607
1608 /* This is needed for readahead, so old kernels will be slower */
1609 static int apfs_setup_bdi(struct super_block *sb)
1610 {
1611 return 0;
1612 }
1613
1614 #endif
1615
1616 static void apfs_set_trans_buffer_limit(struct super_block *sb)
1617 {
1618 struct apfs_nxsb_info *nxi = APFS_NXI(sb);
1619 unsigned long memsize_in_blocks;
1620 struct sysinfo info = {0};
1621
1622 si_meminfo(&info);
1623 memsize_in_blocks = info.totalram << (PAGE_SHIFT - sb->s_blocksize_bits);
1624
1625 /*
1626 * Buffer heads are not reclaimed while they are part of the current
1627 * transaction, so systems with little memory will crash if we don't
1628 * commit often enough. This hack should make that happen in general,
1629 * but I still need to get the reclaim to work eventually (TODO).
1630 */
1631 if (memsize_in_blocks >= 16 * APFS_TRANS_BUFFERS_MAX)
1632 nxi->nx_trans_buffers_max = APFS_TRANS_BUFFERS_MAX;
1633 else
1634 nxi->nx_trans_buffers_max = memsize_in_blocks / 16;
1635 }
1636
1637 static int apfs_fill_super(struct super_block *sb, void *data, int silent)
1638 {
1639 struct apfs_sb_info *sbi = APFS_SB(sb);
1640 struct inode *root = NULL, *priv = NULL;
1641 int err;
1642
1643 /*
1644 * This function doesn't write anything to disk, that happens later
1645 * when an actual transaction begins. So, it's not generally a problem
1646 * if other mounts for the same container fill their own supers at the
1647 * same time (the few critical sections will be protected by
1648 * nxs_mutex), nor is it a problem if other mounted volumes want to
1649 * make reads while the mount is taking place. But we definitely don't
1650 * want any writes, or else we could find ourselves reading stale
1651 * blocks after CoW, among other issues.
1652 */
1653 down_read(&APFS_NXI(sb)->nx_big_sem);
1654
1655 err = apfs_setup_bdi(sb);
1656 if (err)
1657 goto failed_volume;
1658 parse_options_set_flags(sb, sbi, sbi->s_mount_opt);
1659
1660 err = apfs_map_volume_super(sb, false /* write */);
1661 if (err)
1662 goto failed_volume;
1663
1664 err = apfs_check_vol_features(sb);
1665 if (err)
1666 goto failed_omap;
1667
1668 /*
1669 * The omap needs to be set before the call to apfs_read_catalog().
1670 * It's also shared with all the snapshots, so it needs to be read
1671 * before we switch to the old superblock.
1672 */
1673 err = apfs_first_read_omap(sb);
1674 if (err)
1675 goto failed_omap;
1676
1677 if (sbi->s_snap_name) {
1678 err = apfs_switch_to_snapshot(sb);
1679 if (err)
1680 goto failed_cat;
1681 }
1682
1683 err = apfs_read_catalog(sb, false /* write */);
1684 if (err)
1685 goto failed_cat;
1686
1687 sb->s_op = &apfs_sops;
1688 #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 17, 0)
1689 set_default_d_op(sb, &apfs_dentry_operations);
1690 #else
1691 sb->s_d_op = &apfs_dentry_operations;
1692 #endif
1693 sb->s_xattr = apfs_xattr_handlers;
1694 sb->s_maxbytes = MAX_LFS_FILESIZE;
1695 sb->s_time_gran = 1; /* Nanosecond granularity */
1696
1697 /*
1698 * At this point everything is already set up for the inode reads,
1699 * which take care of their own locking as always.
1700 */
1701 up_read(&APFS_NXI(sb)->nx_big_sem);
1702
1703 sbi->s_private_dir = apfs_iget(sb, APFS_PRIV_DIR_INO_NUM);
1704 if (IS_ERR(sbi->s_private_dir)) {
1705 apfs_err(sb, "unable to get private-dir inode");
1706 err = PTR_ERR(sbi->s_private_dir);
1707 goto failed_private_dir;
1708 }
1709
1710 root = apfs_iget(sb, APFS_ROOT_DIR_INO_NUM);
1711 if (IS_ERR(root)) {
1712 apfs_err(sb, "unable to get root inode");
1713 err = PTR_ERR(root);
1714 goto failed_mount;
1715 }
1716
1717 sb->s_root = d_make_root(root);
1718 if (!sb->s_root) {
1719 apfs_err(sb, "unable to get root dentry");
1720 err = -ENOMEM;
1721 goto failed_mount;
1722 }
1723
1724 INIT_WORK(&sbi->s_orphan_cleanup_work, apfs_orphan_cleanup_work);
1725 if (!(sb->s_flags & SB_RDONLY)) {
1726 priv = sbi->s_private_dir;
1727 if (APFS_I(priv)->i_nchildren)
1728 schedule_work(&sbi->s_orphan_cleanup_work);
1729 }
1730 return 0;
1731
1732 failed_mount:
1733 iput(sbi->s_private_dir);
1734 failed_private_dir:
1735 sbi->s_private_dir = NULL;
1736 down_read(&APFS_NXI(sb)->nx_big_sem);
1737 apfs_node_free(sbi->s_cat_root);
1738 failed_cat:
1739 apfs_unset_omap(sb);
1740 failed_omap:
1741 apfs_unmap_volume_super(sb);
1742 failed_volume:
1743 up_read(&APFS_NXI(sb)->nx_big_sem);
1744 return err;
1745 }
1746
1747 /**
1748 * apfs_strings_are_equal - Compare two possible NULL strings
1749 * @str1: the first string
1750 * @str2: the second string
1751 */
1752 static bool apfs_strings_are_equal(const char *str1, const char *str2)
1753 {
1754 if (str1 == str2) /* Both are NULL */
1755 return true;
1756 if (!str1 || !str2) /* One is NULL */
1757 return false;
1758 return strcmp(str1, str2) == 0;
1759 }
1760
1761 /**
1762 * apfs_test_super - Check if two volume superblocks are for the same volume
1763 * @sb: superblock structure for a currently mounted volume
1764 * @data: superblock info for the volume being mounted
1765 */
1766 static int apfs_test_super(struct super_block *sb, void *data)
1767 {
1768 struct apfs_sb_info *sbi_1 = data;
1769 struct apfs_sb_info *sbi_2 = APFS_SB(sb);
1770
1771 if (sbi_1->s_nxi != sbi_2->s_nxi)
1772 return false;
1773 if (sbi_1->s_vol_nr != sbi_2->s_vol_nr)
1774 return false;
1775 return apfs_strings_are_equal(sbi_1->s_snap_name, sbi_2->s_snap_name);
1776 }
1777
1778 /**
1779 * apfs_set_super - Assign the device and an info struct to a superblock
1780 * @sb: superblock structure to set
1781 * @data: superblock info for the volume being mounted
1782 */
1783 static int apfs_set_super(struct super_block *sb, void *data)
1784 {
1785 struct apfs_sb_info *sbi = data;
1786 struct apfs_nxsb_info *nxi = sbi->s_nxi;
1787 int err;
1788
1789 /*
1790 * This fake device number will be unique to this volume-snapshot
1791 * combination. It gets reported by stat(), so that userland tools can
1792 * use it to tell different mountpoints apart.
1793 */
1794 err = get_anon_bdev(&sbi->s_anon_dev);
1795 if (err)
1796 return err;
1797
1798 /*
1799 * This is the actual device number, shared by all volumes and
1800 * snapshots. It gets reported by the mountinfo file, and it seems that
1801 * udisks uses it to decide if a device is mounted, so it must be set.
1802 *
1803 * TODO: does this work for fusion drives?
1804 */
1805 sb->s_dev = nxi->nx_blkdev_info->blki_bdev->bd_dev;
1806
1807 sb->s_fs_info = sbi;
1808 return 0;
1809 }
1810
1811 /*
1812 * Wrapper for lookup_bdev() that supports older kernels.
1813 */
1814 static int apfs_lookup_bdev(const char *pathname, dev_t *dev)
1815 {
1816 #if LINUX_VERSION_CODE < KERNEL_VERSION(5, 11, 0)
1817 struct block_device *bdev;
1818
1819 bdev = lookup_bdev(pathname);
1820 if (IS_ERR(bdev))
1821 return PTR_ERR(bdev);
1822
1823 *dev = bdev->bd_dev;
1824 bdput(bdev);
1825 return 0;
1826 #else
1827 return lookup_bdev(pathname, dev);
1828 #endif
1829 }
1830
1831 /**
1832 * apfs_blkdev_setup - Open a block device and set its info struct
1833 * @info_p: info struct to set
1834 * @dev_name: path name for the block device to open
1835 * @mode: FMODE_* mask
1836 *
1837 * Returns 0 on success, or a negative error code in case of failure.
1838 */
1839 #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 5, 0)
1840 static int apfs_blkdev_setup(struct apfs_blkdev_info **info_p, const char *dev_name, blk_mode_t mode)
1841 #else
1842 static int apfs_blkdev_setup(struct apfs_blkdev_info **info_p, const char *dev_name, fmode_t mode)
1843 #endif
1844 {
1845 struct apfs_blkdev_info *info = NULL;
1846 #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 9, 0) || RHEL_VERSION_GE(9, 5)
1847 struct file *file = NULL;
1848 #elif LINUX_VERSION_CODE >= KERNEL_VERSION(6, 8, 0)
1849 struct bdev_handle *handle = NULL;
1850 #endif
1851 struct block_device *bdev = NULL;
1852 int ret;
1853
1854 info = kzalloc(sizeof(*info), GFP_KERNEL);
1855 if (!info)
1856 return -ENOMEM;
1857 info->blki_path = kstrdup(dev_name, GFP_KERNEL);
1858 if (!info->blki_path) {
1859 ret = -ENOMEM;
1860 goto fail;
1861 }
1862
1863 #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 9, 0) || RHEL_VERSION_GE(9, 5)
1864 file = bdev_file_open_by_path(dev_name, mode, &apfs_fs_type, NULL);
1865 if (IS_ERR(file)) {
1866 ret = PTR_ERR(file);
1867 goto fail;
1868 }
1869 info->blki_bdev_file = file;
1870 bdev = file_bdev(file);
1871 #elif LINUX_VERSION_CODE >= KERNEL_VERSION(6, 8, 0)
1872 handle = bdev_open_by_path(dev_name, mode, &apfs_fs_type, NULL);
1873 if (IS_ERR(handle)) {
1874 ret = PTR_ERR(handle);
1875 goto fail;
1876 }
1877 info->blki_bdev_handle = handle;
1878 bdev = handle->bdev;
1879 #elif LINUX_VERSION_CODE >= KERNEL_VERSION(6, 5, 0) || RHEL_VERSION_GE(9, 4)
1880 bdev = blkdev_get_by_path(dev_name, mode, &apfs_fs_type, NULL);
1881 #else
1882 bdev = blkdev_get_by_path(dev_name, mode, &apfs_fs_type);
1883 #endif
1884
1885 if (IS_ERR(bdev)) {
1886 ret = PTR_ERR(bdev);
1887 goto fail;
1888 }
1889 info->blki_bdev = bdev;
1890 #if LINUX_VERSION_CODE < KERNEL_VERSION(6, 5, 0) && !RHEL_VERSION_GE(9, 4)
1891 info->blki_mode = mode;
1892 #endif
1893 *info_p = info;
1894 return 0;
1895
1896 fail:
1897 kfree(info->blki_path);
1898 info->blki_path = NULL;
1899 kfree(info);
1900 info = NULL;
1901 return ret;
1902 }
1903
1904 /**
1905 * apfs_attach_nxi - Attach container sb info to a volume's sb info
1906 * @sbi: new superblock info structure for the volume to be mounted
1907 * @dev_name: path name for the container's block device
1908 * @mode: FMODE_* mask
1909 *
1910 * Returns 0 on success, or a negative error code in case of failure.
1911 */
1912 #if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 5, 0)
1913 static int apfs_attach_nxi(struct apfs_sb_info *sbi, const char *dev_name, blk_mode_t mode)
1914 #else
1915 static int apfs_attach_nxi(struct apfs_sb_info *sbi, const char *dev_name, fmode_t mode)
1916 #endif
1917 {
1918 struct apfs_nxsb_info *nxi = NULL;
1919 dev_t dev = 0;
1920 int ret;
1921
1922 mutex_lock(&nxs_mutex);
1923
1924 ret = apfs_lookup_bdev(dev_name, &dev);
1925 if (ret)
1926 goto out;
1927
1928 nxi = apfs_nx_find_by_dev(dev);
1929 if (!nxi) {
1930 nxi = kzalloc(sizeof(*nxi), GFP_KERNEL);
1931 if (!nxi) {
1932 ret = -ENOMEM;
1933 goto out;
1934 }
1935
1936 ret = apfs_blkdev_setup(&nxi->nx_blkdev_info, dev_name, mode);
1937 if (ret)
1938 goto out;
1939
1940 if (sbi->s_tier2_path) {
1941 ret = apfs_blkdev_setup(&nxi->nx_tier2_info, sbi->s_tier2_path, mode);
1942 if (ret) {
1943 apfs_blkdev_cleanup(nxi->nx_blkdev_info);
1944 nxi->nx_blkdev_info = NULL;
1945 goto out;
1946 }
1947 /* We won't need this anymore, so why waste memory? */
1948 kfree(sbi->s_tier2_path);
1949 sbi->s_tier2_path = NULL;
1950 }
1951
1952 init_rwsem(&nxi->nx_big_sem);
1953 list_add(&nxi->nx_list, &nxs);
1954 INIT_LIST_HEAD(&nxi->vol_list);
1955 apfs_transaction_init(&nxi->nx_transaction);
1956 }
1957
1958 list_add(&sbi->list, &nxi->vol_list);
1959 sbi->s_nxi = nxi;
1960 ++nxi->nx_refcnt;
1961 ret = 0;
1962 out:
1963 if (ret) {
1964 kfree(nxi);
1965 nxi = NULL;
1966 }
1967 mutex_unlock(&nxs_mutex);
1968 return ret;
1969 }
1970
1971 /*
1972 * This function is a copy of mount_bdev() that allows multiple mounts.
1973 */
1974 #if LINUX_VERSION_CODE >= KERNEL_VERSION(7, 0, 0)
1975 static int apfs_test_super_fc(struct super_block *sb, struct fs_context *fc);
1976 static int apfs_set_super_fc(struct super_block *sb, struct fs_context *fc);
1977 static int apfs_get_tree(struct fs_context *fc)
1978 #else
1979 static struct dentry *apfs_mount(struct file_system_type *fs_type, int flags,
1980 const char *dev_name, void *data)
1981 #endif
1982 {
1983 struct super_block *sb;
1984 struct apfs_sb_info *sbi;
1985 struct apfs_blkdev_info *bd_info = NULL, *tier2_info = NULL;
1986 int error = 0;
1987 #if LINUX_VERSION_CODE >= KERNEL_VERSION(7, 0, 0)
1988 blk_mode_t mode = sb_open_mode(fc->sb_flags);
1989 void *data = fc->fs_private;
1990 const char *dev_name = fc->source;
1991
1992 sbi = fc->s_fs_info;
1993 #elif LINUX_VERSION_CODE >= KERNEL_VERSION(6, 5, 0) || RHEL_VERSION_GE(9, 4)
1994 blk_mode_t mode = sb_open_mode(flags);
1995 #else
1996 fmode_t mode = FMODE_READ | FMODE_EXCL;
1997 #endif
1998
1999 #if LINUX_VERSION_CODE < KERNEL_VERSION(7, 0, 0)
2000 sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
2001 if (!sbi)
2002 return ERR_PTR(-ENOMEM);
2003 apfs_set_default_opts(sbi);
2004 /* Set up the fields that sget() will need to id the superblock */
2005 error = parse_options(sbi, data);
2006 if (error)
2007 goto out_free_sbi;
2008 #endif
2009
2010 /* Make sure that snapshots are mounted read-only */
2011 if (sbi->s_snap_name)
2012 #if LINUX_VERSION_CODE >= KERNEL_VERSION(7, 0, 0)
2013 fc->sb_flags |= SB_RDONLY;
2014 #else
2015 flags |= SB_RDONLY;
2016 #endif
2017
2018 #if LINUX_VERSION_CODE < KERNEL_VERSION(6, 5, 0) && !RHEL_VERSION_GE(9, 4)
2019 if (!(flags & SB_RDONLY))
2020 mode |= FMODE_WRITE;
2021 #endif
2022
2023 error = apfs_attach_nxi(sbi, dev_name, mode);
2024 if (error)
2025 goto out_free_sbi;
2026
2027 /* TODO: lockfs stuff? Btrfs doesn't seem to care */
2028 #if LINUX_VERSION_CODE >= KERNEL_VERSION(7, 0, 0)
2029 fc->sb_flags |= SB_NOSEC;
2030 sb = sget_fc(fc, apfs_test_super_fc, apfs_set_super_fc);
2031 #else
2032 sb = sget(fs_type, apfs_test_super, apfs_set_super, flags | SB_NOSEC, sbi);
2033 #endif
2034 if (IS_ERR(sb)) {
2035 error = PTR_ERR(sb);
2036 goto out_unmap_super;
2037 }
2038
2039 bd_info = APFS_NXI(sb)->nx_blkdev_info;
2040 tier2_info = APFS_NXI(sb)->nx_tier2_info;
2041
2042 /*
2043 * I'm doing something hacky with s_dev inside ->kill_sb(), so I want
2044 * to find out as soon as possible if I messed it up.
2045 */
2046 WARN_ON(sb->s_dev != bd_info->blki_bdev->bd_dev);
2047
2048 if (sb->s_root) {
2049 #if LINUX_VERSION_CODE >= KERNEL_VERSION(7, 0, 0)
2050 if ((fc->sb_flags ^ sb->s_flags) & SB_RDONLY) {
2051 #else
2052 if ((flags ^ sb->s_flags) & SB_RDONLY) {
2053 #endif
2054 error = -EBUSY;
2055 deactivate_locked_super(sb);
2056 goto out_unmap_super;
2057 }
2058 /* Only one superblock per volume */
2059 apfs_free_main_super(sbi);
2060 kfree(sbi->s_snap_name);
2061 sbi->s_snap_name = NULL;
2062 kfree(sbi->s_tier2_path);
2063 sbi->s_tier2_path = NULL;
2064 kfree(sbi);
2065 #if LINUX_VERSION_CODE >= KERNEL_VERSION(7, 0, 0)
2066 fc->s_fs_info = NULL;
2067 #endif
2068 sbi = NULL;
2069 } else {
2070 #if LINUX_VERSION_CODE >= KERNEL_VERSION(7, 0, 0)
2071 fc->s_fs_info = NULL;
2072 #endif
2073 if (!sbi->s_snap_name && !tier2_info)
2074 snprintf(sb->s_id, sizeof(sb->s_id), "%pg:%u", bd_info->blki_bdev, sbi->s_vol_nr);
2075 else if (!tier2_info)
2076 snprintf(sb->s_id, sizeof(sb->s_id), "%pg:%u:%s", bd_info->blki_bdev, sbi->s_vol_nr, sbi->s_snap_name);
2077 else if (!sbi->s_snap_name)
2078 snprintf(sb->s_id, sizeof(sb->s_id), "%pg+%pg:%u", bd_info->blki_bdev, tier2_info->blki_bdev, sbi->s_vol_nr);
2079 else
2080 snprintf(sb->s_id, sizeof(sb->s_id), "%pg+%pg:%u:%s", bd_info->blki_bdev, tier2_info->blki_bdev, sbi->s_vol_nr, sbi->s_snap_name);
2081 error = apfs_read_main_super(sb);
2082 if (error) {
2083 deactivate_locked_super(sb);
2084 goto out_return_error;
2085 }
2086 #if LINUX_VERSION_CODE < KERNEL_VERSION(6, 5, 0) && !RHEL_VERSION_GE(9, 4)
2087 sb->s_mode = mode;
2088 #endif
2089
2090 #if LINUX_VERSION_CODE >= KERNEL_VERSION(7, 0, 0)
2091 error = apfs_fill_super(sb, data, fc->sb_flags & SB_SILENT ? 1 : 0);
2092 #else
2093 error = apfs_fill_super(sb, data, flags & SB_SILENT ? 1 : 0);
2094 #endif
2095 if (error) {
2096 deactivate_locked_super(sb);
2097 goto out_return_error;
2098 }
2099 sb->s_flags |= SB_ACTIVE;
2100 }
2101
2102 #if LINUX_VERSION_CODE >= KERNEL_VERSION(7, 0, 0)
2103 fc->root = dget(sb->s_root);
2104 return 0;
2105 #else
2106 return dget(sb->s_root);
2107 #endif
2108
2109 out_unmap_super:
2110 #if LINUX_VERSION_CODE < KERNEL_VERSION(7, 0, 0)
2111 apfs_free_main_super(sbi);
2112 #endif
2113 out_free_sbi:
2114 #if LINUX_VERSION_CODE < KERNEL_VERSION(7, 0, 0)
2115 kfree(sbi->s_snap_name);
2116 kfree(sbi->s_tier2_path);
2117 kfree(sbi);
2118 #endif
2119 out_return_error:
2120 #if LINUX_VERSION_CODE >= KERNEL_VERSION(7, 0, 0)
2121 return error;
2122 #else
2123 return ERR_PTR(error);
2124 #endif
2125 }
2126
2127 /**
2128 * apfs_free_sb_info - Free the sb info and release all remaining fields
2129 * @sb: superblock structure
2130 *
2131 * This function does not include the cleanup for apfs_fill_super(), which
2132 * already took place inside ->put_super() (or maybe inside apfs_fill_super()
2133 * itself if the mount failed).
2134 */
2135 static void apfs_free_sb_info(struct super_block *sb)
2136 {
2137 struct apfs_sb_info *sbi = NULL;
2138
2139 sbi = APFS_SB(sb);
2140 apfs_free_main_super(sbi);
2141 sb->s_fs_info = NULL;
2142
2143 kfree(sbi->s_snap_name);
2144 sbi->s_snap_name = NULL;
2145 kfree(sbi->s_tier2_path);
2146 sbi->s_tier2_path = NULL;
2147 if (sbi->s_dflt_pfk)
2148 kfree(sbi->s_dflt_pfk);
2149 kfree(sbi);
2150 sbi = NULL;
2151 }
2152
2153 static void apfs_kill_sb(struct super_block *sb)
2154 {
2155 struct apfs_sb_info *sbi = APFS_SB(sb);
2156
2157 /*
2158 * We need to delist the superblock before freeing its info to avoid a
2159 * race with apfs_test_super(), but we can't call kill_super_notify()
2160 * from the driver. The available wrapper is kill_anon_super(), but our
2161 * s_dev is set to the actual device (that gets freed later along with
2162 * the container), not to the anon device that we keep on the sbi. So,
2163 * we change that before the call; this is safe because other mounters
2164 * won't revive this super, even if apfs_test_super() succeeds.
2165 */
2166 sb->s_dev = sbi->s_anon_dev;
2167 kill_anon_super(sb);
2168
2169 apfs_free_sb_info(sb);
2170 }
2171
2172 #if LINUX_VERSION_CODE >= KERNEL_VERSION(7, 0, 0)
2173 static int apfs_test_super_fc(struct super_block *sb, struct fs_context *fc)
2174 {
2175 return apfs_test_super(sb, fc->s_fs_info);
2176 }
2177
2178 static int apfs_set_super_fc(struct super_block *sb, struct fs_context *fc)
2179 {
2180 return apfs_set_super(sb, fc->s_fs_info);
2181 }
2182
2183 static int apfs_reconfigure(struct fs_context *fc)
2184 {
2185 struct super_block *sb = fc->root->d_sb;
2186 int flags = fc->sb_flags;
2187
2188 return apfs_remount(sb, &flags, fc->fs_private);
2189 }
2190
2191 static void apfs_free_fc(struct fs_context *fc)
2192 {
2193 struct apfs_sb_info *sbi = fc->s_fs_info;
2194
2195 if (sbi) {
2196 apfs_free_main_super(sbi);
2197 kfree(sbi->s_snap_name);
2198 kfree(sbi->s_tier2_path);
2199 kfree(sbi);
2200 }
2201 }
2202
2203 static const struct fs_context_operations apfs_context_ops = {
2204 .get_tree = apfs_get_tree,
2205 .reconfigure = apfs_reconfigure,
2206 .free = apfs_free_fc,
2207 .parse_param = apfs_parse_param,
2208 };
2209
2210 static int apfs_init_fs_context(struct fs_context *fc)
2211 {
2212 struct apfs_sb_info *sbi;
2213
2214 /* Setup happens here now instead of the top of apfs_mount */
2215 sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
2216 if (!sbi)
2217 return -ENOMEM;
2218 apfs_set_default_opts(sbi);
2219
2220 fc->s_fs_info = sbi;
2221 fc->ops = &apfs_context_ops;
2222 return 0;
2223 }
2224 #endif /* LINUX_VERSION_CODE >= 7.0.0 */
2225
2226 static struct file_system_type apfs_fs_type = {
2227 .owner = THIS_MODULE,
2228 .name = "apfs",
2229 #if LINUX_VERSION_CODE < KERNEL_VERSION(7, 0, 0)
2230 .mount = apfs_mount,
2231 #else
2232 .init_fs_context = apfs_init_fs_context,
2233 #endif
2234 .kill_sb = apfs_kill_sb,
2235 .fs_flags = FS_REQUIRES_DEV,
2236 };
2237 MODULE_ALIAS_FS("apfs");
2238
2239 static int __init init_apfs_fs(void)
2240 {
2241 int err = 0;
2242
2243 err = init_inodecache();
2244 if (err)
2245 return err;
2246 err = register_filesystem(&apfs_fs_type);
2247 if (err)
2248 destroy_inodecache();
2249 return err;
2250 }
2251
2252 static void __exit exit_apfs_fs(void)
2253 {
2254 unregister_filesystem(&apfs_fs_type);
2255 destroy_inodecache();
2256 }
2257
2258 MODULE_AUTHOR("Ernesto A. Fernández");
2259 MODULE_DESCRIPTION("Apple File System");
2260 MODULE_VERSION(GIT_COMMIT);
2261 MODULE_LICENSE("GPL");
2262 module_init(init_apfs_fs)
2263 module_exit(exit_apfs_fs)