Skip to content

Commit

Permalink
macOS: Add macOS support
Browse files Browse the repository at this point in the history
Add all files required for the macOS port. Add new cmd/os/ for tools
which are only expected to be used on macOS.

This has support for all macOS version up to Catalina. (Not BigSur).

Signed-off-by: Jorgen Lundman <lundman@lundman.net>

macOS: big uio change over.

Make uio be internal (ZFS) struct, possibly referring to supplied (XNU)
uio from kernel. This means zio_crypto.c can now be identical to upstream.

Update for draid, and other changes

macOS: Use SET_ERROR with uiomove. [squash]

macOS: they went and added vdev_draid

macOS: compile fixes from rebase

macOS: oh cstyle, how you vex me so

macOS: They added new methods - squash

macOS: arc_register_hotplug for userland too

Upstream: avoid warning

zio_crypt.c:1302:3: warning: passing 'const struct iovec *' to parameter of
      type 'void *' discards qualifiers
      [-Wincompatible-pointer-types-discards-qualifiers]
                kmem_free(uio->uio_iov, uio->uio_iovcnt * sizeof (iovec_t));
                ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

macOS: Update zfs_acl.c to latest

This includes commits like:

65c7cc4
1b376d1
cfdc432
716b53d
a741b38
485b50b

macOS: struct vdev changes

macOS: cstyle, how you vex me [squash]

Upstream: booo Werror booo

Upstream: squash baby

Not defined gives warnings.

Upstream: Include all Makefiles

Signed-off-by: Jorgen Lundman <lundman@lundman.net>

double draid!

macOS: large commit

macOS: Use APPLE approved kmem_alloc()

macOS: large commit
WIP: remove reliance on zfs.exports

The memory-pressure has been nerfed, and will not run well until we
can find other solutions.

The kext symbol lookup we can live without, used only for debug and
panic. Use lldb to lookup symbols.

leaner! leanerr!

remove zfs.export dependency cont.

export reduction cont. cont.

Corrective tweaks for building

Correct vnode_iocount()

Cleanup pipe wrap code, use pthreads, handle multiple streams

latest pipe send with threads

sort of works, but bad timing can be deadlock

macOS: work out corner case starvation issue in cv_wait_sig()

Fix -C in zfs send/recv

cv_wait_sig squash

Also wrap zfs send resume

Implement VOP_LOOKUP for snowflake Finder

Don't change date when setting size.

Seems to be a weird required with linux, so model after freebsd
version

macOS: correct xattr checks for uio

Fix a noisy source of misleading-indentation warnings

Fix "make install" ln -s failures

Fix a noisy source of misleading-indentation warnings

Fix "make install" ln -s failures

fix ASSERT: don't try to peer into opaque vp structure

Import non-panicking ASSERT from old spl/include/sys/debug.h

Guard with MACOS_ASSERT_SHOULD_PANIC which will do what
Linux and FreeBSD do: redefine ASSERTs as VERIFYs.  The
panic report line will say VERIFY obscuring the problem,
and a system panic is harsher (and more dangerous) on
MacOS than a zfs-module panic on Linux.

ASSERTions: declare assfail in debug.h

Build and link spl-debug.c

Eliminate spurious "off" variable, use position+offset range

Make sure we hold the correct range to avoid panic in
dmu_tx_dirty_buf (macro DMU_TX_DIRTY_BUF defined with --enable-debug).

zvol_log_write the range we have written, not the future range

silence very noisy and dubious ASSERT

macOS: M1 fixes for arm64.

sysctl needs to use OID2
Allocs needs to be IOMalloc_aligned
Initial spl-vmem memory area needs to be aligned to 16KB
No cpu_number() for arm64.

macOS: change zvol locking, add zvol symlinks

macOS: Return error on UF_COMPRESSED

This means bsdtar will be rather noisy, but we prefer noise over corrupt
files (all files would be 0-sized).

usr/bin/zprint: Failed to set file flags~
-rwxr-xr-x  1 root  wheel  47024 Mar 17  2020 /Volumes/BOOM/usr/bin/zprint

usr/bin/zprint: Failed to set file flags
-rwxr-xr-x  1 root  wheel  47024 Mar 17  2020 /Volumes/BOOM/usr/bin/zprint

Actually include zedlet for zvols

macOS: Fix Finder crash on quickview, SMB error codes

xattr=sa would return negative returncode, hangover from ZOL code.
Only set size if passed a ptr.
Convert negative errors codes back to normal.
Add  LIBTOOLFLAGS for macports toolchain

This will replace PR#23

macOS zpool import fixes

The new codebase uses a mixture of thread pools and lio_listio async io, and
on macOS there are low aio limits, and when those are reached lio_listio()
returns EAGAIN when probing several prospective leaf vdevs concurrently,
looking for labels. We should not abandon probing a vdev in this case, and can
usually recover by trying again after a short delay. (We continue to treat
other errnos as unrecoverable for that vdev, and only try to recover from
EAGAIN a few times).

Additionally, take logic from old o3x and don't probe a variety of devices
commonly found in /dev/XXX as they either produce side-effects or are simply
wasted effort.

