93 Commits
Author SHA1 Message Date
Ernesto A. Fernández 41af006115 0.3.7
This is a small release that fixes the dkms build, recently broken by
the implementation of version reporting. From now on I will run a dkms
build before each new tag.

The release also lifts the ban on filesystems with half-written backup
superblocks, a problem that some users appear to have encountered
already.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2024-01-18 20:07:43 -03:00
Ernesto A. Fernández cba2045422 Report dkms version when git is not available
Some users might build the driver from the tarball that github produces
on release, so the reported git commit would be an empty string. Instead
extract the version from the dkms file and use that, but add a question
mark so that I know that it might not be accurate.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2024-01-18 19:35:20 -03:00
Ernesto A. Fernández 5e133a2ca5 Fix version header generation for dkms
The dkms build fails for the latest release:

  https://github.com/linux-apfs/linux-apfs-rw/pull/60

The problem is that dkms does not call my Makefile at all, so the
version header is never generated. Dkms does have a PRE_BUILD hook
though, so use that to call a script that takes care of this.

From now on, I must always remember to run a dkms build before a new
release.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2024-01-17 22:36:05 -03:00
Ernesto A. Fernández 9ae07db606 Don't refuse to mount a bad backup superblock
The backup superblock is only needed to locate the actual superblock, so
it doesn't matter if it's corrupted beyond the first sector, which the
disk is supposed to write atomically. If a crash happened at the right
moment during unmount, any implementation might end up with a
half-written superblock where the checksum doesn't add up, but that's
perfectly fine.

If this is encountered during mount, just report it and proceed. This is
not a theoretical concern, someone appears to have run into the problem
already:

  https://techsparx.com/linux/ubuntu/mount-apfs.html

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2024-01-08 21:22:08 -03:00
Ernesto A. Fernández 10557edf23 0.3.6
This release heavily reworks the node defragmentation and split logic to
fix a handful of rarely triggered data corruption bugs. The new version
is easier to understand and hopefully more robust.

Support is added for containers with a size of up to ~6.7 TiB, improving
the previous maximum of ~1.3 TiB. The next release will probably keep
pushing this limit.

Changes are made to the way that subvolume "devices" are reported. Now
we are closer to matching the behaviour of btrfs and userland tools like
Nautilus are far less confused.

The driver version information is now provided by both the on-disk
filesystem metadata and by modinfo. This may be useful for responding to
bugs at some point.

A few small issues with snapshot reporting have been addressed, as well
as an mmap-related warning in recent kernel versions.

Finally, support is added for the 6.7 kernel version (released today),
contributed by Woody Suwalski.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2024-01-07 20:53:51 -03:00
Ernesto A. Fernández bcedfe1752 Read error before setting error pointer to null
I'm in a rush to get the tag out today and I'm making a mess. The
previous patch set an error pointer to null in apfs_node_split(), but I
didn't notice that the actual error would get read later. Reorder this.
I usually would just squash this into the previous patch, but in my rush
I have already pushed it.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2024-01-07 19:10:40 -03:00
Ernesto A. Fernández 8b2287d91f Don't free error pointers in apfs_node_split()
We mistakenly free an error pointer if apfs_create_node() happens to
fail. Set the node to null before the cleanup, but I guess I should try
to avoid error pointers in the future.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2024-01-07 19:03:09 -03:00
Woody Suwalski 5dc836ad96 Support for kernel 6.7
[eafer: fixed some issues with folios and timestamps]
Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2024-01-07 16:27:45 -03:00
Ernesto A. Fernández fe13bc9636 Don't refresh queries pointing to deleted nodes
Running generic/013 for a few minutes still leaves the filesystem in a
corrupted state, with a missing inode record. This is another regression
caused by my big rework of the node split logic. When a single-record
node is needed but the parent update fails with -EAGAIN,
apfs_create_single_rec_node() leaves the query pointing to the aborted
new node. The refresh does not change this, so the inode record ends up
abandoned in this ghost node.

In then end all of this is caused by the weird way I originally designed
the query struct, which forces me to always keep a more or less valid
leaf query instead of just nuking the whole thing and starting over. I'd
like to change this eventually, but for now just adjust the cleanup for
apfs_create_single_rec_node().

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2024-01-06 01:48:44 -03:00
Ernesto A. Fernández af1491622d Avoid filename normalizations issues on refresh
The previous patch introduced a regression in generic/013, seen when the
test is allowed to run for 20 minutes or so. The result is a corrupted
filesystem where one inode appears to have too many dentries, and
another inode has too few to balance.

The problem is that query refreshes just rerun the query once and expect
the correct result, but dentry queries for an existing record actually
need to be called repeatedly to deal with hash collisions. For
normalization-sensitive filesystems (which I use for most of my tests)
"collisions" are constant because there is no hash. So if a split
happens during a dentry deletion, chances are very high that the refresh
will end up pointing to the wrong record.

Don't add awkward code to deal with this to apfs_query_refresh().
Instead transform the multiple query from apfs_dentry_lookup() into a
regular exact query before returning, setting the key to the
unnormalized name. The refresh code will have no trouble working with
that.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2024-01-04 23:22:34 -03:00
Ernesto A. Fernández e7983cb3fe Restart btree modifications after a node split
I'm encountering some rare failures in generic/075. The problem happens
when a node split is triggered by inserting a record into the first
position. The parent needs to get updated of course, but we've lost the
reference to it after the split, so the filesystem becomes corrupted.

The reality is that this stuff has always been too hacky, and new corner
cases keep popping up. Stop trying to guess which queries need to know
and might have forgotten their ancestors: just restart the whole btree
operation after any split, refreshing the query with a simple rerun.
This has to be the safest possible approach, and I don't expect it to
hurt performance, since node splits should never be a bottleneck.

Big changes are needed to get it to work though, because the b-tree must
be in a consistent state whenever the query gets refreshed. There are
two different considerations here. First, no split can take place unless
the parent has enough room to index the new child node; otherwise the
parent split would trigger a query refresh while half the child's
records are orphaned. To sum up, every cascade of node splits must
happen from root to leaf.

The second consideration is that, even if a node has enough room, no
updates related to the actual requested operation (the leaf record
insertion/deletion/replacement) can take place at any level until all
splits are done. A different policy would mean that a query refresh
might become necessary halfway through the operation, and so the leaf
record could be found to be unexpectedly missing, or covered by the
wrong index key.

So at a given level: the split, if needed, always comes first, followed
by the function call for parent updates, and only then the node gets
modified. After a split an EAGAIN error gets thrown, which then bubbles
back up to the leaf (either through the splits themselves, or through
the parent update calls), so only a single split can happen for the
whole b-tree on each refresh iteration - always at the highest possible
level in the split cascade that would have been triggered before this
patch. The btree, of course, remains valid on EAGAIN, and the leaf
records remain the same.

Inside apfs_node_split() itself, no changes to the old node can be done
until the new one is safely inserted in the b-tree. If that triggers a
split at a higher level, then the new node must be properly cleaned up
(making use of the recent changes to apfs_delete_node()) and, as usual,
EAGAIN must get bubbled up.

A similar cleanup needs to be take place in the one other function that
creates non-root nodes: apfs_create_single_rec_node(). The new
single-record node must be repeatedly destroyed until the parent manages
to index it without any splits.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2024-01-04 22:01:40 -03:00
Ernesto A. Fernández 2de7f65d5b Implement a helper to extract root node from query
Implement apfs_query_root() and use it to simplify two functions. It
will get reused further in the following patch, including inside node.c,
so don't make it static.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-12-30 16:29:55 -03:00
Ernesto A. Fernández e872d3971a Allow NULL to be passed to apfs_node_free()
Allow NULL node pointers to be "freed" with apfs_node_free(). This will
simplify some cleanups soon.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-12-29 23:48:30 -03:00
Ernesto A. Fernández eb6dd65019 Don't let node insert/replace fail with ENOSPC
Currently node insertions/deletions are attempted immediately and they
return -ENOSPC when there is no room, letting the caller know that the
node needs to get split. But in future patches I'll need to reorder the
operations so that the node only gets updated after all the ancestors.

The previous patches already ensured that apfs_node_replace() will never
erroneously report lack of space, no matter how fragmented the node may
be. This was already true of apfs_node_insert(). So from now on we can
safely run space checks ahead of time with only the node metadata, use
that to decide if a split is needed, and only update the records after
all that is done.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-12-29 23:22:46 -03:00
Ernesto A. Fernández 0c8beaa186 Also defragment freed space in apfs_node_replace()
In the near future we want to make sure that apfs_node_replace() will
never fail as long as it has enough space. The defragmentation from the
previous patch is not enough for this, because it still leaves the
replaced record in place instead of moving those useless bytes into the
free area.

To solve this as simply as possible, set the table-of-contents entry for
the replaced record to zero length, for either the key or the value (or
both), depending on which we are replacing. The defragmentation code
will take care of the rest. Of course this weird toc entry remains in
place if the function fails, but it will be replaced eventually so it
should not matter.

By the way, this hack cannot be used on trees with fixed key/value
sizes, because those sizes are simply not reported in the toc. Of course
records in such trees can generally be replaced in place, so they won't
need defragmentation. There is one exception though: the ghost records
of the free queue. Luckily we don't currently call replace on free queue
leaves, so we can safely ignore this problem. Leave an assert in place
so that I don't forget.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-12-29 22:04:16 -03:00
Ernesto A. Fernández 2adf86cba9 Defragment the node in apfs_node_replace()
Like we already do in apfs_node_insert(), attempt to defragment the node
before returning -ENOSPC in apfs_node_replace(). This shouldn't make
much of a difference right now (other than packing the records a bit
tighter together), but in future patches it will help us prevent
apfs_node_replace() from ever failing in normal operation.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-12-29 21:56:02 -03:00
Ernesto A. Fernández f883518a96 Move toc entry update into new function
Define a new apfs_node_update_toc_entry() to be used when replacing
records in a node. This makes apfs_node_replace() somewhat cleaner, but
more importantly it will allow that part to be reused in future patches.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-12-29 19:40:24 -03:00
Ernesto A. Fernández 4eb83167a9 Document some node functions that may throw ENOSPC
Improve the documentation of the record allocation functions to make it
clear that they may return -ENOSPC, because that case will often need to
be handled separately in the future.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-12-29 19:35:22 -03:00
Ernesto A. Fernández e053f3b2b5 Call apfs_delete_node() with a node, not a query
Some changes I'm working on will require being able to delete nodes that
have not yet been indexed in a btree. This cannot be done with the
current version of apfs_delete_node(), because it handles the parent
node modifications itself. So from now on, let the caller handle that if
it's necessary. This is also more symmetrical with apfs_create_node(),
as would be expected.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-12-29 18:28:01 -03:00
Ernesto A. Fernández 196ac31122 Don't allow a stale offset for ghost records
When apfs_node_locate_data() gets called for a ghost record (that is, a
record without a value), the function correctly returns the zero length,
but the offset is left unset, and so a stale number may remain in the
query structure. This does not matter of course, because a zero-length
value will never be read, but I've found it very distracting while
debugging a separate issue with query offsets. Just set it to zero.

To be consistent, do the same in apfs_node_insert(), though I haven't
been bothered by this one yet.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-12-28 19:48:25 -03:00
Ernesto A. Fernández f1775ed0ef Turn the search key into a query field
I've been working on making some very needed changes to how node splits
work. The plan is to always rerun queries after a split, to keep the
query chain valid. One problem I've encountered while implementing this
is that the search key is not really preserved by apfs_update_inode().
We have a pointer to it, but it was allocated in the stack of some other
function, so the data is just noise.

I've always thought it was silly to allocate both a query and a key
before a lookup. Instead, turn the search key into a field within the
query structure, and copy it to the children as the query gets run. This
will ensure that the key remains available for future reruns.

One thing to note is that, while this simplifies most callers a little
bit, some of them still allocate a key in the stack and later copy it to
the query. I didn't want to make any big changes and risk introducing
bugs at this point, since I'm busy with other stuff.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-12-20 20:33:03 -03:00
Ernesto A. Fernández a33f06d8da Do use anon devices, but in a different way
Like I mentioned in the previous patch, df is refusing to acknowledge
multiple mounted volumes or snapshots for the same device, and it's
reporting only one. Luckily the source code for df is straightforward,
so I figured out that it calls stat() on the mount point to find the
device number instead of just accepting the one reported by mountinfo.
This way each mounted volume/snapshot can choose to report a different
number, instead of just going with the one set in the superblock.

After confirming that this is indeed what btrfs does, implement it here.
This fixes the df issue, but sadly it doesn't fix all problems with
thunar. It can tell the different mounts apart, but for some reason I
need to close it and reopen it for that to happen (in fact I now realize
that it could already do that in the previous commit). Since btrfs does
have plugins for udisks and such, maybe this is not the driver's fault,
but I'm not sure.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-12-08 22:08:13 -03:00
Ernesto A. Fernández 9c0d396e20 Don't use anon devices
Nautilus and other file managers fail to unmount apfs volumes:

  https://github.com/linux-apfs/linux-apfs-rw/issues/58