Finally, add a trailing / that FreeBSD and Linux both have.

listxattr may not expose com.apple.system  xattr=sa

We need to ask IOMallocAligned for the enclosing POW2

vmem_create() arenas want at least natural alignment for
the spans they import, and will panic if they don't get it.

For sub-PAGESIZE calls to osif_malloc, align on PAGESIZE.
Otherwise align on the enclosing power of two for any
osif_malloc allocation up to 2^32.   Anything that asks
osif_malloc() for more than that is almost certainly a
bug, but we can try aligning on PAGESIZE anyway, rather
than extend the enclosing-power-of-two device to handle
64-bit allocations.

Simplify the creation of bucket arenas, and adjust their
quanta.  This results in handing back considerably
more (and smaller) chunks of memory to osif_free if there
is pressure, and reduces waits in xnu_alloc_throttled(),
so is a performance win for a busy memory-constrained
system.

Finally, uncomment some valid code that might be used by future
callers of vmem_xcreate().

use vmem_xalloc to match the vmem_xfree of initial dynamic alloc

vmem_alloc() breaks the initial large vmem_add()
allocation into smaller chunks in an effort to have a
large number vmem segments in the arena.  This arena does
not benefit from that.  Additionaly, in vmem_fini() we
call vmem_xfree() to return the initial allocation because
it is done after almost everything has been pulled down.
Unfortunately vmem_xfree() returns the entire initial
allocation as a single span.  IOFree() checks a variable
maintained by the IOMalloc* allocators which tracks the
largest allocation made so far, and will panic when (as it
almost always is the case) the initial large span is
handed to it.  This usually manifests as a panic or hang
on kext unload, or a hang at reboot.

Consequently, we will now use vmem_xalloc() for this
initial allocation; vmem_xalloc() also lets us explicitly
specify the natural alignement we want for it.

zfs_rename SA_ADDTIME may grow SA

Avoid:

zfs`dmu_tx_dirty_buf(tx=0xffffff8890a56e40, db=0xffffff8890ae8cd0) at dmu_tx.c:674:2

-> 674 		panic("dirtying dbuf obj=%llx lvl=%u blkid=%llx but not tx_held\n",
   675 		    (u_longlong_t)db->db.db_object, db->db_level,
   676 		    (u_longlong_t)db->db_blkid);

zfs diff also needs to be wrapped.

Replace call to pipe() with a couple of open(mkfifo) instead.

Upstream: cstyle zfs_fm.c

macOS: cstyle baby

IOMallocAligned() should call IOFreeAligned()

macOS: zpool_disable_volumes v1

When exporting, also kick mounted zvols offline

macOS: zpool_disable_volumes v2

When exporting zvols, check IOReg for the BSDName, instead of using
readlink on the ZVOL symlinks.

Also check if apfs has made any synthesized disks, and ask them to
unmount first.

./scripts/cmd-macos.sh zpool export BOOM
Exporting 'BOOM/volume'
... asking apfs to eject 'disk5'
Unmount of all volumes on disk5 was successful
... asking apfs to eject 'disk5s1'
Unmount of all volumes on disk5 was successful
... asking ZVOL to export 'disk4'
Unmount of all volumes on disk4 was successful
zpool_disable_volume: exit

macOS: Add libdiskmgt and call inuse checks

macOS: compile fixes from rebase

macOS: oh cstyle, how you vex me so

macOS: They added new methods - squash

macOS: arc_register_hotplug for userland too

macOS: minor tweaks for libdiskmgt

macOS: getxattr size==0 is to lookup size

Also skip the ENOENT return for "zero" finderinfo, as we do not
skip over them in listxattr.

macOS:  10.9 compile fixes

macOS: go to rc2

macOS: kstat string handling should copyin.

cstyle baby

macOS: Initialise ALL quota types

projectid, userobj, groupobj and projectobj, quotas were missed.

macOS: error check sysctl for older macOS

Wooo cstyle, \o/

Make arc sysctl tunables work (#27)

* use an IOMemAligned for a PAGE_SIZE allocation

* we should call arc_kstat_update_osx()

Changing kstat.zfs.darwin.tunable.zfs_arc_min doesn't do
anything becasue arc_kstat_update_osx() was removed at the
same time the (obsoleted by upstream) arc_kstat_update()
was removed from zfs_kstat_osx.c.   Put it back.

* when we sysctl arc tunables, call arc_tuning_update()

* rely on upstream's sanity checking

Simplification which also avoids spurious CMN_WARN
messages caused by setting the arcstat variables here,
when upstream's arc_tuning_update() checks that they
differ from the tunable variables.

* add tunable zfs_arc_sys_free and fix zfs_arc_lotsfree_percent

both are in upstream's arc_tuning_update()

zfs_arc_sys_free controls the amount of memory that ARC
will leave free, which is roughly what lundman wants for
putting some sort of cap on memory use.

* cstyle

macOS: set UIO direction, to receive xattr from XNU

macOS: ensure uio is zeroed

in case XNU uio is NULL.

Fix zfs_vnop_getxattr (openzfs#28)

"xattr -l <file>" would return inconsistent garbage,
especially from non-com.apple.FinderInfo xattrs.

The UIO_WRITE was a 0 (UIO_READ) in the previous commit, change it.

Also turn kmem_alloc -> kmem_zalloc in zfs_vnops_osx.c,
for cheap extra safety.

launch `zpool import` through launchd in the startup script (#26)

Signed-off-by: Guillaume Lessard <glessard@tffenterprises.com>

cstyle

macOS: correct dataset_kstat_ logic and kstat leak.

dataset_kstat_create() will allocate a string and set it before calling
kstat_create() - so we can not set strings to NULL. Likewise, we
can not bulk free strings on unload, we have to rely on the
caller of kstat to do so. (Which is proper).

Add calls to dataset_kstat for datasets and zvol.

kstat.zfs/BOOM.dataset.objset-0x36.dataset_name: BOOM
kstat.zfs/BOOM.dataset.objset-0x36.writes: 0
kstat.zfs/BOOM.dataset.objset-0x36.nwritten: 0
kstat.zfs/BOOM.dataset.objset-0x36.reads: 11
kstat.zfs/BOOM.dataset.objset-0x36.nread: 10810
kstat.zfs/BOOM.dataset.objset-0x36.nunlinks: 0
kstat.zfs/BOOM.dataset.objset-0x36.nunlinked: 0

macOS: remove no previous prototype for function

macOS: correct openat wrapper

build fixes re TargetConditionals.h (openzfs#30)

AvailabilityMacros.h needs TargetConditionals.h defintions
in picky modern compilers.   Add them to sysmacros.h,
and fix a missing sysmacros.h include.

Memory fixes on macOS_pure (openzfs#31)

* Improve memory handling on macOS

* remove obsolete/unused zfs_file_data/zfs_metadata caching

* In the new code base, we use upstream's zio.c without
modification, and so the special zio caching code became
entirely vestigial, and likely counterproductive.

* and make busy ABD better behaved on busy macOS box

Post-ABD we no longer gained much benefit in the old code
base from the complicated special handling for the caches
created in zio.c.

As there's only really one size of ABD allocation, we do
not need a qcache layer as in 1.9.  Instead use an arena
with VMC_NO_QCACHE set to ask for for 256k chunks.

* don't reap extra caches in arc_kmem_reap_now()

KMF_LITE in DEBUG build is OK

* build fixes re TargetConditionals.h

AvailabilityMacros.h needs TargetConditionals.h defintions
in picky modern compilers.   Add them to sysmacros.h,
and fix a missing sysmacros.h include.

Use barrier synchronization and IO Priority in ldi_iokit.cpp (openzfs#33)

* other minor changes in vdev_disk

Thread and taskq fixing (openzfs#32)

Highlights:

* thread names for spindump
* some taskq_d is safe and useful
* reduce thread priorities
* use througput & latency QOS
* TIMESHARE scheduling
* passivate some IO

* Pull in relevant changes from old taskq_fixing branch

1.9 experimentation pulled into 2.x

* add throttle_set_thread_io_policy to zfs.exports

* selectively re-enable TASKQ_DYNAMIC

also drop wr_iss zio taskqs even further in priority (cf freebsd)

* reduce zvol taskq priority

* make system_taskq dynamic

* experimentally allow three more taskq_d

* lower thread prorities overall

on an M1 with no zfs whatsoever, the highest
priority threads are in the mid 90s, with
most kernel threads at priority 81 (basepri).

with so many maxclsyspri threads in zfs, we owuld starve out
important things like vm_pageout_scan (pri 91),
sched_maintenance_thread (pri 95), and numerous others.

moreover, ifnet_start_{interfaces} are all priority 82.

we should drop minclsyspri below 81, have defclsyspri
at no more than 81, and make sure we have few threads above 89.

* some tidying up of lowering of priority

Thread and taskq fixing

* fix old code pulled into spa.c, and further lower priorities

* Thread and taskq fixing

drop xnu priorities by one

update a comment block

set USER_INITIATED throughput QOS on TIMESHARE taskq threads

don't boost taskq threads accidentally

don't let taskq threads be pri==81

don't let o3x threads have importance > 0

apply xnu thread policies to taskq_d threads too

assuming this works, it calls out for DRY refactoring
with the other two flavours, that operate on current_thread().

simplify in spa.c

make practically all the taskqs TIMESHARE

Revert "apply xnu thread policies to taskq_d threads too"

Panic in VM

This reverts commit 39f93be.

Revert "Revert "apply xnu thread policies to taskq_d threads too""

I see what happened now.

This reverts commit 75619f0.

adjust thread not the magic number

refactor setting thread qos

make DRY refactor rebuild

this includes userland TASKQ_REALLY_DYNAMIC fixes

fix typo

set thread names for spindump visibility

cstyle

Upstream: Add --enable-macos-impure to autoconf

Controls -DMACOS_IMPURE

Signed-off-by: Jorgen lundman <lundman@lundman.net>

macOS: Add --enable-macos-impure switch to missing calls.

Call the wrapped spl_throttle_set_thread_io_policy

Add spl_throttle_set_thread_io_policy to headers

macOS: vdev_file should use file_taskq

Also cleanup spl-taskq to have taskq_wait_outstanding() in
preparation for one day implementing it.

Change alloc to zalloc in zfs_ctldir.c

Call wrap_zstd_init() and wrap_zstd_fini() (openzfs#34)

macOS: change both alloc to zalloc

macOS: mutex_tryenter can be used while holding

zstd uses mutex_tryenter() to check if it already is holding
the mutex. Can't find any implementations that object to it, so
changing our spl-mutex.c

Tag zfs-2.0.0rc4

macOS: return error from uiomove instead of panic

macOS: Skip known /dev entry which hangs

macOS: Give better error msg when features are needed for crypto

Using 1.9.4 crypto dataset now require userobj and projectquota.
Alert the user to activate said features to mount crypt dataset.

There is no going back to 1.9.4 after features are enabled.

macOS: Revert to pread() over AIO due to platform issues.

We see waves of EAGAIN errors from lio_listio() on BigSur
(but not Catalina) which could stem from recent changes to AIO
in XNU. For now, we will go with the classic read label.

Re-introduce a purified memory pressure handling mechanism (openzfs#35)

* Introduce pure pressure-detecting-and-reacting system

* "pure" -- no zfs.exports requirement

* plumb in mach_vm_pressure_level_monitor() and
mach_vm_pressure_monitor() calls to maintain reduced set
of inputs into previous signalling into (increasingly
shared with upstream) arc growth or shrinking policy

* introduce mach_vm_pressure kstats which can be
compared with userland-only sysctls:

kstat.spl.misc.spl_misc.spl_vm_pages_reclaimed: 0
kstat.spl.misc.spl_misc.spl_vm_pages_wanted: 0
kstat.spl.misc.spl_misc.spl_vm_pressure_level: 0
vm.page_free_wanted: 0
vm.page_free_count: 25,545
vm.page_speculative_count: 148,572

* and a start on tidying and obsolete code elimination

* make arc_default_max() much bigger

Optional: can be squashed into main pressure commit,
or omitted.

Users can use zsysctl.conf or manual setting
of kstat.zfs.darwin.tunable.zfs_arc_max to override
whichever default is chosen (this one, or the one it
replaces).

Allmem is already deflated during initialization, so
this patch raises the un-sysctled ARC maximum from
1/6 to 1/2 of physmem.

* handle (vmem) abd_cache fragmentation after arc shrink

When arc shrinks due to a significant pressure event, the
abd_chunk kmem cache will free slabs back to the vmem
abd_cache, and this memory can be several gigabytes.

Unfortunately multi-threaded concurrent kmem_cache
allocation in the first place, and a priori unpredicatble
arc object lifetimes means that abds held by arc objects
may be scattered across multiple slabs, with different
objects interleaved within slabs.  Thus after a moderate
free, the vmem cache can be fragmented and this is seen
by (sysctl) kstat.vmem.vmem.abd_cache.mem_inuse being much
smaller than (sysctl)
kstat.vmem.vmem.abd_cache.mem_import, the latter of which
may even be stuck at approximately the same value as
before the arc free and kmem_cache reap.

When there is a large difference between import and inuse,
we set arc_no_grow in hopes that ongoing arc activity will
defragment organically.

This works better with more arc read/write activity after
the free, and almost not at all if after the free there is
almost no activity.

We also add BESTFIT policy to abd_arena experimentally

BESTFIT: look harder to place an abd chunk in a slab
         rather than place in the first slot that is
	 definitely large enough

which breaks the vmem constant-time allocation guarantee,
although that is less important for this particular vmem
arena because of the strong modality of allocations from
the abd_chunk cache (its only client).

Additionally reduce the abd_cache arena import size to
128k from 256k; the increase in allocation and free
traffic between it and the heap is small compared to the
gain under this new anti-fragmentation scheme.

* some additional tidying in arc_os.c

Tag macos-2.0.0-rc5

abd_cache fragmentation mitigation (openzfs#36)

* printf->dprintf HFS_GET_BOOT_INFO

periodically there will be huge numbers of these printfs,
and they are not really useful except when debugging
vnops.

* Mitigate fragmentation in vmem.abd_cache

In macOS_pure the abd_chunk kmem cache is parented to the
abd_cache vmem arena to avoid sometimes-heavy ARC
allocation and free stress on the main kmem cache, and
because abd_chunk has such a strongly modal page-sized
allocation size.  Additionally, abd_chunk allocations and
frees come in gangs, often with high multi-thread
concurrency.  It is that latter property which is the
primary source of arena fragmentation, and it will affect any
vmem arena directly underneath the abd_chunk kmem cache.

Because we have a vmeme parent solely for abd_chunk, we
can monitor that parent for various patterns and react to
them.

This patch monitors the difference between the variables
exported as kstat.vmem.vmem.abd_cache.mem_inuse and
kstat.vmem.vmem.abd_cache.mem_import, watching for a large
gap between the two, which can arise after an ARC shrink
returns many slabs from the arc_chunk kmem cache to the
abd_cache arena, as vmem segments still contain slabs
which hold still-alive abds.

When there is a significant gap, we turn on arc_no_grow
and hope that organic ARC activity reduces the gap.  If
after several minutes this is not the case, a small
arc_reduce_target_size() is applied.

In comparison with previous behaviour, ARC equilibrium
sizes will tend slightly -- but not neormously -- lower
because the arc target size reduction is made fairly
frequently.  However, this is offset by the benefit of
less *long-term* abd_cache fragmentation, and less
complete collapses of ARC in the face of system memory
pressure (since less is "stuck" in vmem).  ARC
consequently will stay at its equilibrium more often than
near its minimum.  This is demonstrated by a generally
lower overall total held memory
(kstat.spl.misc.spl_misc.os_mem_alloc) except on systems
with essentially no memory pressure, or systems which have
been sysctl-tuned for different behaviour.

macOS: Additional 10.9 fixes that missed the boat

Tidying nvram zfs_boot=pool (openzfs#37)

If zfs_boot is set we run a long-lived
zfs_boot_import_thread, which can stay running until the
kernel module is running _fini() functions at unload or
shutdown.

This patch dispatches it on a zfs_boot() taskq, to avoid
causing a hang at the taskq_wait_outstanding(system_taskq,
0) in zvol.c's zvol_create_minors_recursive(), which would
prevent pool imports finishing if the pool contained
zvols.  (Symptoms: "zpool import" does not exit for any
pool, system does not see any zvols).

This exposed a long-term race condition in our
zfs_boot.cpp: the notifier can cause the
mutex_enter(&pools->lock) in zfs_boot_probe_media to be
reached before the mutex_enter() after the notifier was
created.   The use of the system_taskq was masking that,
by quietly imposing a serialization choke.

Moving the mutex and cv initialization earlier -- in
particular before the notifier is created -- eliminates
the race.

Further tidying in zfs_boot.cpp, including some
cstyling, switching to _Atomic instead of volatile.
Volatile is for effectively random reads; _Atomic is for
when we want many readers to have a consistent view after
the variable is written.

Finally, we need TargetConditionals.h in front of
AvailabilityMacros.h in order to build.

Add includes to build on Big Sur with macports-clang-11  (openzfs#38)

* TargetConditionals.h before all AvailabilityMacros.h

* add several TargetConditionals.h and AvaialbilityMacros.h

Satisfy picky macports-clang-11 toolchain on Big Sur.

macOS: clean up large build, indicate errors. Fix debug

macOS: Retire MNTTYPE_ZFS_SUBTYPE lookup zfs in iokit

macOS: rename net.lundman. -> org.openzfsonosx.

macOS: Tag va_mode for upstream ASSERTS

XNU sets va_type = VDIR, but does not bother with va_mode. However
ZFS checks to confirm S_ISDIR is set in mkdir.

macOS: Fix zfs_ioc_osx_proxy_dataset for datasets

It was defined as a _pool() ioctl. While we are here changing things
change it into a new-style ioctl instead.

This should fix non-root datasets mounting as a proxy (devdisk=on).

cstyle

macOS: setxattr debug prints left in

macOS: don't create DYNAMIC with _ent taskq

macOS: Also uninstall new /usr/local/zfs before install

macos-2.0.0-rc6

macOS: strcmp deprecated after macOS 11

macOS: pkg needs to notarize at the end

macOS: strdup strings in getmntent

mirrored on FreeBSD.

macOS: remove debug print

macOS: unload zfs, not openzfs

macOS: actually include the volume icon file as well

also update to PR

macOS: prefer disk over rdisk

macOS: devdisk=off mimic=on needs to check for dataset

Datasets with devdisks=on will be in ioreg, with it off and mimic=on
then it needs to handle:
BOOM/fs1                        /Volumes/BOOM/fs1

by testing if "BOOM/fs1" is a valid dataset.

fixifx

macOS: doubled up "int rc" losing returncode

Causing misleading messages

macOS: zfsctl was sending from IDs

macOS: let zfs mount as user succeed

If the "mkdir" can succeed (home dir etc, as opposed to /Volumes)
then let the mount be able to happen.

macOS: Attempt to implement taskq_dispatch_delay()

frequently used with taskq_cancel_id() to stop taskq from
calling `func()` before the timeout expires.

Currently implemented by the taskq sleeping in cv_timedwait()
until timeout expires, or it is signalled by taskq_cancel_id().

Seems a little undesirable, could we build an ordered list
of delayed taskqs, and only place them to run once timeout has
expired, leaving the taskq available to work instead of delaying.

macOS: Separate unmount and proxy_remove

When proxy_remove is called at the tail end of unmount, we get the
alert about "ejecting before disconnecting device". To mirror the
proxy create, we make it a separate ioctl, and issue it after
unmount completes.

macOS: explicitly call setsize with O_TRUNC

It appears O_TRUNC does nothing, like the goggles.

macOS: Add O_APPEND to zfs_file_t

It is currently not used, but since it was written for a test case,
we might as well keep it.

macOS: Pass fd_offset between kernel and userland.

macOS: Missing return in non-void function

macOS: finally fix taskq_dispatch_delay()

you find a bug, you own the bug.

macOS: add missing kstats

macOS: restore the default system_delay_taskq

macOS: dont call taskq_wait in taskq_cancel

macOS: fix taskq_cancel_id()

We need to make sure the taskq has finished before returning in
taskq_cancel_id(), so that the taskq doesn't get a chance to run
after.

macOS: correct 'hz' to 100.

sysctl kern.clockrate: 100

sleeping for 1 second. bolt: 681571
sleep() 35 bolt: 681672: diff 101

'hz' is definitely 100.

macOS: implement taskq_delay_dispatch()

Implement delayed taskq by adding them to a list, sorted by wake-up time,
and a dispatcher thread which sleeps until the soonest taskq is due.

taskq_cancel_id() will remove task from list if present.

macOS: ensure to use 1024 version of struct statfs

and avoid coredump if passed zhp == NULL.

macOS: fix memory leak in xattr_list

macOS: must define D__DARWIN_64_BIT_INO_T for working getfsstat

getmntany: don't set _DARWIN_FEATURE_64_BIT_INODE

This is automatically set by default in userland
if the deployment target is > 10.5

macOS: Fix watchdog unload and delay()

macOS: improve handling of invariant disks

Don't prepend /dev to all paths not starting with
/dev as InvariantDisks places its symlinks in
/var/run/disk/by-* not /dev/disk/by-*.

Also, merge in some tweaks from Linux's
zpool_vdev_os.c such as only using O_EXCL with
spares.

macOS: remove zfs_unmount_006_pos from large.

Results in KILLED.

Tag macos-2.0.0rc7

macOS: If we don't set SOURCES it makes up zfs.c from nowhere

macOS: remove warning

macOS: compile fixes after rebase

macOS: connect SEEK_HOLE SEEK_DATA to ioctl

macOS: Only call vnode_specrdev() when valid

macOS: Use VNODE_RELOAD in iterate

in the hopes of avoiding ZFS call back in VNOP_INACTIVE

macOS: zfs_kmod_fini() calls taskq_cancel_id()

so we must unload system_taskq_fini() after the call to zfs_kmod_fini()

macOS: shellcheck error

macOS: Setting landmines cause panic on M1

  "panicString" : "panic(cpu 1 caller 0xfffffe001db72dc8): Break 0xC470 instruction exception from kernel. Ptrauth failure with IA key resulted in 0x2000000000000001 at pc 0xfffffe001c630880, lr 0x8afcfe001c630864 (saved state: 0xfffffe309386b180)

macOS: vget should only lookup direct IDs

macOS: rootzp left z_projid uninitialised

Causing z_projid to have "0xBADDCAFEBADDCAFE" initially, and
zfs_link() to return EXDEV due to differenting z_projid, presenting
the user with "Cross-device link".

Would only happen after loading kext, on the root znode.

macOS: Update installer rtf

macOS: update and correct the kext_version

macOS: Update copyright, fix url and versions

macOS ARC memory improvements and old code removal

macOS_pure "purification" in spl-[kv]mem coupled with the
new dynamics of trying to contain the split between inuse
and allocated in the ABD vmem arena produce less
memory-greed, so we don't have to do as much policing of
memory consumption, and lets us rely on some more
common/cross-platform code for a number of commonplace
calculation and adjustment of ARC variables.

Additionally:

* Greater niceness in spl_free_thread : when we see pages
are wanted (but no xnu pressure), react more strongly.
Notably if we are within 64MB of zfs's memory ceiling,
clamp spl_free to a maximum of 32MB.

* following recent fixes to abd_os.c, revert to
KMC_NOTOUCH at abd_chunk kmem cache creation time, to turn
off BUFTAG|CONTENTS|LITE, thus avoiding allocations of
many many extra 4k chunks in DEBUG builds.

* Double prepopulation of kmem_taskq entries:
kmem_cache_applyall() makes this busy, and we want at
least as many entries as we have kmem caches at
kmem_reqp() time.

macOS: more work

Upstream: zfs_log can't VN_HOLD a possibly unlinked vp

Follow in FreeBSD steps, and avoid the first call to
VN_HOLD in case it is unlinked, as that can deadlock waiting
in vnode_iocount(). Walk up the xattr_parent.
  • Loading branch information
lundman committed Jun 6, 2021
1 parent 50e0872 commit 6f56734
Show file tree
Hide file tree
Showing 373 changed files with 103,947 additions and 204 deletions.
12 changes: 12 additions & 0 deletions appveryor.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
version: 1.0.{build}
branches:
only:
- macos
image: macOS
build_script:
- sh: >-
pwd
ls -l
sh autoconf.sh
./configure CPPFLAGS="-I/usr/local/opt/gettext/include -I/usr/local/opt/openssl@1.1/include" LDFLAGS="-L/usr/local/opt/gettext/lib/ -L/usr/local/opt/openssl@1.1/lib"
make
4 changes: 4 additions & 0 deletions cmd/os/Makefile.am
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@

if BUILD_MACOS
SUBDIRS = macos
endif
3 changes: 3 additions & 0 deletions cmd/os/macos/InvariantDisks/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/DerivedData/
*.xcworkspace/
xcuserdata/
27 changes: 27 additions & 0 deletions cmd/os/macos/InvariantDisks/BSD.LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
Copyright (c) 2014, Gerhard Röthlin
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

* Neither the name of the Project nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
375 changes: 375 additions & 0 deletions cmd/os/macos/InvariantDisks/InvariantDisks.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

71 changes: 71 additions & 0 deletions cmd/os/macos/InvariantDisks/InvariantDisks/IDBaseLinker.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
//
// IDBaseLinker.cpp
// InvariantDisks
//
// Created by Gerhard Röthlin on 2014.05.03.
// Copyright (c) 2014 the-color-black.net. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the conditions of the "3-Clause BSD" license described in the BSD.LICENSE file are met.
// Additional licensing options are described in the README file.
//

#include "IDBaseLinker.hpp"

#include "IDDiskArbitrationUtils.hpp"
#include "IDFileUtils.hpp"

namespace ID
{
BaseLinker::BaseLinker(std::string base, LogClient const & logger) :
DiskArbitrationHandler(logger),
m_base(std::move(base))
{
createCleanPath(m_base);
}

void BaseLinker::diskDisappeared(DADiskRef disk, DiskInformation const & di)
{
removeLinksForDisk(di);
}

void BaseLinker::addLinkForDisk(std::string const & link, DiskInformation const & di)
{
try
{
if (link.empty())
return;
std::string devicePath = "/dev/" + di.mediaBSDName;
logger().logDefault("Creating symlink: ", link, " -> ", devicePath);
m_links.emplace(devicePath, SymlinkHandle(link, devicePath));
}
catch (std::exception const & e)
{
logger().logError("Could not create symlink: ", e.what());
}
}

void BaseLinker::removeLinksForDisk(DiskInformation const & di)
{
try
{
std::string devicePath = "/dev/" + di.mediaBSDName;
auto found = m_links.equal_range(devicePath);
for (auto it = found.first; it != found.second; ++it)
{
logger().logDefault("Removing symlink: ", it->second.link());
it->second.reset();
}
m_links.erase(found.first, found.second);
}
catch (std::exception const & e)
{
logger().logError("Could not remove symlink: ", e.what());
}
}

std::string const & BaseLinker::base() const
{
return m_base;
}
}
44 changes: 44 additions & 0 deletions cmd/os/macos/InvariantDisks/InvariantDisks/IDBaseLinker.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
//
// IDBaseLinker.hpp
// InvariantDisks
//
// Created by Gerhard Röthlin on 2014.05.03.
// Copyright (c) 2014 the-color-black.net. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the conditions of the "3-Clause BSD" license described in the BSD.LICENSE file are met.
// Additional licensing options are described in the README file.
//

#ifndef ID_BASE_LINKER_HPP
#define ID_BASE_LINKER_HPP

#include "IDDiskArbitrationHandler.hpp"

#include "IDSymlinkHandle.hpp"

#include <string>
#include <map>

namespace ID
{
class BaseLinker : public DiskArbitrationHandler
{
public:
explicit BaseLinker(std::string base, LogClient const & logger);

public:
virtual void diskDisappeared(DADiskRef disk, DiskInformation const & info) override;

protected:
void addLinkForDisk(std::string const & link, DiskInformation const & di);
void removeLinksForDisk(DiskInformation const & di);
std::string const & base() const;

private:
std::string m_base;
std::multimap<std::string,SymlinkHandle> m_links;
};
}

#endif
171 changes: 171 additions & 0 deletions cmd/os/macos/InvariantDisks/InvariantDisks/IDCLI.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
//
// IDCLI.cpp
// InvariantDisks
//
// Created by Gerhard Röthlin on 2014.04.27.
// Copyright (c) 2014 the-color-black.net. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the conditions of the "3-Clause BSD" license described in the BSD.LICENSE file are met.
// Additional licensing options are described in the README file.
//

#include "IDCLI.hpp"

#include "IDException.hpp"
#include "IDDiskArbitrationDispatcher.hpp"
#include "IDDiskInfoLogger.hpp"
#include "IDDAHandlerIdle.hpp"
#include "IDMediaPathLinker.hpp"
#include "IDUUIDLinker.hpp"
#include "IDSerialLinker.hpp"
#include "IDImagePathLinker.hpp"
#include "IDDispatchUtils.hpp"
#include "IDLogUtils.hpp"

#include <vector>
#include <map>
#include <string>
#include <iostream>
#include <algorithm>
#include <thread>
#include <functional>

#include <CoreFoundation/CoreFoundation.h>

#include <dispatch/dispatch.h>

#include "git-version.h"

namespace ID
{
struct CLI::Impl
{
std::mutex mutex;
DispatchSource signalSourceINT;
DispatchSource signalSourceTERM;
bool showHelp = false;
bool verbose = false;
std::string basePath = "/var/run/disk";
std::string logPath;
int64_t idleTimeoutNS = 4000000000;
CFRunLoopRef runloop = nullptr;
LogClient * logger = nullptr;
};

CLI::CLI(int & argc, char ** argv, LogClient & logger) :
m_impl(new Impl)
{
m_impl->logger = &logger;
// Setup
dispatch_function_t stopHandler = [](void * ctx){ static_cast<CLI*>(ctx)->stop();};
m_impl->signalSourceINT = createSourceSignal(SIGINT, this, stopHandler);
m_impl->signalSourceTERM = createSourceSignal(SIGTERM, this, stopHandler);
// UI
showVersion();
parse(argc, argv);
}

CLI::~CLI()
{
}

int CLI::exec()
{
// Print help and terminate
if (m_impl->showHelp)
{
showHelp();
return 0;
}
// Start runloop
{
std::lock_guard<std::mutex> lock(m_impl->mutex);
if (m_impl->runloop)
throw Exception("CLI already running");
m_impl->runloop = CFRunLoopGetCurrent();
}
auto & logger = *m_impl->logger;
if (!m_impl->logPath.empty())
logger.addLogFile(m_impl->logPath.c_str());
DiskArbitrationDispatcher dispatcher;
dispatcher.addHandler(std::make_shared<DAHandlerIdle>(m_impl->basePath, m_impl->idleTimeoutNS, logger));
dispatcher.addHandler(std::make_shared<DiskInfoLogger>(m_impl->verbose, logger));
dispatcher.addHandler(std::make_shared<MediaPathLinker>(m_impl->basePath + "/by-path", logger));
dispatcher.addHandler(std::make_shared<UUIDLinker>(m_impl->basePath + "/by-id", logger));
dispatcher.addHandler(std::make_shared<SerialLinker>(m_impl->basePath + "/by-serial", logger));
dispatcher.addHandler(std::make_shared<ImagePathLinker>(m_impl->basePath + "/by-image-path", logger));
dispatcher.start();
CFRunLoopRun();
{
std::lock_guard<std::mutex> lock(m_impl->mutex);
m_impl->runloop = nullptr;
}
return 0;
}

void CLI::stop()
{
std::lock_guard<std::mutex> lock(m_impl->mutex);
if (m_impl->runloop)
CFRunLoopStop(m_impl->runloop);
}

struct CLIFlagHandler
{
size_t argCount;
std::function<void(char **)> func;
};

void CLI::showVersion() const
{
std::cout << "InvariantDisk " << GIT_VERSION << std::endl;
}

void CLI::showHelp() const
{
std::cout << "Usage: InvariantDisks [-hv] [-p <basePath>] [-t <timeoutMS>]\n";
std::cout << "\t-h:\tprint help and exit\n";
std::cout << "\t-v:\tverbose logging\n";
std::cout << "\t-p <basePath>:\tset base path for symlinks (" << m_impl->basePath << ")\n";
std::cout << "\t-l <logPath>:\tset optional path for logging (" << m_impl->logPath << ")\n";
std::cout << "\t-t <timeoutMS>:\tset idle timeout (" << m_impl->idleTimeoutNS/1000000 << " ms)\n";
}

void CLI::parse(int & argc, char ** argv)
{
// Command Line Parsing
std::map<std::string, CLIFlagHandler> cliFlags =
{
{"-h", { 0, [&](char **){ m_impl->showHelp = true; }}},
{"-v", { 0, [&](char **){ m_impl->verbose = true; }}},
{"-p", { 1, [&](char ** a){ m_impl->basePath = a[1]; }}},
{"-l", { 1, [&](char ** a){ m_impl->logPath = a[1]; }}},
{"-t", { 1, [&](char ** a){
try
{
int64_t timeoutInNS = std::stol(a[1])*1000000ll;
if (timeoutInNS < 0)
throw std::out_of_range("negative");
m_impl->idleTimeoutNS = timeoutInNS;
}
catch (std::exception const & e)
{
Throw<Exception>() << "Idle Timeout " << a[1] << " is not a valid timeout: " << e.what();
}
}}}
};
for (int argIdx = 0; argIdx < argc; ++argIdx)
{
auto flagIt = cliFlags.find(argv[argIdx]);
if (flagIt != cliFlags.end())
{
CLIFlagHandler const & f = flagIt->second;
if (argIdx + f.argCount >= argc)
Throw<Exception>() << "Flag " << argv[argIdx] << " requires " << f.argCount << " arguments";
f.func(&argv[argIdx]);
argIdx += f.argCount;
}
}
}
}
44 changes: 44 additions & 0 deletions cmd/os/macos/InvariantDisks/InvariantDisks/IDCLI.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
//
// IDCLI.hpp
// InvariantDisks
//
// Created by Gerhard Röthlin on 2014.04.27.
// Copyright (c) 2014 the-color-black.net. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the conditions of the "3-Clause BSD" license described in the BSD.LICENSE file are met.
// Additional licensing options are described in the README file.
//

#ifndef ID_CLI_HPP
#define ID_CLI_HPP

#include <string>
#include <memory>

namespace ID
{
class LogClient;

class CLI
{
public:
CLI(int & argc, char ** argv, LogClient & logger);
~CLI();

public:
int exec();
void stop();

private:
void showVersion() const;
void showHelp() const;
void parse(int & argc, char ** argv);

private:
struct Impl;
std::unique_ptr<Impl> m_impl;
};
}

#endif
Loading

0 comments on commit 6f56734

Please sign in to comment.