This has been broken for years, since commit 4a6c0e2b77 ("Support
simultaneous mount of multiple volumes"), but I never noticed because I
always use the command line, and there are no problems either there or
with libmount.

The error message ("Device `%s' is not mounted") appears to come from
udisks. I don't know much about this stuff, but from tests to my driver
it seems that userland expects /proc/self/mountinfo to report the device
number for the mounted device, not just the name. The tricks we do with
anon devices to support multiple mounts cause a confusion.

Stop using anon devices. Instead set the real device number on the
superblock, and ignore it for all purposes other that mountinfo
reporting, which is done by the common code.

This should solve the reported bug, but causes other weird behaviour.
For instance, if I mount the current transaction and later mount a
snapshot, both df and thunar refuse to acknowledge the existence of the
first mount. I don't know how btrfs deals with this, but they seem to
have plugins for udisks and libblockdev so it's probably not as simple
as a driver change.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-12-07 22:16:55 -03:00
Ernesto A. Fernández 760cf779ef Add snapshot name to apfs_show_options()
I just noticed that the snapshot name option is not getting output in
/proc/mounts. I guess I just forgot to implement this, do it now.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-12-07 21:52:06 -03:00
Ernesto A. Fernández 0d274c7b48 Fix ->statfs() block count for snapshot mounts
I just noticed that df throws a "No data available" error if it's used
while a snapshot is mounted. The problem happens while gathering the
total number of used blocks: to iterate through the existing volume
superblocks, this requires working with the container omap, which we
otherwise only do for snapshots during mount. apfs_omap_lookup_block()
is written with the idea that snapshots will only call it for the volume
omap, and so it uses the snapshot xid to get the wanted (old) version of
the object. But for used space calculations we actually want the latest,
and in fact the container omap doesn't even have the old versions of the
volumes, so the call fails.

Reimplement apfs_omap_lookup_block() as a wrapper around a new
apfs_omap_lookup_block_with_xid() that uses the current snapshot
transaction, and use this to implement apfs_omap_lookup_newest_block()
to be used in this situation.

By the way, there was no output on dmesg when I discovered this bug.
That's no good, so add a new error message in here.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-12-07 21:22:32 -03:00
Ernesto A. Fernández 53a9145401 Support multiblock internal pool bitmaps
A container with a size starting at 1454383304704 bytes (~1.3 TiB) needs
more than one block to hold the bitmap of its internal pool. Add support
for such large filesystems.

To this end, replace the single buffer head holding the bitmap in the
spaceman struct with an array, which requires allocating the spaceman
separately from the container superblock info. Then rework the alloc and
free functions to work with the whole array.

The biggest changes are in apfs_rotate_ip_bitmaps(), which now has to
copy all the bitmap blocks at once to make them available for the
transaction. This is probably not what the official implementation
intended, but it should be technically correct.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-12-01 20:46:36 -03:00
Ernesto A. Fernández 1e8251a458 Report driver version for modinfo
The previous commit started reporting the driver version on disk after a
modification. Report it as well in the driver metadata, so that it can
be obtained with modinfo.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-11-14 20:54:54 -03:00
Ernesto A. Fernández e0b1eeb29d Include release info in apfs_modified_by field
The filesystem superblock has an apfs_modified_by field to report which
implementation is responsible for the latest changes. This could be
useful to track down bugs eventually, but it will need to have more
information. Right now we only report my name and the name of the
module; change it to also report the exact commit id, or the tag if
there is one. There is a strict size limit here, so shorten my name to
"eafer", which is what I use on github, so it will make the driver easy
to track down.

Also move the APFS_MODULE_ID_STRING macro definition to super.c. We'll
now need to recompile that file with every build, but if we left it
inside apfs.h then we would have to recompile everything all the time.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-11-03 22:10:03 -03:00
Ernesto A. Fernández 3c36f372be Get rid of apfs_end_buffer_write_sync()
Some mmap related tests such as generic/030 are throwing the following
callstack on kernels 6.1 and above:

[ 9810.190496] ------------[ cut here ]------------
[ 9810.192000] irq 15 handler ata_bmdma_interrupt+0x0/0x1f0 [libata] enabled interrupts
[ 9810.193639] WARNING: CPU: 0 PID: 0 at kernel/irq/handle.c:161 __handle_irq_event_percpu+0x150/0x190
[ 9810.195220] Modules linked in: apfs(OE) libcrc32c(E) 9p(E) fscache(E) netfs(E) intel_rapl_msr(E) intel_rapl_common(E) intel_pmc_core_pltdrv(E) intel_pmc_core(E) kvm_intel(E) kvm(E) irqbypass(E) ghash_clmulni_intel(E) ppdev(E) aesni_intel(E) bochs(E) libaes(E) drm_vram_helper(E) drm_ttm_helper(E) crypto_simd(E) cryptd(E) ttm(E) rapl(E) snd_pcm(E) snd_timer(E) 9pnet_virtio(E) drm_kms_helper(E) 9pnet(E) snd(E) soundcore(E) pcspkr(E) parport_pc(E) parport(E) button(E) joydev(E) evdev(E) serio_raw(E) sg(E) binfmt_misc(E) fuse(E) drm(E) efi_pstore(E) configfs(E) qemu_fw_cfg(E) ip_tables(E) x_tables(E) autofs4(E) ext4(E) crc32c_generic(E) crc16(E) mbcache(E) jbd2(E) sd_mod(E) t10_pi(E) crc64_rocksoft(E) crc64(E) crc_t10dif(E) crct10dif_generic(E) ata_generic(E) ata_piix(E) libata(E) crct10dif_pclmul(E) crct10dif_common(E) crc32_pclmul(E) virtio_pci(E) virtio_pci_legacy_dev(E) crc32c_intel(E) virtio_pci_modern_dev(E) virtio(E) psmouse(E) virtio_ring(E) e1000(E) scsi_mod(E) scsi_common(E)
[ 9810.195294]  i2c_piix4(E) floppy(E) [last unloaded: apfs(OE)]
[ 9810.215274] CPU: 0 PID: 0 Comm: swapper/0 Tainted: G        W  OE      6.0.0-rc2+ #24
[ 9810.216639] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.15.0-1 04/01/2014
[ 9810.217983] RIP: 0010:__handle_irq_event_percpu+0x150/0x190
[ 9810.218904] Code: 44 00 00 e9 09 ff ff ff 80 3d 8f 16 4e 01 00 75 1b 48 8b 13 44 89 ee 48 c7 c7 e8 31 91 bc c6 05 79 16 4e 01 01 e8 90 26 81 00 <0f> 0b fa 0f 1f 44 00 00 e9 fc fe ff ff 3e 48 0f ba 6b 40 01 0f 82
[ 9810.223642] RSP: 0018:ffffaf4240003f60 EFLAGS: 00010286
[ 9810.224836] RAX: 0000000000000000 RBX: ffff94804172f080 RCX: 0000000000000000
[ 9810.226451] RDX: 0000000000010002 RSI: ffffffffbc94d2a2 RDI: 00000000ffffffff
[ 9810.228082] RBP: 0000000000000001 R08: 0000000000000000 R09: ffffaf4240003e00
[ 9810.229506] R10: 0000000000000003 R11: ffffffffbccc4778 R12: 0000000000000000
[ 9810.231182] R13: 000000000000000f R14: ffff94804019ae00 R15: 0000000000000000
[ 9810.232856] FS:  0000000000000000(0000) GS:ffff948177c00000(0000) knlGS:0000000000000000
[ 9810.234771] CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[ 9810.236112] CR2: 00007f6d608b1210 CR3: 000000006020a004 CR4: 0000000000370ef0
[ 9810.237812] Call Trace:
[ 9810.239294]  <IRQ>
[ 9810.239767]  handle_irq_event+0x34/0x70
[ 9810.240688]  handle_edge_irq+0x9f/0x240
[ 9810.241577]  __common_interrupt+0x63/0x100
[ 9810.242444]  common_interrupt+0xb4/0xd0
[ 9810.243141]  </IRQ>
[ 9810.243575]  <TASK>
[ 9810.244008]  asm_common_interrupt+0x22/0x40
[ 9810.244820] RIP: 0010:native_safe_halt+0xb/0x10
[ 9810.245705] Code: 01 00 3e 80 48 02 20 48 8b 00 a8 08 75 bf e9 7b ff ff ff cc cc cc cc cc cc cc cc cc cc cc cc 66 90 0f 00 2d a9 eb 49 00 fb f4 <c3> cc cc cc cc 66 90 0f 00 2d 99 eb 49 00 f4 c3 cc cc cc cc cc 0f
[ 9810.249342] RSP: 0018:ffffffffbcc03e90 EFLAGS: 00000252
[ 9810.250451] RAX: ffffffffbc16ab90 RBX: ffffffffbcc139c0 RCX: 0000000000000000
[ 9810.252391] RDX: 4000000000000000 RSI: ffffffffbc94d2a2 RDI: 00000000005ec6ec
[ 9810.253784] RBP: 0000000000000000 R08: 00000a4bf1fdb94f R09: 0000000000000000
[ 9810.256613] R10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000000
[ 9810.258508] R13: 0000000000000000 R14: ffffffffbcc13118 R15: 0000000000000000
[ 9810.260053]  ? ldsem_down_write+0x230/0x230
[ 9810.261021]  default_idle+0xa/0x10
[ 9810.261734]  default_idle_call+0x36/0xf0
[ 9810.262574]  do_idle+0x220/0x2b0
[ 9810.263341]  cpu_startup_entry+0x19/0x20
[ 9810.264217]  rest_init+0xcb/0xd0
[ 9810.265119]  arch_call_rest_init+0xa/0x14
[ 9810.266173]  start_kernel+0x6d2/0x6fb
[ 9810.267059]  secondary_startup_64_no_verify+0xce/0xdb
[ 9810.268261]  </TASK>
[ 9810.268837] ---[ end trace 0000000000000000 ]---

I bisected this back to upstream commit f168420c62e7 ("blk-mq: don't
redirect completion for hctx withs only one ctx mapping"), but that
doesn't tell me much.

I can't tell for sure what's going wrong here, but it seems to be
related to my implementation of ->b_end_io(), which exists to force page
faults when we write to an mmapped page again after a commit. I didn't
follow any clear reference when I wrote that code, and I'm guessing
something about it is not allowed. Also, this code runs asynchronously,
which seems to fit with the nature of the problem, since my driver is
not mentioned in the callstack.

Just use the standard end_buffer_write_sync() for ->b_end_io(), and wait
for each buffer before cleaning its page. This is similar to what we do
for reads and it doesn't have any original async stuff, so hopefully it
will work better. At least none of my tests are failing anymore.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-11-03 20:49:35 -03:00
Ernesto A. Fernández 620d6257f8 0.3.5
This release adds support for reading compressed files of arbitrary
on-disk size, which is becoming more and more necessary in recent ipsw
images.

A number of bugs are addressed for systems with little ram, reported by
Gilgamesh via email.

Support is added for the 6.6 kernel version, mainly thanks to Woody
Suwalski. I'm afraid the driver sometimes triggers a warning for recent
kernels, but I didn't manage to fix it in time for the new upstream
release, and it's better to at least get things to build.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-10-30 13:58:24 -03:00
Ernesto A. Fernández 225a17aa77 Set splice read/write methods explicitly
Several of xfstests (generic/249 for example) are failing on kernel 6.6
because of sendfile issues. Starting with upstream commit 36e2c7421f02
("fs: don't allow splice read/write without explicit ops"), the
->splice_read() and ->splice_write() methods need to be set explicitly,
or else we just get EINVAL when sendfile needs them. This change
happened in the 5.10 release, but I never noticed because I usually only
run tests on 5.3.

So, set the methods as required, taking into consideration the kernel
version because there was another related change in commit 2cb1e08985e3
("splice: Use filemap_splice_read() instead of
generic_file_splice_read()").

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-10-27 22:13:05 -03:00
Ernesto A. Fernández 6813d7e614 Ignore return value for generic_update_time()
Attempts to run xfstests for the 6.6 kernel fail brutally. Transactions
are getting aborted inside apfs_update_time(), which has never happened
before. The problem comes from upstream commit 541d4c798a59 ("fs: drop
the timespec64 arg from generic_update_time"): generic_update_time()
can't fail and used to always return a symbolic 0, but now instead
returns some flags - which my code mistakes for an error. We don't care
about the flags, so just ignore the return value for all kernel
versions.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-10-27 19:24:13 -03:00
Ernesto A. Fernández 4dab24ef6b Stop triggering kernel panics for silly reasons
I was reading the list of deprecated interfaces at [0] and it mentions
that the use of BUG() and BUG_ON() is discouraged in the kernel, and
that we should be prepared to fail gracefully even for impossible
situations.

I definitely agree with this: so far I've used BUG_ON() to implement
ASSERT(), but in practice I always turn that into a WARN_ON() while
debugging. Just leave it as WARN_ON() permanently.

I also use BUG() in apfs_query_storage() to mark an impossible query
tree flag. I can't imagine how this would ever be reached, but still
keep going and return an invalid storage type. This way the error can
get reported later, after calling either apfs_create_node() or
apfs_read_node(), which have been modified to fail gracefully and
complain with apfs_alert() in this situation. I also considered putting
an assertion in apfs_query_storage(), but that would require reordering
apfs.h and it seems unnecessarily messy.

Warnings should not be abused either, because of the panic_on_warn
option. Replace our one call to WARN_ON(), inside apfs_btree_replace(),
with another apfs_alert(). This function was already failing gracefully.

[0]: https://docs.kernel.org/process/deprecated.html#zero-length-and-one-element-arrays

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-10-27 15:44:47 -03:00
Ernesto A. Fernández 1d9630b194 Get rid of zero-length arrays
According to checkpatch.pl, the use of zero-length arrays is now
deprecated in the kernel. Replace them all with C99 flexible array
members.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-10-26 21:56:56 -03:00
Ernesto A. Fernández 2d6cdba8f6 Fix trivial style issues
Some code that wasn't originally written by me has a style that differs
slightly from the rest of the module. Since I've been refactoring
compress.c quite a lot lately, I have made the inconsistencies more
visible, so I think it's a good time to switch everything to the typical
kernel style.

For this purpose I'm running checkpatch.pl for the first time in years,
and it has detected a handful of other issues that I introduced myself.
Fix most of the issues now, but I prefer to leave the zero-length array
stuff for a separate patch.

For the record, at the moment I'm choosing to ignore style inconsistency
in the compression libraries, even in libzbitmap which I wrote myself. I
prefer to keep them as close to upstream as possible.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-10-26 21:44:30 -03:00
Woody Suwalski 1bca725a63 Fix for the kernel 6.6 build errors
[eafer: removed unnecessary setting of some timestamps]
Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-10-25 22:43:27 -03:00
Ernesto A. Fernández 12f526f2de Perform locking for compressed reads
For some reason I never remembered to take the big lock during reads of
compressed files. Do it. As always, my locking is coarse and hacky, and
I will have get back to it at some point.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-10-24 21:30:08 -03:00
Ernesto A. Fernández 2ec72ff747 Simplify gotos in apfs_compress_file_open()
After the recent refactoring of the compression code, the fail_enomem
label feels a little unnecessary. Get rid of it.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-10-24 20:42:15 -03:00
Ernesto A. Fernández 133ed4fbf3 Don't swallow errors in compressed ->readpage()
While debugging the previous patch, I noticed that my implementation of
compressed ->readpage() from f9ca9061bb ("Implement mmap for
compressed files") has a serious issue: if something goes wrong during
the read, the error code is swallowed and stale garbage becomes visible
to the user.

I messed this up because I was following ext4_read_inline_page(), which
first calls ext4_read_inline_data() and then, without checking the
return code, calls SetPageUptodate(). But ext4_read_inline_data() can't
actually fail, so this is not a problem. In my version the function
called is apfs_compress_file_read_page(), which does fail sometimes,
leaving a stale page marked as updated. Fix it, and also return the
error code correctly.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-10-19 23:33:21 -03:00
Ernesto A. Fernández 71b11b377b Unify read of attr and rsrc compressed files
Currently, compressed files that are stored directly in the decmpfs
xattr are handled separately: they get entirely uncompressed on open,
and on reads the contents simply get copied. To get rid of this code
duplication, use a new apfs_compressed_data struct to read from both
inline and dstream xattrs, and let the regular resource-compressed code
handle reads for both types.

These changes weren't made exclusively for code quality. A compressed
file may be too big to fit inside decmpfs, but still small enough to fit
inside a xattr. If that happens, the resulting resource fork will be an
inline xattr, and the dstream read code implemented with e4bb06ecef
("Avoid reading whole compressed files into memory") will break down. So
the apfs_compressed_data struct is strictly necessary for the resource
case; using the same struct for both cases simplifies testing, because
inline resource compressed files are rare (I've seen them, but right now
I don't even have an image with one of them).

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-10-19 23:33:21 -03:00
Ernesto A. Fernández e6370242fa Try to preread the dstream for compressed files
After commit e4bb06ecef ("Avoid reading whole compressed files into
memory"), performance for compressed reads worsened by about 50%. The
problem is that, when we stopped reading the xattr all at once, we lost
the advantage of letting the kernel batch and schedule the buffer reads.

The ideal way to handle this would be to make a fake inode for the xattr
dstream, and let the kernel do readahead in the usual manner. I don't
feel very confident that I can get that right though, so I'm leaving it
for some other time.

For now, just request all the blocks as soon as a read begins (I would
have preferred to do it on open, but that's slower for some reason), and
ignore the results. Compressed data is supposed to be small so, as long
as there is enough memory, this has all the performance benefits of the
original implementation (in fact it's somewhat faster), but it still
avoids the problems with large virtual memory allocation.

Of course, unlike normal readahead, this will be useless if memory is
scarce, or if we don't read the whole file sequentially.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-10-13 22:01:15 -03:00
Ernesto A. Fernández 040358bd4a Check for failure in buffer head array allocation
I've neglected to check for failure after allocating an array in
apfs_nonsparse_dstream_read(). This is not a new bug: it got carried
over from the original xattr code, which has been around since
84c3ecebac ("Don't read dstream xattr blocks one by one"). Fix it now.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-10-11 20:28:54 -03:00
Ernesto A. Fernández e537eccc88 Fix apfs_compress_file_read_block() return code
In commit e4bb06ecef ("Avoid reading whole compressed files into
memory"), I moved part of the code of apfs_compress_file_read_block()
into a separate apfs_compress_file_read_from_block() that must call it.
I made a mistake, though: the original version of the function would
reset the return value before returning, but this version no longer does
it. This doesn't play well with the decompression functions for some of
the algorithms, which return decompressed lengths. So we get a "failed
to read block into buffer" message and the decompression is abandoned.
Fix this.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-10-10 19:04:34 -03:00
Ernesto A. Fernández c6de394653 Make all compressed reads use the page cache
When implementing compressed mmap I was forced to duplicate the code for
regular compressed reads, so that one version could copy to a user
buffer and the other to the kernel. To simplify this, get rid of the
regular version and instead use the generic read iterator, which will
make use of the same mmap code.

This should also allow regular compressed reads to take advantage of the
page cache.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-10-06 21:21:14 -03:00
Ernesto A. Fernández e99d7b4d51 Get rid of apfs_compress_file_mmap()
When compressed mmap was implemented, apfs_compress_file_mmap() was
added with the purpose of ignoring calls to ->page_mkwrite(). With the
last patch, I no longer allow compressed files to be opened for writing
at all, so I can just use regular ->mmap() for all files.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-10-06 20:18:31 -03:00
Ernesto A. Fernández a55f0effc7 Ban the opening of compressed files for writing
In commit 31df49c6d8 ("Ban writes to compressed files explicitly"), I
blocked writes to compressed files when they actually happen, not when
the file gets opened. My fear was that banning rw open entirely could
break other people's code, since I'm not sure who is using this driver
and how.

Now I've implemented compressed mmap, and blocking writes when they
happen is becoming a little too hacky. Do this properly, and wait to see
if anyone complains.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-10-06 19:08:10 -03:00
Ernesto A. Fernández f9ca9061bb Implement mmap for compressed files
Attempts to mmap compressed files currently fail with ENODEV. I guess I
had forgotten about compressed mmap. Implement it now, in read-only mode
like all compressed operations so far.

Since the existing read code works with userland buffers, it can't be
reused to copy stuff into the kernel. For now I've been forced to
duplicate a lot of code, but I think it might be a good idea to use the
generic read implementations instead. I'll look into that soon.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-10-05 22:36:52 -03:00
Ernesto A. Fernández 131953ffd8 Always lock pages before making them clean
Gilgamesh reports via email that his kernel often crashes on my call to
page_mkclean() due to "BUG_ON(!PageLocked(page))".

I should have expected problems such as this, since the locking in
apfs_end_buffer_write_sync() is not sane at all. Apparently back when I
wrote this, I only realized that I needed to lock the page because of
the above-mentioned panic. So I tried to take the lock, but this caused
a deadlock in generic/013 of xfstests. Instead of figuring out what the
problem was, I just replaced lock_page() with trylock_page(), to silence
the panic and still avoid deadlock. Of course this leaves us open to a
race, which in this case became visible because whatever was holding the
page released the lock before the check happened in page_mkclean().

In my defense, most of the locking in the driver is insane at this
point, so I don't usually put much thought into it unless I see actual
problems, as in this case.

So, replace trylock_page() with lock_page(), and figure out what was
causing the generic/013 deadlock in the first place. This was actually
very simple: a check of the contents of the problem page showed that
it's always a chunk-info block, and those are the only block types that
both get dirtied and added to the transaction. This is unnecessary, and
it causes some conflict on commit with whatever the kernel does to the
dirty blocks. Stop dirtying the cib blocks.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-09-29 20:54:45 -03:00
Gilgamesh 12dde7a08f Only commit in apfs_sync_fs() if wait == 1
I've been ignoring the 'wait' argument to apfs_sync_fs() so far, but
this means that transactions get committed twice in a row whenever a
sync is requested. Instead, just do nothing when wait == 0. If the
caller actually needs a sync, they will have to try again with wait == 1
later anyway.

[eafer: added comment and commit message]
Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-09-27 19:41:26 -03:00
Ernesto A. Fernández 19430cbdb2 Improve error messages in apfs_xattr_get_dstream()
I wrote apfs_xattr_get_dstream() long before error messages were changed
in d4797823ea ("Improve error reporting"), but the code wasn't
actually merged until recently, and I forgot to update the error
messages to our current standards. Fix that now.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-09-25 20:03:05 -03:00
Ernesto A. Fernández 1756ff18d3 Limit transaction size on systems without much ram
Gilgamesh reports via email that there is a kernel crash when you try to
copy an 800Mb file on a system with 512Mb of memory. The reason is that
I don't allow buffer heads to be reclaimed before commit time (I tried
it at some point and it was trickier than it seemed), and since commit
c5dfaa2de9 ("Allow bigger transactions"), each transaction can get as
big as 256Mb.

So, until I can get around to the reclaim issue (or hopefully get rid of
buffer heads), make transactions smaller for systems with little memory.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-09-22 16:28:05 -03:00
Ernesto A. Fernández 31df49c6d8 Ban writes to compressed files explicitly
The official implementation doesn't seem to truly support writes to
compressed files: when it's attempted, the file gets decompressed
transparently instead. I don't intend to that in this driver, unless
someone actually requests it. Users can just make a decompressed copy of
the file and replace the original.

By mistake, truncating compressed files is currently allowed, but since
compressed reads don't depend on the vfs-reported size, nothing seems to
happen. Other writes fail, but the error code is confusing and there is
no output on dmesg. Ban all writes explicitly, and explain the problem
in the console.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-09-21 19:50:09 -03:00
Ernesto A. Fernández e4bb06ecef Avoid reading whole compressed files into memory
Currently, compressed files saved in xattrs are read into memory all at
once, and later decompressed as needed. This has always required a large
memory allocation, which can be a problem in general, but especially for
32-bit archs which can't request more than 128Mb from vmalloc(). As
mentioned in commit 1e3fa28c4f ("Increase limit for compressed size
of files"), we are beginning to encounter files bigger than that limit.

Using the new apfs_nonsparse_dstream_read() to read from arbitrary xattr
offsets, rework the compressed reads so that we only allocate memory for
one compressed block at a time. For now the change is only for resource
xattrs, since I don't expect inline xattrs to ever be this big.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-09-20 15:41:49 -03:00
Ernesto A. Fernández a68325ef9e Spin xattr dstream reads into a new function
Lately I'm encountering more and more compressed files that are too
large for their xattrs to be read into memory all at once, so I'll need
to be able to read xattrs from arbitrary offsets. The code for this is
very similar to what's already inside apfs_xattr_extents_read(), so spin
it into a new apfs_nonsparse_dstream_read() with a generic interface
that can later be reused from compress.c.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-09-20 15:34:00 -03:00
Ernesto A. Fernández af0671f58f 0.3.4
This release fixes the build for the Linux 6.5 release candidate, and it
should also fix a long-standing mmap bug in Linux 5.14 and above, which
resulted in null pointer dereference.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-08-14 23:50:19 -03:00
Ernesto A. Fernández 740d7db44b Fix mmap for kernels 5.14 and above
Adamantinum reports trouble while attempting to use apfs as root with
kernel version 6.4.8:

  https://github.com/linux-apfs/linux-apfs-rw/issues/50

His callstack shows an npd in mmap, and the bug can be easily reproduced
by generic/029, but not in kernel version 5.3, where I usually run my
tests. Via bisection I tracked the problem back to kernel commit
0af573780b0b ("mm: require ->set_page_dirty to be explicitly wired up").
Starting with kernel 5.14, the ->set_page_dirty() address space method
gets called unconditionally, without checking for null first, so set it
explicitly.

Kernel 5.18 replaced ->set_page_dirty() with ->dirty_folio(), so take
care of that as well.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-08-14 19:50:22 -03:00
Ernesto A. Fernández bc2be91bb4 Update FMODE_* stuff for the 6.5 kernel
The build is broken for the Linux 6.5 release candidate:

  https://github.com/linux-apfs/linux-apfs-rw/issues/49

The fmode_t type can no longer be used for block open flags, and we must
switch to blk_mode_t instead. FMODE_EXCL is no longer needed, since just
having a holder already implies it, but this requires a change to the
blkdev_put() api. There is also a new argument to blkdev_get_by_path()
which can be safely ignored. And finally, sb->s_mode is gone, but it
doesn't seem to make any difference.

Update all the code to the new apis.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-08-08 20:58:11 -03:00
Ernesto A. Fernández 5c4773c036 Convert all strcpy() to strscpy()
The build appears to be broken for some configurations on the Linux 6.5
release candidate:

  https://github.com/linux-apfs/linux-apfs-rw/issues/49

Some sort of static overflow check is going on for strcpy(), and several
of my calls are triggering false positives. Just be safe and switch them
all to strscpy(). The qstr stuff in particular looked a bit too weird
anyway.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-08-08 19:14:10 -03:00
Ernesto A. Fernández 1e3fa28c4f Increase limit for compressed size of files
A recent cryptex image contains a file with a compressed size above the
current 128Mb limit. This limit exists because of vmalloc(), and it can
be increased (at least for 64-bit archs). Do that for now, but I really
should try to restructure the code to use smaller kmalloc() allocations
instead.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-06-07 20:40:53 -03:00
Ernesto A. Fernández d4799475db 0.3.3
This release fixes builds for kernels below 5.3, which have all been
broken for a while. So far development has only been focused on Linux
5.3, and I've relied on reporters to find out about issues on other
versions. From now on I will at least run builds for a range of kernels
before each release, so hopefully this won't happen again.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-05-24 23:05:25 -03:00
Ernesto A. Fernández c54e3a7423 Silence b_blocknr width warnings on old kernels
While fixing the build for old kernels, I noticed that in some of them
you get a warning when you prink a buffer head's b_blocknr as 0x%llx.
I haven't checked but I'm guessing that, at some point, sector_t on
64-bit archs went from being 'unsigned long' to 'unsigned long long',
so these warnings went away. Anyway, just cast b_blocknr before printing
it in all kernels.

At some point I do need to attempt a 32-bit build though. It's been a
long time, and I'm sure there will be much worse problems than this one.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-05-19 18:49:38 -03:00
Ernesto A. Fernández b185ce13bd Fix builds before generic_copy_file_range()
Even with the previous patch, builds are still broken for all kernels
before 5.2. The problem is that generic_copy_file_range() wasn't
introduced until Linux 5.3. The good news is that we don't actually need
it for older kernels: as I explained in the commit message for the patch
that broke this, we can just returning an error code from
apfs_remap_file_range().

Fixes: 396650b056 ("Don't let copy_file_range() use clones")
Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-05-19 18:31:51 -03:00
Ernesto A. Fernández 42d70a8997 Fix build for kernels with separate clone/dedupe
Luflosi reports that the build is broken once again for Linux 4.14 and
4.19:

  https://github.com/linux-apfs/linux-apfs-rw/issues/43

The problem here is that the clone and dedupe operations used to be
implemented with separate methods. Since Linux 4.20, they both use the
same ->remap_file_range(), with some flags passed to tell them apart.
So when I implemented clones I used this new version and broke the build
for the old ones. Fix it now.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-05-19 18:31:51 -03:00
Ernesto A. Fernández 97ba9b0dc8 0.3.2
This release improves error messages, which will hopefully make it
easier to communicate with bug reporters. A number of bugs are also
addressed, most importantly a missing check on the node count limit for
the free queues, which could trigger reports of corruption in some rare
cases (no data loss though, as far as I can see).

Support is added for the 6.3 kernel version, courtesy of Woody Suwalski.

I was hoping to wait until encryption was ready before making a release,
but I'm not finding much time for apfs these days so that could take a
while. In the meantime, it's better to get this stuff out the door.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-05-16 17:57:01 -03:00
Ernesto A. Fernández 8b99af84d1 Try to avoid failing insertion on fragmented nodes
I'm getting somewhat regular failures on generic/112 because the ip free
queue for the test image has a one-node limit, and it sometimes gets
full. The thing is, the node actually has plenty of room, but it's all
in the key free list, so I can't allocate values. From now on, if an
insertion fails with ENOSPC, check the available room and defragment
the node if it should be enough. Then retry the insertion instead of
jumping straight to a split.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-04-17 20:05:26 -03:00
Ernesto A. Fernández 3a605ec8ff Don't ignore error code in apfs_flush_fq_rec()
The previous patch was intended to trigger an immediate abort when a
free queue violated its own node limit. But I managed to trigger this
event again with generic/112, and to my surprise there were several
operations in dmesg before the abort finally happened. The problem here
is in apfs_flush_fq_rec(): when apfs_main_free() fails (in this case
because the ip free queue is full), the error code is reported but not
bubbled up. This is a mistake of course, so fix it.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-04-12 17:49:12 -03:00
Ernesto A. Fernández ccefdd13d8 Don't allow free queues to exceed their node limit
Free queues have a node limit that is set by the mkfs. Very rarely,
generic/112 manages to break this limit, and corruption is reported.
Preventing corruption is always the number one priority, so add a check
for this limit after every free queue insertion so that we can abort
immediately when it fails.

Remember though, that there is a deeper issue here: either the btrees
are becoming too fragmented, or the flushes are not frequent enough. The
queues should never fill like this.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-04-12 16:47:55 -03:00
Ernesto A. Fernández 5beaaae75c Fix out-of-bounds read on snapshot ioctl
Don't call strlen() on the name argument of the ioctl, because it may
not be null-terminated. I'm not sure what the consequences of this are,
but I don't think it should be exploitable. Use strnlen() instead.

Also move the length check outside the transaction: we don't want simple
user mistakes triggering aborts. And fix the returned error code: there
is no on-disk corruption going on, just user error.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-04-05 23:06:22 -03:00
Ernesto A. Fernández 0f47fc762a Fix memory leak on xattr length overflow
Always free the allocated dstream in apfs_xattr_extents_read() before
returning.

Fixes: 362c4e32ab ("Allow internal reads of huge xattrs")
Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-04-05 22:21:53 -03:00
Ernesto A. Fernández d4797823ea Improve error reporting
The driver is much closer to being usable, so I might start getting
subtler bug reports soon. To make them easier to handle, put error
messages all over the place. I should have done this from the beginning,
but I guess I didn't fully understand the need back then.

From now my general policy will be to use apfs_warn() for user errors or
unsupported features; apfs_err() for things that are probably corruption
or io errors; and apfs_alert() for things that are most likely bugs.
These last two should be rare, so the same error/alert will be thrown by
several layers in the callstack to provide as much information as
possible. Be careful and don't flood the console on normal situations.

Also, make messages with a log level lower than warning output their
function name and line number, which I think will help debugging more
than the actual messages.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-04-05 21:59:24 -03:00
Woody Suwalski 24daddc890 Changes needed to build on kernel 6.3 2023-03-24 15:12:47 -03:00
Ernesto A. Fernández 72e8873a6a 0.3.1
Snapshots and clones seem to be working properly now, though testing has
been somewhat limited. As far as I know (I could definitely be wrong),
this is the last thing that was needed to fully support writes to
unencrypted volumes, so it's an important change that warrants a new
release. Everything remains experimental, of course.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-03-23 21:15:51 -03:00
Ernesto A. Fernández 8bb6d325ea Try to make longer free queue records
When running xfstests generic/142 (a file clone test), I encounter the
following error:

  APFS (2cg): creation of cpm blocks not yet supported

This is expected to happen when we have an absurdly large number of free
queue records. In this particular test, many writes are made to the
middle of files, so each of these writes becomes its own extent. When
the file is later deleted, all of these extents are deleted in a single
massive transaction. Each of them becomes its own free queue record, and
there is no opportunity to flush the queue.

There are three problems in here. The first one is that writes to the
middle of files should be allowed to allocate longer extents. The second
one is that truncation of orphan files should get split in multiple
transactions. These problems are important, but for now I just want to
test file clones, so I'll leave the fixes for later.

The third problem, much easier to fix, is that the driver should never
create bursts of small consecutive free queue records: it should just
merge them all into a bigger one. For that purpose, keep a cache of the
latest freed range, and always attempt to extend it instead of creating
a new record directly.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-03-23 00:50:22 -03:00
Ernesto A. Fernández 7ea6920bc4 Give a clone its own dstream before mmap writes
Call apfs_inode_create_exclusive_dstream() during mkwrite(), just like
we do during write_begin(), or else things could get weird for cloned
files. This patch fixes generic/140 of xfstests.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-03-22 19:18:34 -03:00
Ernesto A. Fernández 699a07189a Don't try to map invalid blocks in get_block()
If __apfs_get_block() gets called with a block number after the end of
the file, it still maps the buffer head successfully but using invalid
information from the previous extent. So far this has never been a
problem for any of the callers, but the previous patch implemented
FIEMAP and generic_block_fiemap() appears to use an unmapped buffer head
to check for EOF. With the current code, it just loops forever.

So, do the right thing and check that the logical block is in range
before doing any extent lookups. At this point there is no reason why
apfs_extent_read() should ever fail to find a matching extent, so make
it return EFSCORRUPTED when that happens.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-03-22 18:30:18 -03:00
Ernesto A. Fernández 1490bc7d36 Support FIEMAP for the 5.3 kernel
I'm trying to run the "clone" group of xfstests, but it seems that those
tests require the FIEMAP ioctl to confirm that clones share the same
physical extents. This doesn't seem trivial to implement for all kernel
versions, so for now only do it for 5.3, the one I use for testing.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-03-22 16:14:02 -03:00
Ernesto A. Fernández d74165587b Don't free the blocks on update extent deletion
If an UPDATE record is created to take a reference, and then a reference
to that same range gets put, then the UPDATE extent will simply get
deleted. When that happens, we mistakenly mark all of its blocks as
free, but the blocks are still in use by the original snapshot. Fix
this.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-03-20 21:29:59 -03:00
Ernesto A. Fernández e8847c734a Don't copy the sparse flag into cloned inodes
When an inode becomes a clone, the internal flags from the original get
copied to it. The problem is that a few of these flags imply the
presence of a matching xfield, but those haven't been created at this
point. The sparse xfield, in particular, may never get created at all if
the original file is no longer sparse. Don't copy those xfield flags,
just set them when the xfield gets created as usual.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-03-17 21:32:10 -03:00
Ernesto A. Fernández 201b0872fd Correct return value for apfs_remap_file_range()
The return value for apfs_remap_file_range() on sucess is supposed to be
the length of the copied region, not 0. I haven't checked if this has
any practical consequences, but fix it.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-03-17 17:20:49 -03:00
Ernesto A. Fernández 396650b056 Don't let copy_file_range() use clones
I'm seeing a silly regression in generic/430: now that clones are
implemented, copy_file_range() has started to use them under the hood,
but it only wants to clone a portion of the file, and that's not
something I'm interested in supporting.

To avoid this on newer kernels, set ->copy_file_range() to the generic
implementation. For older kernels, start throwing errors if anything
calls apfs_remap_file_range() for partial ranges. This is the right
thing to do in general, since we don't support that.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-03-17 17:20:49 -03:00
Ernesto A. Fernández b00b571757 Implement writes to cloned extents
This rewrites a considerable part of the physical extents code, so let's
hope for the best.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-03-17 01:42:44 -03:00
Ernesto A. Fernández c994a77bfd Fork cloned dstreams on write operations
When first created, a clone is just a new reference to the original
dstream. At this point the driver can't even delete a cloned file,
because all of the dstream extents go away, and those are still in use
by the other copies.

So, before any write operation happens on a clone file, create a new
dstream for the modified copy, with its own file extents and new
references to the physical extents. This should at least allow deletion
to work correctly, but real writes will not, because individual extent
changes haven't been implemented yet. It won't be hard though, because
now my mind is a little more clear about this stuff.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-03-17 01:42:44 -03:00
Ernesto A. Fernández 573fe59e7f Implement basic file cloning functionality
Implement the FICLONE ioctl to be able to create clones of files. This
will never work the same as macos, because Linux requires that the user
first creates the target file, and only then it can be made into a
clone. A crash halfway throught would leave an empty file in place of
the clone.

This patch only duplicates the data stream, it does not deal with the
actual extents. Reads from clones should work correctly, but writes will
not. I'll get to that right away.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-03-08 22:22:18 -03:00
Ernesto A. Fernández 76babcc7ad Fix cleanup on failure during snapshot creation
It seems that I messed up the cleanups during some late fixups to the
code in apfs_do_ioc_take_snapshot(): the transaction could be left open
in some cases. Fix it.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-03-08 19:18:50 -03:00
Ernesto A. Fernández 9c39466269 Make updates to blocks_freed and blocks_alloced
The apfs_total_blocks_freed and apfs_total_blocks_alloced fields of the
volume superblock keep track of the total number of blocks that have
been freed/alloced through the whole lifetime of the volume so far.
Since the value of these fields depends on historical operations, it
can't be calculated from the volume contents, so I figured I could just
ignore them without consequences.

This seems to be mostly correct, but the official fsck does complain if
the freed blocks appear to be more than the alloced blocks. It's just a
warning, not an error, but it does often trigger after the official
driver makes changes to one of my images. So, try to be careful with
these two fields from now on.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-03-06 22:05:29 -03:00
Ernesto A. Fernández 7a5d4085ea Fix apfs_node_min_table_size() for non-leaf nodes
In the previous patch I forgot to consider that index nodes have
different value sizes than leaf nodes, even for fixed key/value size
trees. Fix it.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-02-22 17:30:45 -03:00
Ernesto A. Fernández d29943de45 Fix apfs_node_min_table_size() for new tree types
When I started working with OMAP_SNAPSHOT trees, I forgot to add support
for them inside apfs_node_min_table_size(). The result is that the index
of each of those trees is initialized to a tiny minimum size, as if the
keys and values were of variable length. This went unnoticed for a while
because of other bugs in my fsck, which I've recently fixed in
5a20a212d8f0 ("apfsck: fix checks of index size for fixed kv size"). The
official fsck always complained though, I just wasn't using it:

  ** Checking the snapshot metadata.
  error: btn: invalid btn_table_space (0, 64), given btn_flags (0x7)

So, implement apfs_node_min_table_size() properly for the OMAP_SNAPSHOT
tree type. For consistency with the fsck, also implement the FEXT tree
type, but I don't actually support writes to sealed volumes in the
driver at the moment.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-02-21 22:55:31 -03:00
Ernesto A. Fernández 2e63fbc8dd Add APFS prefix to all object type macros
Some recently defined object types are missing the "APFS_" prefix. I've
fixed this a while back in the fsck, do it in the driver too.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-02-21 22:54:39 -03:00
Ernesto A. Fernández 15d5ab65d5 Set a snapshot's inum on creation
Right now the "inum" field of new snapshot metadata record gets set to
zero, and the official fsck is complaining about it. I was confused for
a while about this field because I thought it referred to an actual file
somewhere, but now I'm pretty sure it's just an identifier for the
snapshot, which gets picked from the same pool as regular inode numbers.
So, do that.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-02-21 20:16:18 -03:00
Ernesto A. Fernández 8c330866de Fix volume block count after snapshots
There are two bugs in the way apfs_fs_alloc_count is calculated after a
snapshot. I had not noticed them so far because it randomly gets the
right number as long as no node splits happen, but the new test I'm
working on (called apfs/006 for now) does split nodes and reports the
corruption.

Anyway, the problems are that the volume superblock should never get
counted in apfs_fs_alloc_count, not even after a snapshot; and that
regular CoW of virtual nodes needs to increase apfs_fs_alloc_count if
the original is preserved in a snapshot. Fix both now.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-02-17 22:53:18 -03:00
Ernesto A. Fernández 0e15c381c1 Fix mmap regressions from snapshot writes
The previous commit has caused regressions for a couple of mmap tests
from xfstests. I always assumed that all buffer heads mapping a physical
block would be the same object, with the same metadata, but that's only
true for buffer heads in the same mapping. So the apfs_sb_bread() inside
apfs_zero_dstream_tail() will not get the same bh that joined the
transaction via mmap, and two separate CoWs will happen, losing some of
the writes.

So, first of all, apfs_zero_dstream_tail() can't just read blocks from
the device like it used to, it needs to have a reference to the file
mapping and work with that. Put a pointer to the inode in the dstream
info for this purpose. Now, since individual buffer tails are already
zeroed during ->write_begin(), spin the part of that code that doesn't
deal with transactions into __apfs_write_begin() and __apfs_write_end(),
and use those here. Finally, reorder apfs_dstream_get_new_block() to
avoid problems with the extent cache during this recursion.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-02-16 18:47:28 -03:00
Ernesto A. Fernández 9e5e2aaf17 Implement writes to snapshot files
Make the necessary changes to the extent code so that writes to files
that are part of a snapshot will work correctly. I don't believe there
is any real risk of deleting the original content at this point, because
those physical extents are kept in a separate tree. The real problem is
keeping track of extent references, because that will become important
for the official implementation if a snapshot gets deleted.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-02-16 18:47:28 -03:00
Ernesto A. Fernández b5a2f9fb62 Update the README with compression support
As I mentioned in the release notes, the driver now has a reasonable
support for compression. The README still claims that it doesn't,
though, because I forgot to update it before the release. Fix it now.

Signed-off-by: Ernesto A. Fernández <ernesto@corellium.com>
2023-02-02 19:19:00 -03:00
24 changed files with 4363 additions and 1744 deletions

No files matched your search

+1
View File
@@ -9,3 +9,4 @@
*.a
*.mod
tags
version.h
+2
View File
@@ -14,8 +14,10 @@ apfs-y := btree.o compress.o dir.o extents.o file.o inode.o key.o libzbitmap.o \
spaceman.o super.o symlink.o transaction.o unicode.o xattr.o xfield.o
default:
./genver.sh
make -C $(KERNEL_DIR) M=$(PWD)
install:
make -C $(KERNEL_DIR) M=$(PWD) modules_install
clean:
rm -f version.h
make -C $(KERNEL_DIR) M=$(PWD) clean
+1 -2
View File
@@ -22,8 +22,7 @@ This module is the result of reverse engineering and testing has been limited.
If you make use of the write support, expect data corruption. Please report any
issues that you find, but I can't promise a quick resolution at this stage.
Many features are not yet implemented, including encryption and most forms of
compression.
Encryption is not yet implemented even in read-only mode.
Build
=====
+125 -28
View File
@@ -13,8 +13,6 @@
#include <linux/version.h>
#include "apfs_raw.h"
#define APFS_MODULE_ID_STRING "linux-apfs by EA Fernández"
#define EFSBADCRC EBADMSG /* Bad CRC detected */
#define EFSCORRUPTED EUCLEAN /* Filesystem is corrupted */
@@ -124,7 +122,7 @@ static inline bool apfs_node_has_fixed_kv_size(struct apfs_node *node)
struct apfs_spaceman {
struct apfs_spaceman_phys *sm_raw; /* On-disk spaceman structure */
struct buffer_head *sm_bh; /* Buffer head for @sm_raw */
struct buffer_head *sm_ip; /* Current internal pool */
struct apfs_nxsb_info *sm_nxi; /* Container superblock */
u32 sm_blocks_per_chunk; /* Blocks covered by a bitmap block */
u32 sm_chunks_per_cib; /* Chunk count in a chunk-info block */
@@ -133,6 +131,22 @@ struct apfs_spaceman {
u32 sm_cib_count; /* Number of chunk-info blocks */
u64 sm_free_count; /* Number of free blocks */
u32 sm_addr_offset; /* Offset of cib addresses in @sm_raw */
/*
* A range of freed blocks not yet put in the free queue. Extend this as
* much as possible before creating an actual record.
*/
u64 sm_free_cache_base;
u64 sm_free_cache_blkcnt;
/* Shift to match an ip block with its bitmap in the array */
int sm_ip_bmaps_shift;
/* Mask to find an ip block's offset inside its ip bitmap */
u32 sm_ip_bmaps_mask;
/* Number of ip bitmaps */
u32 sm_ip_bmaps_count;
/* List of ip bitmaps, in order */
struct buffer_head *sm_ip_bmaps[];
};
#define TRANSACTION_MAIN_QUEUE_MAX 4096
@@ -212,7 +226,7 @@ struct apfs_nxsb_info {
unsigned long nx_blocksize;
unsigned char nx_blocksize_bits;
struct apfs_spaceman nx_spaceman;
struct apfs_spaceman *nx_spaceman;
struct apfs_nx_transaction nx_transaction;
/* For now, a single semaphore for every operation */
@@ -276,6 +290,8 @@ struct apfs_sb_info {
struct list_head list; /* List of mounted volumes in container */
struct apfs_superblock *s_vsb_raw; /* On-disk volume sb */
dev_t s_anon_dev; /* Anonymous device for this volume-snapshot */
char *s_snap_name; /* Label for the mounted snapshot */
u64 s_snap_xid; /* Transaction id for mounted snapshot */
@@ -292,6 +308,7 @@ struct apfs_sb_info {
struct apfs_crypto_state_val *s_dflt_pfk; /* default per-file key */
struct apfs_vol_transaction s_transaction;
int s_trans_buffers_max;
struct inode *s_private_dir; /* Inode for the private directory */
};
@@ -312,8 +329,10 @@ static inline bool apfs_is_sealed(struct super_block *sb)
* apfs_vol_is_encrypted - Check if a volume is encrypting files
* @sb: superblock
*/
static inline bool apfs_vol_is_encrypted(struct super_block *sb) {
static inline bool apfs_vol_is_encrypted(struct super_block *sb)
{
struct apfs_superblock *vsb_raw = APFS_SB(sb)->s_vsb_raw;
return (vsb_raw->apfs_fs_flags & cpu_to_le64(APFS_FS_UNENCRYPTED)) == 0;
}
@@ -332,7 +351,7 @@ static inline struct apfs_nxsb_info *APFS_NXI(struct super_block *sb)
*/
static inline struct apfs_spaceman *APFS_SM(struct super_block *sb)
{
return &APFS_NXI(sb)->nx_spaceman;
return APFS_NXI(sb)->nx_spaceman;
}
static inline bool apfs_is_case_insensitive(struct super_block *sb)
@@ -490,7 +509,7 @@ static inline void apfs_init_sibling_link_key(u64 ino, u64 id,
{
key->id = ino;
key->type = APFS_TYPE_SIBLING_LINK;
key->number = id; /* Only guessing */
key->number = id; /* Only guessing (TODO) */
key->name = NULL;
}
@@ -604,7 +623,7 @@ static inline u64 apfs_cat_cnid(struct apfs_key_header *key)
*/
struct apfs_query {
struct apfs_node *node; /* Node being searched */
struct apfs_key *key; /* What the query is looking for */
struct apfs_key key; /* What the query is looking for */
struct apfs_query *parent; /* Query for parent node */
unsigned int flags;
@@ -639,7 +658,9 @@ static inline u32 apfs_query_storage(struct apfs_query *query)
return APFS_OBJ_PHYSICAL;
if (query->flags & APFS_QUERY_OMAP_SNAP)
return APFS_OBJ_PHYSICAL;
BUG();
/* Absurd, but don't panic: let the callers fail and report it */
return -1;
}
/*
@@ -660,6 +681,7 @@ struct apfs_phys_extent {
u64 blkcount;
u64 len; /* In bytes */
u32 refcnt;
u8 kind;
};
/*
@@ -667,12 +689,14 @@ struct apfs_phys_extent {
*/
struct apfs_dstream_info {
struct super_block *ds_sb; /* Filesystem superblock */
struct inode *ds_inode; /* NULL for xattr dstreams */
u64 ds_id; /* ID of the extent records */
u64 ds_size; /* Length of the stream */
u64 ds_sparse_bytes;/* Hole byte count in stream */
struct apfs_file_extent ds_cached_ext; /* Latest extent record */
bool ds_ext_dirty; /* Is ds_cached_ext dirty? */
spinlock_t ds_ext_lock; /* Protects ds_cached_ext */
bool ds_shared; /* Has multiple references? */
};
/**
@@ -764,17 +788,31 @@ struct apfs_xattr {
bool has_dstream;
};
#define apfs_emerg(sb, fmt, ...) apfs_msg(sb, KERN_EMERG, fmt, ##__VA_ARGS__)
#define apfs_alert(sb, fmt, ...) apfs_msg(sb, KERN_ALERT, fmt, ##__VA_ARGS__)
#define apfs_crit(sb, fmt, ...) apfs_msg(sb, KERN_CRIT, fmt, ##__VA_ARGS__)
#define apfs_err(sb, fmt, ...) apfs_msg(sb, KERN_ERR, fmt, ##__VA_ARGS__)
#define apfs_warn(sb, fmt, ...) apfs_msg(sb, KERN_WARNING, fmt, ##__VA_ARGS__)
#define apfs_notice(sb, fmt, ...) apfs_msg(sb, KERN_NOTICE, fmt, ##__VA_ARGS__)
#define apfs_info(sb, fmt, ...) apfs_msg(sb, KERN_INFO, fmt, ##__VA_ARGS__)
struct apfs_compressed_data {
bool has_dstream;
u64 size;
union {
struct apfs_dstream_info *dstream;
void *data;
};
};
/*
* Report function name and line number for the message types that are likely
* to signal a bug, to make things easier for reporters. Don't do this for the
* common messages, there is no point and it makes the console look too busy.
*/
#define apfs_emerg(sb, fmt, ...) apfs_msg(sb, KERN_EMERG, __func__, __LINE__, fmt, ##__VA_ARGS__)
#define apfs_alert(sb, fmt, ...) apfs_msg(sb, KERN_ALERT, __func__, __LINE__, fmt, ##__VA_ARGS__)
#define apfs_crit(sb, fmt, ...) apfs_msg(sb, KERN_CRIT, __func__, __LINE__, fmt, ##__VA_ARGS__)
#define apfs_err(sb, fmt, ...) apfs_msg(sb, KERN_ERR, __func__, __LINE__, fmt, ##__VA_ARGS__)
#define apfs_warn(sb, fmt, ...) apfs_msg(sb, KERN_WARNING, NULL, 0, fmt, ##__VA_ARGS__)
#define apfs_notice(sb, fmt, ...) apfs_msg(sb, KERN_NOTICE, NULL, 0, fmt, ##__VA_ARGS__)
#define apfs_info(sb, fmt, ...) apfs_msg(sb, KERN_INFO, NULL, 0, fmt, ##__VA_ARGS__)
#ifdef CONFIG_APFS_DEBUG
#define ASSERT(expr) BUG_ON(!(expr))
#define apfs_debug(sb, fmt, ...) apfs_msg(sb, KERN_DEBUG, fmt, ##__VA_ARGS__)
#define ASSERT(expr) WARN_ON(!(expr))
#define apfs_debug(sb, fmt, ...) apfs_msg(sb, KERN_DEBUG, __func__, __LINE__, fmt, ##__VA_ARGS__)
#else
#define ASSERT(expr) ((void)0)
#define apfs_debug(sb, fmt, ...) no_printk(fmt, ##__VA_ARGS__)
@@ -793,16 +831,17 @@ do { \
} while (0)
/* btree.c */
extern struct apfs_node *apfs_query_root(const struct apfs_query *query);
extern struct apfs_query *apfs_alloc_query(struct apfs_node *node,
struct apfs_query *parent);
extern void apfs_free_query(struct apfs_query *query);
extern int apfs_btree_query(struct super_block *sb, struct apfs_query **query);
extern struct apfs_node *apfs_omap_read_node(struct super_block *sb, u64 id);
extern int apfs_omap_lookup_block(struct super_block *sb, struct apfs_omap *omap,
u64 id, u64 *block, bool write);
extern int apfs_omap_lookup_block(struct super_block *sb, struct apfs_omap *omap, u64 id, u64 *block, bool write);
extern int apfs_omap_lookup_newest_block(struct super_block *sb, struct apfs_omap *omap, u64 id, u64 *block, bool write);
extern int apfs_create_omap_rec(struct super_block *sb, u64 oid, u64 bno);
extern int apfs_delete_omap_rec(struct super_block *sb, u64 oid);
extern int apfs_query_join_transaction(struct apfs_query *query);
extern int __apfs_btree_insert(struct apfs_query *query, void *key, int key_len, void *val, int val_len);
extern int apfs_btree_insert(struct apfs_query *query, void *key, int key_len,
void *val, int val_len);
extern int apfs_btree_remove(struct apfs_query *query);
@@ -828,7 +867,7 @@ extern int apfs_rename(struct inode *old_dir, struct dentry *old_dentry,
unsigned int flags);
extern int apfs_create(struct inode *dir, struct dentry *dentry, umode_t mode,
bool excl);
#else
#elif LINUX_VERSION_CODE < KERNEL_VERSION(6, 3, 0)
extern int apfs_mknod(struct user_namespace *mnt_userns, struct inode *dir,
struct dentry *dentry, umode_t mode, dev_t rdev);
extern int apfs_mkdir(struct user_namespace *mnt_userns, struct inode *dir,
@@ -838,6 +877,16 @@ extern int apfs_rename(struct user_namespace *mnt_userns, struct inode *old_dir,
struct dentry *new_dentry, unsigned int flags);
extern int apfs_create(struct user_namespace *mnt_userns, struct inode *dir,
struct dentry *dentry, umode_t mode, bool excl);
#else
extern int apfs_mknod(struct mnt_idmap *idmap, struct inode *dir,
struct dentry *dentry, umode_t mode, dev_t rdev);
extern int apfs_mkdir(struct mnt_idmap *idmap, struct inode *dir,
struct dentry *dentry, umode_t mode);
extern int apfs_rename(struct mnt_idmap *idmap, struct inode *old_dir,
struct dentry *old_dentry, struct inode *new_dir,
struct dentry *new_dentry, unsigned int flags);
extern int apfs_create(struct mnt_idmap *idmap, struct inode *dir,
struct dentry *dentry, umode_t mode, bool excl);
#endif
extern int apfs_link(struct dentry *old_dentry, struct inode *dir,
@@ -861,8 +910,17 @@ extern int apfs_get_new_block(struct inode *inode, sector_t iblock,
struct buffer_head *bh_result, int create);
extern int APFS_GET_NEW_BLOCK_MAXOPS(void);
extern int apfs_truncate(struct apfs_dstream_info *dstream, loff_t new_size);
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 20, 0)
extern loff_t apfs_remap_file_range(struct file *src_file, loff_t off, struct file *dst_file, loff_t destoff, loff_t len, unsigned int remap_flags);
#else
extern int apfs_clone_file_range(struct file *src_file, loff_t off, struct file *dst_file, loff_t destoff, u64 len);
#endif
extern int apfs_clone_extents(struct apfs_dstream_info *dstream, u64 new_id);
extern int apfs_nonsparse_dstream_read(struct apfs_dstream_info *dstream, void *buf, size_t count, u64 offset);
extern void apfs_nonsparse_dstream_preread(struct apfs_dstream_info *dstream);
/* file.c */
extern int apfs_file_mmap(struct file *file, struct vm_area_struct *vma);
extern int apfs_fsync(struct file *file, loff_t start, loff_t end, int datasync);
/* inode.c */
@@ -874,16 +932,27 @@ extern struct inode *apfs_new_inode(struct inode *dir, umode_t mode,
dev_t rdev);
extern int apfs_create_inode_rec(struct super_block *sb, struct inode *inode,
struct dentry *dentry);
extern int apfs_inode_create_exclusive_dstream(struct inode *inode);
extern int APFS_CREATE_INODE_REC_MAXOPS(void);
extern int __apfs_write_begin(struct file *file, struct address_space *mapping, loff_t pos, unsigned int len, unsigned int flags, struct page **pagep, void **fsdata);
extern int __apfs_write_end(struct file *file, struct address_space *mapping, loff_t pos, unsigned int len, unsigned int copied, struct page *page, void *fsdata);
extern int apfs_dstream_adj_refcnt(struct apfs_dstream_info *dstream, u32 delta);
#if LINUX_VERSION_CODE < KERNEL_VERSION(5, 12, 0)
extern int apfs_setattr(struct dentry *dentry, struct iattr *iattr);
#else
#elif LINUX_VERSION_CODE < KERNEL_VERSION(6, 3, 0)
extern int apfs_setattr(struct user_namespace *mnt_userns,
struct dentry *dentry, struct iattr *iattr);
#else
extern int apfs_setattr(struct mnt_idmap *idmap,
struct dentry *dentry, struct iattr *iattr);
#endif
#if LINUX_VERSION_CODE < KERNEL_VERSION(6, 6, 0)
extern int apfs_update_time(struct inode *inode, struct timespec64 *time, int flags);
#else
extern int apfs_update_time(struct inode *inode, int flags);
#endif
long apfs_dir_ioctl(struct file *file, unsigned int cmd, unsigned long arg);
long apfs_file_ioctl(struct file *file, unsigned int cmd, unsigned long arg);
@@ -893,16 +962,23 @@ extern int apfs_getattr(struct vfsmount *mnt, struct dentry *dentry,
#elif LINUX_VERSION_CODE < KERNEL_VERSION(5, 12, 0)
extern int apfs_getattr(const struct path *path, struct kstat *stat,
u32 request_mask, unsigned int query_flags);
#else
#elif LINUX_VERSION_CODE < KERNEL_VERSION(6, 3, 0)
extern int apfs_getattr(struct user_namespace *mnt_userns,
const struct path *path, struct kstat *stat, u32 request_mask,
unsigned int query_flags);
#else
extern int apfs_getattr(struct mnt_idmap *idmap,
const struct path *path, struct kstat *stat, u32 request_mask,
unsigned int query_flags);
#endif
extern int apfs_crypto_adj_refcnt(struct super_block *sb, u64 crypto_id, int delta);
extern int APFS_CRYPTO_ADJ_REFCNT_MAXOPS(void);
#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 13, 0)
#if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 3, 0)
extern int apfs_fileattr_get(struct dentry *dentry, struct fileattr *fa);
extern int apfs_fileattr_set(struct mnt_idmap *idmap, struct dentry *dentry, struct fileattr *fa);
#elif LINUX_VERSION_CODE >= KERNEL_VERSION(5, 13, 0)
extern int apfs_fileattr_get(struct dentry *dentry, struct fileattr *fa);
extern int apfs_fileattr_set(struct user_namespace *mnt_userns, struct dentry *dentry, struct fileattr *fa);
#endif
@@ -919,14 +995,13 @@ extern int apfs_read_snap_meta_key(void *raw, int size, struct apfs_key *key);
extern int apfs_read_omap_snap_key(void *raw, int size, struct apfs_key *key);
/* message.c */
extern __printf(3, 4)
void apfs_msg(struct super_block *sb, const char *prefix, const char *fmt, ...);
extern __printf(5, 6) void apfs_msg(struct super_block *sb, const char *prefix, const char *func, int line, const char *fmt, ...);
/* node.c */
extern struct apfs_node *apfs_read_node(struct super_block *sb, u64 oid,
u32 storage, bool write);
extern void apfs_update_node(struct apfs_node *node);
extern int apfs_delete_node(struct apfs_query *query);
extern int apfs_delete_node(struct apfs_node *node, int type);
extern int apfs_node_query(struct super_block *sb, struct apfs_query *query);
extern void apfs_node_query_first(struct apfs_query *query);
extern int apfs_omap_map_from_query(struct apfs_query *query, struct apfs_omap_map *map);
@@ -934,6 +1009,7 @@ extern int apfs_node_split(struct apfs_query *query);
extern int apfs_node_locate_key(struct apfs_node *node, int index, int *off);
extern void apfs_node_free(struct apfs_node *node);
extern void apfs_node_free_range(struct apfs_node *node, u16 off, u16 len);
extern bool apfs_node_has_room(struct apfs_node *node, int length, bool replace);
extern int apfs_node_replace(struct apfs_query *query, void *key, int key_len, void *val, int val_len);
extern int apfs_node_insert(struct apfs_query *query, void *key, int key_len, void *val, int val_len);
extern int apfs_create_single_rec_node(struct apfs_query *query, void *key, int key_len, void *val, int val_len);
@@ -957,6 +1033,7 @@ extern int apfs_switch_to_snapshot(struct super_block *sb);
/* spaceman.c */
extern int apfs_read_spaceman(struct super_block *sb);
extern int apfs_free_queue_insert_nocache(struct super_block *sb, u64 bno, u64 count);
extern int apfs_free_queue_insert(struct super_block *sb, u64 bno, u64 count);
extern int apfs_spaceman_allocate_block(struct super_block *sb, u64 *bno, bool backwards);
@@ -989,6 +1066,9 @@ extern int apfs_xattr_set(struct inode *inode, const char *name, const void *val
size_t size, int flags);
extern int APFS_XATTR_SET_MAXOPS(void);
extern ssize_t apfs_listxattr(struct dentry *dentry, char *buffer, size_t size);
extern int apfs_xattr_get_compressed_data(struct inode *inode, const char *name, struct apfs_compressed_data *cdata);
extern void apfs_release_compressed_data(struct apfs_compressed_data *cdata);
extern int apfs_compressed_data_read(struct apfs_compressed_data *cdata, void *buf, size_t count, u64 offset);
/* xfield.c */
extern int apfs_find_xfield(u8 *xfields, int len, u8 xtype, char **xval);
@@ -1002,6 +1082,7 @@ extern int apfs_insert_xfield(u8 *buffer, int buflen,
*/
/* compress.c */
extern const struct address_space_operations apfs_compress_aops;
extern const struct file_operations apfs_compress_file_operations;
/* dir.c */
@@ -1022,6 +1103,18 @@ extern const struct inode_operations apfs_symlink_inode_operations;
/* xattr.c */
extern const struct xattr_handler *apfs_xattr_handlers[];
/**
* apfs_assert_query_is_valid - Assert that all of a query's ancestors are set
* @query: the query to check
*
* A query may lose some of its ancestors during a node split, but nothing
* should be done to such a query until it gets refreshed.
*/
static inline void apfs_assert_query_is_valid(const struct apfs_query *query)
{
ASSERT(apfs_node_is_root(apfs_query_root(query)));
}
/*
* TODO: the following are modified variants of buffer head functions that will
* work with the shared block device for the container. The correct approach
@@ -1049,7 +1142,11 @@ apfs_getblk(struct super_block *sb, sector_t block)
{
struct buffer_head *bh;
#if LINUX_VERSION_CODE < KERNEL_VERSION(6, 7, 0)
bh = __getblk_gfp(APFS_NXI(sb)->nx_bdev, block, sb->s_blocksize, __GFP_MOVABLE);
#else
bh = bdev_getblk(APFS_NXI(sb)->nx_bdev, block, sb->s_blocksize, __GFP_MOVABLE);
#endif
if (bh)
set_buffer_uptodate(bh);
return bh;
+19 -19
View File
@@ -49,11 +49,11 @@
#define APFS_OBJECT_TYPE_GBITMAP 0x00000019
#define APFS_OBJECT_TYPE_GBITMAP_TREE 0x0000001a
#define APFS_OBJECT_TYPE_GBITMAP_BLOCK 0x0000001b
#define OBJECT_TYPE_ER_RECOVERY_BLOCK 0x0000001c
#define OBJECT_TYPE_SNAP_META_EXT 0x0000001d
#define OBJECT_TYPE_INTEGRITY_META 0x0000001e
#define OBJECT_TYPE_FEXT_TREE 0x0000001f
#define OBJECT_TYPE_RESERVED_20 0x00000020
#define APFS_OBJECT_TYPE_ER_RECOVERY_BLOCK 0x0000001c
#define APFS_OBJECT_TYPE_SNAP_META_EXT 0x0000001d
#define APFS_OBJECT_TYPE_INTEGRITY_META 0x0000001e
#define APFS_OBJECT_TYPE_FEXT_TREE 0x0000001f
#define APFS_OBJECT_TYPE_RESERVED_20 0x00000020
#define APFS_OBJECT_TYPE_INVALID 0x00000000
#define APFS_OBJECT_TYPE_TEST 0x000000ff
@@ -306,7 +306,7 @@ struct apfs_wrapped_crypto_state {
__le32 key_os_version;
__le16 key_revision;
__le16 key_len;
u8 persistent_key[0];
u8 persistent_key[];
} __packed;
/*
@@ -503,7 +503,7 @@ struct apfs_dir_stats_val {
struct apfs_sibling_val {
__le64 parent_id;
__le16 name_len;
u8 name[0];
u8 name[];
} __packed;
/*
@@ -622,7 +622,7 @@ enum {
struct apfs_drec_key {
struct apfs_key_header hdr;
__le16 name_len;
u8 name[0];
u8 name[];
} __packed;
/*
@@ -632,7 +632,7 @@ struct apfs_drec_key {
struct apfs_drec_hashed_key {
struct apfs_key_header hdr;
__le32 name_len_and_hash;
u8 name[0];
u8 name[];
} __packed;
/*
@@ -641,7 +641,7 @@ struct apfs_drec_hashed_key {
struct apfs_xattr_key {
struct apfs_key_header hdr;
__le16 name_len;
u8 name[0];
u8 name[];
} __packed;
/*
@@ -660,7 +660,7 @@ struct apfs_snap_metadata_key {
struct apfs_snap_name_key {
struct apfs_key_header hdr;
__le16 name_len;
u8 name[0];
u8 name[];
} __packed;
/*
@@ -1278,7 +1278,7 @@ enum {
struct apfs_xattr_val {
__le16 flags;
__le16 xdata_len;
u8 xdata[0];
u8 xdata[];
} __packed;
/*
@@ -1372,7 +1372,7 @@ struct apfs_file_info_key {
struct apfs_file_data_hash_val {
__le16 hashed_len;
u8 hash_size;
u8 hash[0];
u8 hash[];
} __packed;
#define APFS_FILE_INFO_DATA_HASH 1
@@ -1435,7 +1435,7 @@ struct apfs_compress_rsrc_data {
struct apfs_compress_rsrc_block {
__le32 offs;
__le32 size;
} __packed block[0];
} __packed block[];
} __packed;
/*
@@ -1456,7 +1456,7 @@ struct apfs_snap_metadata_val {
__le32 extentref_tree_type;
__le32 flags;
__le16 name_len;
u8 name[0];
u8 name[];
} __packed;
/*
@@ -1475,7 +1475,7 @@ struct apfs_snap_meta_ext {
__le32 sme_version;
__le32 sme_flags;
__le64 sme_snap_xid;
char sme_uuid[UUID_SIZE];
char sme_uuid[UUID_SIZE];
__le64 sme_token;
} __packed;
@@ -1503,11 +1503,11 @@ enum {
* Structure of a single entry in the keybag
*/
struct apfs_keybag_entry {
char ke_uuid[UUID_SIZE];
char ke_uuid[UUID_SIZE];
__le16 ke_tag;
__le16 ke_keylen;
__le32 padding;
u8 ke_keydata[0];
u8 ke_keydata[];
} __packed;
#define APFS_KEYBAG_VERSION 2
@@ -1520,7 +1520,7 @@ struct apfs_kb_locker {
__le16 kl_nkeys;
__le32 kl_nbytes;
__le64 padding;
struct apfs_keybag_entry kl_entries[0];
struct apfs_keybag_entry kl_entries[];
} __packed;
#endif /* _APFS_RAW_H */
+401 -217
View File
File diff suppressed because it is too large. Load diff
+327 -300
View File
File diff suppressed because it is too large. Load diff
+219 -83
View File
File diff suppressed because it is too large. Load diff
+2 -1
View File
@@ -1,7 +1,8 @@
PACKAGE_NAME="linux-apfs-rw"
PACKAGE_VERSION="0.3.0"
PACKAGE_VERSION="0.3.7"
BUILT_MODULE_NAME[0]="apfs"
DEST_MODULE_LOCATION[0]="/extra"
AUTOINSTALL="yes"
PRE_BUILD="genver.sh"
+1140 -331
View File
File diff suppressed because it is too large. Load diff
+64 -10
View File
@@ -18,6 +18,9 @@ static vm_fault_t apfs_page_mkwrite(struct vm_fault *vmf)
struct vm_area_struct *vma = vmf->vma;
#endif
struct page *page = vmf->page;
#if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 7, 0)
struct folio *folio;
#endif
struct inode *inode = file_inode(vma->vm_file);
struct super_block *sb = inode->i_sb;
struct buffer_head *bh, *head;
@@ -41,6 +44,12 @@ static vm_fault_t apfs_page_mkwrite(struct vm_fault *vmf)
goto out;
apfs_inode_join_transaction(sb, inode);
err = apfs_inode_create_exclusive_dstream(inode);
if (err) {
apfs_err(sb, "dstream creation failed for ino 0x%llx", apfs_ino(inode));
goto out_abort;
}
lock_page(page);
wait_for_stable_page(page);
if (page->mapping != inode->i_mapping) {
@@ -48,8 +57,16 @@ static vm_fault_t apfs_page_mkwrite(struct vm_fault *vmf)
goto out_unlock;
}
if (!page_has_buffers(page))
if (!page_has_buffers(page)) {
#if LINUX_VERSION_CODE < KERNEL_VERSION(6, 7, 0)
create_empty_buffers(page, sb->s_blocksize, 0);
#else
folio = page_folio(page);
bh = folio_buffers(folio);
if (!bh)
bh = create_empty_buffers(folio, sb->s_blocksize, 0);
#endif
}
size = i_size_read(inode);
if (page->index == size >> PAGE_SHIFT)
@@ -73,8 +90,10 @@ static vm_fault_t apfs_page_mkwrite(struct vm_fault *vmf)
unlock_page(page); /* XXX: race? */
err = block_page_mkwrite(vma, vmf, apfs_get_new_block);
if (err)
if (err) {
apfs_err(sb, "mkwrite failed for ino 0x%llx", apfs_ino(inode));
goto out_abort;
}
set_page_dirty(page);
/* An immediate commit would leave the page unlocked */
@@ -91,7 +110,11 @@ out_abort:
apfs_transaction_abort(sb);
out:
if (err)
#if LINUX_VERSION_CODE < KERNEL_VERSION(6, 6, 0)
ret = block_page_mkwrite_return(err);
#else
ret = vmf_fs_error(err);
#endif
sb_end_pagefault(inode->i_sb);
return ret;
}
@@ -102,7 +125,7 @@ static const struct vm_operations_struct apfs_file_vm_ops = {
.page_mkwrite = apfs_page_mkwrite,
};
static int apfs_file_mmap(struct file * file, struct vm_area_struct * vma)
int apfs_file_mmap(struct file *file, struct vm_area_struct *vma)
{
struct address_space *mapping = file->f_mapping;
@@ -130,15 +153,43 @@ int apfs_fsync(struct file *file, loff_t start, loff_t end, int datasync)
}
const struct file_operations apfs_file_operations = {
.llseek = generic_file_llseek,
.read_iter = generic_file_read_iter,
.write_iter = generic_file_write_iter,
.mmap = apfs_file_mmap,
.open = generic_file_open,
.fsync = apfs_fsync,
.unlocked_ioctl = apfs_file_ioctl,
.llseek = generic_file_llseek,
.read_iter = generic_file_read_iter,
.write_iter = generic_file_write_iter,
.mmap = apfs_file_mmap,
.open = generic_file_open,
.fsync = apfs_fsync,
.unlocked_ioctl = apfs_file_ioctl,
#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 3, 0)
.copy_file_range = generic_copy_file_range,
#endif
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 20, 0)
.remap_file_range = apfs_remap_file_range,
#else
.clone_file_range = apfs_clone_file_range,
#endif
#if LINUX_VERSION_CODE < KERNEL_VERSION(6, 5, 0)
.splice_read = generic_file_splice_read,
#else
.splice_read = filemap_splice_read,
#endif
.splice_write = iter_file_splice_write,
};
#if LINUX_VERSION_CODE == KERNEL_VERSION(5, 3, 0)
/*
* This is needed mainly to test clones with xfstests, so we only support the
* kernel version I use during testing. TODO: support all kernel versions.
*/
int apfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, u64 start, u64 len)
{
return generic_block_fiemap(inode, fieinfo, start, len, apfs_get_block);
}
#endif
const struct inode_operations apfs_file_inode_operations = {
.getattr = apfs_getattr,
.listxattr = apfs_listxattr,
@@ -148,4 +199,7 @@ const struct inode_operations apfs_file_inode_operations = {
.fileattr_get = apfs_fileattr_get,
.fileattr_set = apfs_fileattr_set,
#endif
#if LINUX_VERSION_CODE == KERNEL_VERSION(5, 3, 0)
.fiemap = apfs_fiemap,
#endif
};
Executable
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-2.0-only
#
# Script to generate the module version header
#
if command -v git >/dev/null 2>&1 && [ -d .git ]; then
GIT_COMMIT=$(git describe HEAD | tail -c 9)
else
GIT_COMMIT="$(grep PACKAGE_VERSION dkms.conf | cut -d '"' -f2)?"
fi
printf '#define GIT_COMMIT\t"%s"\n' "$GIT_COMMIT" > version.h
+551 -180
View File
File diff suppressed because it is too large. Load diff
+34 -10
View File
@@ -81,8 +81,10 @@ int apfs_keycmp(struct apfs_key *k1, struct apfs_key *k2)
*/
int apfs_read_cat_key(void *raw, int size, struct apfs_key *key, bool hashed)
{
if (size < sizeof(struct apfs_key_header))
if (size < sizeof(struct apfs_key_header)) {
apfs_err(NULL, "bad key length (%d)", size);
return -EFSCORRUPTED;
}
key->id = apfs_cat_cnid((struct apfs_key_header *)raw);
key->type = apfs_cat_type((struct apfs_key_header *)raw);
@@ -92,6 +94,7 @@ int apfs_read_cat_key(void *raw, int size, struct apfs_key *key, bool hashed)
if (size < sizeof(struct apfs_drec_hashed_key) + 1 ||
*((char *)raw + size - 1) != 0) {
/* Filename must have NULL-termination */
apfs_err(NULL, "invalid drec key (%d)", size);
return -EFSCORRUPTED;
}
/* Name length is not used in key comparisons, only the hash */
@@ -103,6 +106,7 @@ int apfs_read_cat_key(void *raw, int size, struct apfs_key *key, bool hashed)
if (size < sizeof(struct apfs_drec_key) + 1 ||
*((char *)raw + size - 1) != 0) {
/* Filename must have NULL-termination */
apfs_err(NULL, "invalid drec key (%d)", size);
return -EFSCORRUPTED;
}
/* There's no hash */
@@ -114,21 +118,26 @@ int apfs_read_cat_key(void *raw, int size, struct apfs_key *key, bool hashed)
if (size < sizeof(struct apfs_xattr_key) + 1 ||
*((char *)raw + size - 1) != 0) {
/* xattr name must have NULL-termination */
apfs_err(NULL, "invalid xattr key (%d)", size);
return -EFSCORRUPTED;
}
key->number = 0;
key->name = ((struct apfs_xattr_key *)raw)->name;
break;
case APFS_TYPE_FILE_EXTENT:
if (size != sizeof(struct apfs_file_extent_key))
if (size != sizeof(struct apfs_file_extent_key)) {
apfs_err(NULL, "bad key length (%d)", size);
return -EFSCORRUPTED;
}
key->number = le64_to_cpu(
((struct apfs_file_extent_key *)raw)->logical_addr);
key->name = NULL;
break;
case APFS_TYPE_SIBLING_LINK:
if (size != sizeof(struct apfs_sibling_link_key))
if (size != sizeof(struct apfs_sibling_link_key)) {
apfs_err(NULL, "bad key length (%d)", size);
return -EFSCORRUPTED;
}
key->number = le64_to_cpu(
((struct apfs_sibling_link_key *)raw)->sibling_id);
key->name = NULL;
@@ -146,8 +155,10 @@ int apfs_read_fext_key(void *raw, int size, struct apfs_key *key)
{
struct apfs_fext_tree_key *raw_key;
if (size != sizeof(*raw_key))
if (size != sizeof(*raw_key)) {
apfs_err(NULL, "bad key length (%d)", size);
return -EFSCORRUPTED;
}
raw_key = raw;
key->id = le64_to_cpu(raw_key->private_id);
@@ -169,8 +180,10 @@ int apfs_read_free_queue_key(void *raw, int size, struct apfs_key *key)
{
struct apfs_spaceman_free_queue_key *raw_key;
if (size < sizeof(struct apfs_spaceman_free_queue_key))
if (size < sizeof(struct apfs_spaceman_free_queue_key)) {
apfs_err(NULL, "bad key length (%d)", size);
return -EFSCORRUPTED;
}
raw_key = raw;
key->id = le64_to_cpu(raw_key->sfqk_xid);
@@ -191,8 +204,10 @@ int apfs_read_free_queue_key(void *raw, int size, struct apfs_key *key)
*/
int apfs_read_omap_key(void *raw, int size, struct apfs_key *key)
{
if (size < sizeof(struct apfs_omap_key))
if (size < sizeof(struct apfs_omap_key)) {
apfs_err(NULL, "bad key length (%d)", size);
return -EFSCORRUPTED;
}
key->id = le64_to_cpu(((struct apfs_omap_key *)raw)->ok_oid);
key->type = 0;
@@ -212,8 +227,10 @@ int apfs_read_omap_key(void *raw, int size, struct apfs_key *key)
*/
int apfs_read_extentref_key(void *raw, int size, struct apfs_key *key)
{
if (size != sizeof(struct apfs_phys_ext_key))
if (size != sizeof(struct apfs_phys_ext_key)) {
apfs_err(NULL, "bad key length (%d)", size);
return -EFSCORRUPTED;
}
key->id = apfs_cat_cnid((struct apfs_key_header *)raw);
key->type = apfs_cat_type((struct apfs_key_header *)raw);
key->number = 0;
@@ -223,21 +240,26 @@ int apfs_read_extentref_key(void *raw, int size, struct apfs_key *key)
int apfs_read_snap_meta_key(void *raw, int size, struct apfs_key *key)
{
if (size < sizeof(struct apfs_key_header))
if (size < sizeof(struct apfs_key_header)) {
apfs_err(NULL, "bad key length (%d)", size);
return -EFSCORRUPTED;
}
key->id = apfs_cat_cnid((struct apfs_key_header *)raw);
key->type = apfs_cat_type((struct apfs_key_header *)raw);
key->number = 0;
switch (key->type) {
case APFS_TYPE_SNAP_METADATA:
if (size != sizeof(struct apfs_snap_metadata_key))
if (size != sizeof(struct apfs_snap_metadata_key)) {
apfs_err(NULL, "bad key length (%d)", size);
return -EFSCORRUPTED;
}
key->name = NULL;
return 0;
case APFS_TYPE_SNAP_NAME:
if (size < sizeof(struct apfs_snap_name_key) + 1 || *((char *)raw + size - 1) != 0) {
/* snapshot name must have NULL-termination */
apfs_err(NULL, "invalid snap name key (%d)", size);
return -EFSCORRUPTED;
}
key->name = ((struct apfs_snap_name_key *)raw)->name;
@@ -251,8 +273,10 @@ int apfs_read_omap_snap_key(void *raw, int size, struct apfs_key *key)
{
__le64 *xid = NULL;
if (size != sizeof(*xid))
if (size != sizeof(*xid)) {
apfs_err(NULL, "bad key length (%d)", size);
return -EFSCORRUPTED;
}
xid = raw;
key->id = le64_to_cpup(xid);
+9 -2
View File
@@ -6,8 +6,9 @@
#include <linux/fs.h>
#include "apfs.h"
void apfs_msg(struct super_block *sb, const char *prefix, const char *fmt, ...)
void apfs_msg(struct super_block *sb, const char *prefix, const char *func, int line, const char *fmt, ...)
{
char *sb_id = NULL;
struct va_format vaf;
va_list args;
@@ -16,7 +17,13 @@ void apfs_msg(struct super_block *sb, const char *prefix, const char *fmt, ...)
vaf.fmt = fmt;
vaf.va = &args;
printk("%sAPFS (%s): %pV\n", prefix, sb->s_id, &vaf);
/* The superblock is not available to all callers */
sb_id = sb ? sb->s_id : "?";
if (func)
printk("%sAPFS (%s): %pV (%s:%d)\n", prefix, sb_id, &vaf, func, line);
else
printk("%sAPFS (%s): %pV\n", prefix, sb_id, &vaf);
va_end(args);
}
+10 -3
View File
@@ -18,13 +18,17 @@ static struct dentry *apfs_lookup(struct inode *dir, struct dentry *dentry,
return ERR_PTR(-ENAMETOOLONG);
err = apfs_inode_by_name(dir, &dentry->d_name, &ino);
if (err && err != -ENODATA)
if (err && err != -ENODATA) {
apfs_err(dir->i_sb, "inode lookup by name failed");
return ERR_PTR(err);
}
if (!err) {
inode = apfs_iget(dir->i_sb, ino);
if (IS_ERR(inode))
if (IS_ERR(inode)) {
apfs_err(dir->i_sb, "iget failed");
return ERR_CAST(inode);
}
}
return d_splice_alias(inode, dentry);
@@ -33,9 +37,12 @@ static struct dentry *apfs_lookup(struct inode *dir, struct dentry *dentry,
#if LINUX_VERSION_CODE < KERNEL_VERSION(5, 12, 0)
static int apfs_symlink(struct inode *dir, struct dentry *dentry,
const char *symname)
#else
#elif LINUX_VERSION_CODE < KERNEL_VERSION(6, 3, 0)
static int apfs_symlink(struct user_namespace *mnt_userns, struct inode *dir,
struct dentry *dentry, const char *symname)
#else
static int apfs_symlink(struct mnt_idmap *idmap, struct inode *dir,
struct dentry *dentry, const char *symname)
#endif
{
/* Symlink permissions don't mean anything and their value is fixed */
+476 -211
View File
File diff suppressed because it is too large. Load diff
+46 -11
View File
@@ -78,8 +78,10 @@ static int apfs_cpm_lookup_oid(struct super_block *sb,
u32 map_count = le32_to_cpu(cpm->cpm_count);
int i;
if (map_count > apfs_max_maps_per_block(sb))
if (map_count > apfs_max_maps_per_block(sb)) {
apfs_err(sb, "block has too many maps (%d)", map_count);
return -EFSCORRUPTED;
}
for (i = 0; i < map_count; ++i) {
struct apfs_checkpoint_mapping *map = &cpm->cpm_map[i];
@@ -214,14 +216,17 @@ int apfs_remove_cpoint_map(struct super_block *sb, u64 bno)
int err = 0;
bh = apfs_read_cpm_block(sb);
if (!bh)
if (!bh) {
apfs_err(sb, "failed to read cpm block");
return -EIO;
}
cpm = (struct apfs_checkpoint_map_phys *)bh->b_data;
apfs_assert_in_transaction(sb, &cpm->cpm_o);
/* TODO: multiple cpm blocks? */
cpm_count = le32_to_cpu(cpm->cpm_count);
if (cpm_count > apfs_max_maps_per_block(sb)) {
apfs_err(sb, "block has too many maps (%d)", cpm_count);
err = -EFSCORRUPTED;
goto fail;
}
@@ -240,6 +245,7 @@ int apfs_remove_cpoint_map(struct super_block *sb, u64 bno)
map->cpm_paddr = cpu_to_le64(apfs_data_index_to_bno(sb, curr_off - 1));
}
if (!bno_map) {
apfs_err(sb, "no mapping for bno 0x%llx", bno);
err = -EFSCORRUPTED;
goto fail;
}
@@ -269,8 +275,10 @@ struct buffer_head *apfs_read_ephemeral_object(struct super_block *sb, u64 oid)
u32 desc_len = le32_to_cpu(raw_sb->nx_xp_desc_len);
u32 i;
if (!desc_blks || !desc_len)
if (!desc_blks || !desc_len) {
apfs_err(sb, "no blocks in checkpoint descriptor area");
return ERR_PTR(-EFSCORRUPTED);
}
/* Last block in the area is superblock; the rest are mapping blocks */
for (i = 0; i < desc_len - 1; ++i) {
@@ -281,8 +289,10 @@ struct buffer_head *apfs_read_ephemeral_object(struct super_block *sb, u64 oid)
int err;
bh = apfs_sb_bread(sb, cpm_bno);
if (!bh)
if (!bh) {
apfs_err(sb, "failed to read cpm block");
return ERR_PTR(-EIO);
}
cpm = (struct apfs_checkpoint_map_phys *)bh->b_data;
err = apfs_cpm_lookup_oid(sb, cpm, oid, &obj_bno);
@@ -290,15 +300,20 @@ struct buffer_head *apfs_read_ephemeral_object(struct super_block *sb, u64 oid)
cpm = NULL;
if (err == -EAGAIN) /* Search the next mapping block */
continue;
if (err)
if (err) {
apfs_err(sb, "cpm lookup failed for oid 0x%llx", oid);
return ERR_PTR(err);
}
bh = apfs_sb_bread(sb, obj_bno);
if (!bh)
if (!bh) {
apfs_err(sb, "failed to read ephemeral block");
return ERR_PTR(-EIO);
}
return bh;
}
return ERR_PTR(-EFSCORRUPTED); /* The mapping is missing */
apfs_err(sb, "no mapping for oid 0x%llx", oid);
return ERR_PTR(-EFSCORRUPTED);
}
/**
@@ -315,6 +330,7 @@ struct buffer_head *apfs_read_ephemeral_object(struct super_block *sb, u64 oid)
struct buffer_head *apfs_read_object_block(struct super_block *sb, u64 bno, bool write, bool preserve)
{
struct apfs_nxsb_info *nxi = APFS_NXI(sb);
struct apfs_superblock *vsb_raw = NULL;
struct buffer_head *bh, *new_bh;
struct apfs_obj_phys *obj;
u32 type;
@@ -324,13 +340,16 @@ struct buffer_head *apfs_read_object_block(struct super_block *sb, u64 bno, bool
ASSERT(write || !preserve);
bh = apfs_sb_bread(sb, bno);
if (!bh)
if (!bh) {
apfs_err(sb, "failed to read object block 0x%llx", bno);
return ERR_PTR(-EIO);
}
obj = (struct apfs_obj_phys *)bh->b_data;
type = le32_to_cpu(obj->o_type);
ASSERT(!(type & APFS_OBJ_EPHEMERAL));
if (nxi->nx_flags & APFS_CHECK_NODES && !apfs_obj_verify_csum(sb, bh)) {
apfs_err(sb, "bad checksum for object in block 0x%llx", bno);
err = -EFSBADCRC;
goto fail;
}
@@ -344,18 +363,34 @@ struct buffer_head *apfs_read_object_block(struct super_block *sb, u64 bno, bool
return bh;
err = apfs_spaceman_allocate_block(sb, &new_bno, true /* backwards */);
if (err)
if (err) {
apfs_err(sb, "block allocation failed");
goto fail;
}
new_bh = apfs_getblk(sb, new_bno);
if (!new_bh) {
apfs_err(sb, "failed to map block for CoW (0x%llx)", new_bno);
err = -EIO;
goto fail;
}
memcpy(new_bh->b_data, bh->b_data, sb->s_blocksize);
/* Don't free the old copy if it's part of a snapshot */
if (!preserve)
/*
* Don't free the old copy of the object if it's part of a snapshot.
* Also increase the allocation count, except for the volume superblock
* which is never counted there.
*/
if (!preserve) {
err = apfs_free_queue_insert(sb, bh->b_blocknr, 1);
if (err)
apfs_err(sb, "free queue insertion failed for 0x%llx", (unsigned long long)bh->b_blocknr);
} else if ((type & APFS_OBJECT_TYPE_MASK) != APFS_OBJECT_TYPE_FS) {
vsb_raw = APFS_SB(sb)->s_vsb_raw;
apfs_assert_in_transaction(sb, &vsb_raw->apfs_o);
le64_add_cpu(&vsb_raw->apfs_fs_alloc_count, 1);
le64_add_cpu(&vsb_raw->apfs_total_blocks_alloced, 1);
}
brelse(bh);
bh = new_bh;
new_bh = NULL;
+116 -61
View File
@@ -24,16 +24,18 @@ static int apfs_create_superblock_snapshot(struct super_block *sb, u64 *bno)
int err;
err = apfs_spaceman_allocate_block(sb, bno, true /* backwards */);
if (err)
if (err) {
apfs_err(sb, "block allocation failed");
goto fail;
}
snap_bh = apfs_getblk(sb, *bno);
if (!snap_bh) {
apfs_err(sb, "failed to map block for volume snap (0x%llx)", *bno);
err = -EIO;
goto fail;
}
apfs_assert_in_transaction(sb, &vsb_raw->apfs_o);
le64_add_cpu(&vsb_raw->apfs_fs_alloc_count, 1);
curr_bh = sbi->s_vobject.o_bh;
memcpy(snap_bh->b_data, curr_bh->b_data, sb->s_blocksize);
@@ -69,7 +71,6 @@ static int apfs_create_snap_metadata_rec(struct inode *mntpoint, struct apfs_nod
struct apfs_sb_info *sbi = APFS_SB(sb);
struct apfs_superblock *vsb_raw = sbi->s_vsb_raw;
struct apfs_query *query = NULL;
struct apfs_key key = {0};
struct apfs_snap_metadata_key raw_key;
struct apfs_snap_metadata_val *raw_val = NULL;
int val_len;
@@ -77,23 +78,24 @@ static int apfs_create_snap_metadata_rec(struct inode *mntpoint, struct apfs_nod
u64 xid = APFS_NXI(sb)->nx_xid;
int err;
apfs_init_snap_metadata_key(xid, &key);
query = apfs_alloc_query(snap_root, NULL /* parent */);
if (!query) {
err = -ENOMEM;
goto fail;
}
query->key = &key;
apfs_init_snap_metadata_key(xid, &query->key);
query->flags |= APFS_QUERY_SNAP_META | APFS_QUERY_EXACT;
err = apfs_btree_query(sb, &query);
if (err == 0) {
apfs_err(sb, "record exists for xid 0x%llx", xid);
err = -EFSCORRUPTED;
goto fail;
}
if (err != -ENODATA)
if (err != -ENODATA) {
apfs_err(sb, "query failed for xid 0x%llx", xid);
goto fail;
}
apfs_key_set_hdr(APFS_TYPE_SNAP_METADATA, xid, &raw_key);
@@ -108,13 +110,18 @@ static int apfs_create_snap_metadata_rec(struct inode *mntpoint, struct apfs_nod
now = current_time(mntpoint);
raw_val->create_time = cpu_to_le64(timespec64_to_ns(&now));
raw_val->change_time = raw_val->create_time;
raw_val->inum = 0; /* TODO: what is this? */
raw_val->extentref_tree_type = vsb_raw->apfs_extentref_tree_type;
raw_val->flags = 0;
raw_val->name_len = cpu_to_le16(name_len + 1); /* Count the null byte */
strcpy(raw_val->name, name);
strscpy(raw_val->name, name, name_len + 1);
apfs_assert_in_transaction(sb, &vsb_raw->apfs_o);
raw_val->inum = vsb_raw->apfs_next_obj_id;
le64_add_cpu(&vsb_raw->apfs_next_obj_id, 1);
err = apfs_btree_insert(query, &raw_key, sizeof(raw_key), raw_val, val_len);
if (err)
apfs_err(sb, "insertion failed for xid 0x%llx", xid);
fail:
kfree(raw_val);
raw_val = NULL;
@@ -127,20 +134,17 @@ static int apfs_create_snap_name_rec(struct apfs_node *snap_root, const char *na
{
struct super_block *sb = snap_root->object.sb;
struct apfs_query *query = NULL;
struct apfs_key key = {0};
struct apfs_snap_name_key *raw_key = NULL;
struct apfs_snap_name_val raw_val;
int key_len;
int err;
apfs_init_snap_name_key(name, &key);
query = apfs_alloc_query(snap_root, NULL /* parent */);
if (!query) {
err = -ENOMEM;
goto fail;
}
query->key = &key;
apfs_init_snap_name_key(name, &query->key);
query->flags |= APFS_QUERY_SNAP_META | APFS_QUERY_EXACT;
err = apfs_btree_query(sb, &query);
@@ -150,8 +154,10 @@ static int apfs_create_snap_name_rec(struct apfs_node *snap_root, const char *na
err = -EEXIST;
goto fail;
}
if (err != -ENODATA)
if (err != -ENODATA) {
apfs_err(sb, "query failed (%s)", name);
goto fail;
}
key_len = sizeof(*raw_key) + name_len + 1;
raw_key = kzalloc(key_len, GFP_KERNEL);
@@ -161,11 +167,13 @@ static int apfs_create_snap_name_rec(struct apfs_node *snap_root, const char *na
}
apfs_key_set_hdr(APFS_TYPE_SNAP_NAME, APFS_SNAP_NAME_OBJ_ID, raw_key);
raw_key->name_len = cpu_to_le16(name_len + 1); /* Count the null byte */
strcpy(raw_key->name, name);
strscpy(raw_key->name, name, name_len + 1);
raw_val.snap_xid = cpu_to_le64(APFS_NXI(sb)->nx_xid);
err = apfs_btree_insert(query, raw_key, key_len, &raw_val, sizeof(raw_val));
if (err)
apfs_err(sb, "insertion failed (%s)", name);
fail:
kfree(raw_key);
raw_key = NULL;
@@ -174,30 +182,29 @@ fail:
return err;
}
static int apfs_create_snap_meta_records(struct inode *mntpoint, const char *name, u64 sblock_oid)
static int apfs_create_snap_meta_records(struct inode *mntpoint, const char *name, int name_len, u64 sblock_oid)
{
struct super_block *sb = mntpoint->i_sb;
struct apfs_superblock *vsb_raw = APFS_SB(sb)->s_vsb_raw;
struct apfs_node *snap_root = NULL;
size_t name_len;
int err;
snap_root = apfs_read_node(sb, le64_to_cpu(vsb_raw->apfs_snap_meta_tree_oid), APFS_OBJ_PHYSICAL, true /* write */);
if (IS_ERR(snap_root))
if (IS_ERR(snap_root)) {
apfs_err(sb, "failed to read snap meta root 0x%llx", le64_to_cpu(vsb_raw->apfs_snap_meta_tree_oid));
return PTR_ERR(snap_root);
}
apfs_assert_in_transaction(sb, &vsb_raw->apfs_o);
vsb_raw->apfs_snap_meta_tree_oid = cpu_to_le64(snap_root->object.oid);
name_len = strlen(name);
if (name_len > APFS_SNAP_MAX_NAMELEN) {
err = -EFSCORRUPTED;
err = apfs_create_snap_metadata_rec(mntpoint, snap_root, name, name_len, sblock_oid);
if (err) {
apfs_err(sb, "meta rec creation failed");
goto fail;
}
err = apfs_create_snap_metadata_rec(mntpoint, snap_root, name, name_len, sblock_oid);
if (err)
goto fail;
err = apfs_create_snap_name_rec(snap_root, name, name_len);
if (err)
apfs_err(sb, "name rec creation failed");
fail:
apfs_node_free(snap_root);
@@ -211,8 +218,10 @@ static int apfs_create_new_extentref_tree(struct super_block *sb)
int err;
err = apfs_make_empty_btree_root(sb, APFS_OBJECT_TYPE_BLOCKREFTREE, &oid);
if (err)
if (err) {
apfs_err(sb, "failed to make empty root");
return err;
}
apfs_assert_in_transaction(sb, &vsb_raw->apfs_o);
vsb_raw->apfs_extentref_tree_oid = cpu_to_le64(oid);
@@ -231,7 +240,6 @@ static int apfs_update_omap_snap_tree(struct super_block *sb, __le64 *oid_p)
struct apfs_nxsb_info *nxi = APFS_NXI(sb);
struct apfs_node *root = NULL;
u64 oid = le64_to_cpup(oid_p);
struct apfs_key key = {0};
struct apfs_query *query = NULL;
__le64 raw_key;
struct apfs_omap_snapshot raw_val = {0};
@@ -240,35 +248,42 @@ static int apfs_update_omap_snap_tree(struct super_block *sb, __le64 *oid_p)
/* An empty snapshots tree may not even have a root yet */
if (!oid) {
err = apfs_make_empty_btree_root(sb, APFS_OBJECT_TYPE_OMAP_SNAPSHOT, &oid);
if (err)
if (err) {
apfs_err(sb, "failed to make empty root");
return err;
}
}
root = apfs_read_node(sb, oid, APFS_OBJ_PHYSICAL, true /* write */);
if (IS_ERR(root))
if (IS_ERR(root)) {
apfs_err(sb, "failed to read omap snap root 0x%llx", oid);
return PTR_ERR(root);
}
oid = 0;
apfs_init_omap_snap_key(nxi->nx_xid, &key);
query = apfs_alloc_query(root, NULL /* parent */);
if (!query) {
err = -ENOMEM;
goto fail;
}
query->key = &key;
apfs_init_omap_snap_key(nxi->nx_xid, &query->key);
query->flags = APFS_QUERY_OMAP_SNAP | APFS_QUERY_EXACT;
err = apfs_btree_query(sb, &query);
if (err == 0) {
apfs_err(sb, "record exists for xid 0x%llx", nxi->nx_xid);
err = -EFSCORRUPTED;
goto fail;
}
if (err != -ENODATA)
if (err != -ENODATA) {
apfs_err(sb, "query failed for xid 0x%llx", nxi->nx_xid);
goto fail;
}
raw_key = cpu_to_le64(nxi->nx_xid);
err = apfs_btree_insert(query, &raw_key, sizeof(raw_key), &raw_val, sizeof(raw_val));
if (err)
apfs_err(sb, "insertion failed for xid 0x%llx", nxi->nx_xid);
*oid_p = cpu_to_le64(root->object.block_nr);
fail:
@@ -298,14 +313,18 @@ static int apfs_update_omap_snapshots(struct super_block *sb)
omap_blk = le64_to_cpu(vsb_raw->apfs_omap_oid);
bh = apfs_read_object_block(sb, omap_blk, true /* write */, false /* preserve */);
if (IS_ERR(bh))
if (IS_ERR(bh)) {
apfs_err(sb, "CoW failed for bno 0x%llx", omap_blk);
return PTR_ERR(bh);
}
omap = (struct apfs_omap_phys *)bh->b_data;
apfs_assert_in_transaction(sb, &omap->om_o);
le32_add_cpu(&omap->om_snap_count, 1);
omap->om_most_recent_snap = cpu_to_le64(xid);
err = apfs_update_omap_snap_tree(sb, &omap->om_snapshot_tree_oid);
if (err)
apfs_err(sb, "omap snap tree update failed");
omap = NULL;
brelse(bh);
@@ -320,7 +339,7 @@ static int apfs_update_omap_snapshots(struct super_block *sb)
*
* Returns 0 on success, or a negative error code in case of failure.
*/
static int apfs_do_ioc_take_snapshot(struct inode *mntpoint, const char *name)
static int apfs_do_ioc_take_snapshot(struct inode *mntpoint, const char *name, int name_len)
{
struct super_block *sb = mntpoint->i_sb;
struct apfs_sb_info *sbi = APFS_SB(sb);
@@ -341,24 +360,34 @@ static int apfs_do_ioc_take_snapshot(struct inode *mntpoint, const char *name)
* changes to the layout after the snapshot is set up.
*/
err = apfs_transaction_flush_all_inodes(sb);
if (err)
return err;
if (err) {
apfs_err(sb, "failed to flush all inodes");
goto fail;
}
err = apfs_create_superblock_snapshot(sb, &sblock_oid);
if (err)
return err;
err = apfs_create_snap_meta_records(mntpoint, name, sblock_oid);
if (err)
if (err) {
apfs_err(sb, "failed to snapshot superblock");
goto fail;
}
err = apfs_create_snap_meta_records(mntpoint, name, name_len, sblock_oid);
if (err) {
apfs_err(sb, "failed to create snap meta records");
goto fail;
}
err = apfs_create_new_extentref_tree(sb);
if (err)
if (err) {
apfs_err(sb, "failed to create new extref tree");
goto fail;
}
err = apfs_update_omap_snapshots(sb);
if (err)
if (err) {
apfs_err(sb, "failed to update omap snapshots");
goto fail;
}
/*
* The official reference allows old implementations to ignore extended
@@ -395,6 +424,7 @@ int apfs_ioc_take_snapshot(struct file *file, void __user *user_arg)
struct inode *inode = file_inode(file);
struct super_block *sb = inode->i_sb;
struct apfs_ioctl_snap_name *arg = NULL;
size_t name_len;
int err;
if (apfs_ino(inode) != APFS_ROOT_DIR_INO_NUM) {
@@ -404,8 +434,10 @@ int apfs_ioc_take_snapshot(struct file *file, void __user *user_arg)
#if LINUX_VERSION_CODE < KERNEL_VERSION(5, 12, 0)
if (!inode_owner_or_capable(inode))
#else
#elif LINUX_VERSION_CODE < KERNEL_VERSION(6, 3, 0)
if (!inode_owner_or_capable(&init_user_ns, inode))
#else
if (!inode_owner_or_capable(&nop_mnt_idmap, inode))
#endif
return -EPERM;
@@ -424,7 +456,14 @@ int apfs_ioc_take_snapshot(struct file *file, void __user *user_arg)
goto fail;
}
err = apfs_do_ioc_take_snapshot(inode, arg->name);
name_len = strnlen(arg->name, sizeof(arg->name));
if (name_len == sizeof(arg->name)) {
apfs_warn(sb, "snapshot name is too long (%d)", (int)name_len);
err = -EINVAL;
goto fail;
}
err = apfs_do_ioc_take_snapshot(inode, arg->name, name_len);
fail:
kfree(arg);
arg = NULL;
@@ -437,8 +476,10 @@ static int apfs_snap_xid_from_query(struct apfs_query *query, u64 *xid)
char *raw = query->node->object.data;
__le64 *val = NULL;
if (query->len != sizeof(*val))
if (query->len != sizeof(*val)) {
apfs_err(query->node->object.sb, "bad value length (%d)", query->len);
return -EFSCORRUPTED;
}
val = (__le64 *)(raw + query->off);
*xid = le64_to_cpup(val);
@@ -449,22 +490,24 @@ static int apfs_snapshot_name_to_xid(struct apfs_node *snap_root, const char *na
{
struct super_block *sb = snap_root->object.sb;
struct apfs_query *query = NULL;
struct apfs_key key = {0};
int err;
apfs_init_snap_name_key(name, &key);
query = apfs_alloc_query(snap_root, NULL /* parent */);
if (!query)
return -ENOMEM;
query->key = &key;
apfs_init_snap_name_key(name, &query->key);
query->flags |= APFS_QUERY_SNAP_META | APFS_QUERY_EXACT;
err = apfs_btree_query(sb, &query);
if (err)
if (err) {
if (err != -ENODATA)
apfs_err(sb, "query failed (%s)", name);
goto fail;
}
err = apfs_snap_xid_from_query(query, xid);
if (err)
apfs_err(sb, "bad snap name record (%s)", name);
fail:
apfs_free_query(query);
query = NULL;
@@ -476,8 +519,10 @@ static int apfs_snap_sblock_from_query(struct apfs_query *query, u64 *sblock_oid
char *raw = query->node->object.data;
struct apfs_snap_metadata_val *val = NULL;
if (query->len < sizeof(*val))
if (query->len < sizeof(*val)) {
apfs_err(query->node->object.sb, "bad value length (%d)", query->len);
return -EFSCORRUPTED;
}
val = (struct apfs_snap_metadata_val *)(raw + query->off);
*sblock_oid = le64_to_cpu(val->sblock_oid);
@@ -488,22 +533,23 @@ static int apfs_snapshot_xid_to_sblock(struct apfs_node *snap_root, u64 xid, u64
{
struct super_block *sb = snap_root->object.sb;
struct apfs_query *query = NULL;
struct apfs_key key = {0};
int err;
apfs_init_snap_metadata_key(xid, &key);
query = apfs_alloc_query(snap_root, NULL /* parent */);
if (!query)
return -ENOMEM;
query->key = &key;
apfs_init_snap_metadata_key(xid, &query->key);
query->flags |= APFS_QUERY_SNAP_META | APFS_QUERY_EXACT;
err = apfs_btree_query(sb, &query);
if (err)
if (err) {
apfs_err(sb, "query failed for xid 0x%llx", xid);
goto fail;
}
err = apfs_snap_sblock_from_query(query, sblock_oid);
if (err)
apfs_err(sb, "bad snap meta record for xid 0x%llx", xid);
fail:
apfs_free_query(query);
query = NULL;
@@ -531,17 +577,24 @@ int apfs_switch_to_snapshot(struct super_block *sb)
ASSERT(sb->s_flags & SB_RDONLY);
name = sbi->s_snap_name;
if (strlen(name) > APFS_SNAP_MAX_NAMELEN)
if (strlen(name) > APFS_SNAP_MAX_NAMELEN) {
apfs_warn(sb, "snapshot name is too long");
return -EINVAL;
}
snap_root = apfs_read_node(sb, le64_to_cpu(vsb_raw->apfs_snap_meta_tree_oid), APFS_OBJ_PHYSICAL, false /* write */);
if (IS_ERR(snap_root))
if (IS_ERR(snap_root)) {
apfs_err(sb, "failed to read snap meta root 0x%llx", le64_to_cpu(vsb_raw->apfs_snap_meta_tree_oid));
return PTR_ERR(snap_root);
}
vsb_raw = NULL;
err = apfs_snapshot_name_to_xid(snap_root, name, &xid);
if (err)
if (err) {
if (err == -ENODATA)
apfs_info(sb, "no snapshot under that name (%s)", name);
goto fail;
}
sbi->s_snap_xid = xid;
err = apfs_snapshot_xid_to_sblock(snap_root, xid, &sblock_oid);
@@ -550,6 +603,8 @@ int apfs_switch_to_snapshot(struct super_block *sb)
apfs_unmap_volume_super(sb);
err = apfs_map_volume_super_bno(sb, sblock_oid, nxi->nx_flags & APFS_CHECK_NODES);
if (err)
apfs_err(sb, "failed to map volume block 0x%llx", sblock_oid);
fail:
apfs_node_free(snap_root);
+362 -95
View File
File diff suppressed because it is too large. Load diff
Loaded 20 of 24 files, more files were not shown because too many files have changed in this diff. Show more