2 * Copyright (c) 1998-2011 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
28 #include <IOKit/IOBSD.h>
29 #include <IOKit/IOLib.h>
30 #include <IOKit/IOService.h>
31 #include <IOKit/IOCatalogue.h>
32 #include <IOKit/IODeviceTreeSupport.h>
33 #include <IOKit/IOKitKeys.h>
34 #include <IOKit/IONVRAM.h>
35 #include <IOKit/IOPlatformExpert.h>
36 #include <IOKit/IOUserClient.h>
39 #include <pexpert/pexpert.h>
40 #include <kern/clock.h>
41 #include <mach/machine.h>
42 #include <uuid/uuid.h>
43 #include <sys/vnode_internal.h>
44 #include <sys/mount.h>
46 // how long to wait for matching root device, secs
48 #define ROOTDEVICETIMEOUT 120
50 #define ROOTDEVICETIMEOUT 60
53 extern dev_t
mdevadd(int devid
, uint64_t base
, unsigned int size
, int phys
);
54 extern dev_t
mdevlookup(int devid
);
55 extern void mdevremoveall(void);
56 extern int mdevgetrange(int devid
, uint64_t *base
, uint64_t *size
);
57 extern void di_root_ramfile(IORegistryEntry
* entry
);
59 #define ROUNDUP(a, b) (((a) + ((b) - 1)) & (~((b) - 1)))
61 #define IOPOLLED_COREFILE (CONFIG_KDP_INTERACTIVE_DEBUGGING)
63 #if defined(XNU_TARGET_OS_BRIDGE)
64 #define kIOCoreDumpPath "/private/var/internal/kernelcore"
65 #elif defined(XNU_TARGET_OS_OSX)
66 #define kIOCoreDumpPath "/System/Volumes/VM/kernelcore"
68 #define kIOCoreDumpPath "/private/var/vm/kernelcore"
71 #define SYSTEM_NVRAM_PREFIX "40A0DDD2-77F8-4392-B4A3-1E7304206516:"
73 #if CONFIG_KDP_INTERACTIVE_DEBUGGING
75 * Touched by IOFindBSDRoot() if a RAMDisk is used for the root device.
77 extern uint64_t kdp_core_ramdisk_addr
;
78 extern uint64_t kdp_core_ramdisk_size
;
82 static void IOOpenPolledCoreFile(thread_call_param_t __unused
, thread_call_param_t corefilename
);
84 thread_call_t corefile_open_call
= NULL
;
90 IOService::publishResource("IOBSD");
93 corefile_open_call
= thread_call_allocate_with_options(IOOpenPolledCoreFile
, NULL
, THREAD_CALL_PRIORITY_KERNEL
, THREAD_CALL_OPTIONS_ONCE
);
96 return kIOReturnSuccess
;
100 IOServicePublishResource( const char * property
, boolean_t value
)
103 IOService::publishResource( property
, kOSBooleanTrue
);
105 IOService::getResourceService()->removeProperty( property
);
110 IOServiceWaitForMatchingResource( const char * property
, uint64_t timeout
)
112 OSDictionary
* dict
= NULL
;
113 IOService
* match
= NULL
;
114 boolean_t found
= false;
117 dict
= IOService::resourceMatching( property
);
121 match
= IOService::waitForMatchingService( dict
, timeout
);
138 IOCatalogueMatchingDriversPresent( const char * property
)
140 OSDictionary
* dict
= NULL
;
141 OSOrderedSet
* set
= NULL
;
142 SInt32 generationCount
= 0;
143 boolean_t found
= false;
146 dict
= OSDictionary::withCapacity(1);
150 dict
->setObject( property
, kOSBooleanTrue
);
151 set
= gIOCatalogue
->findDrivers( dict
, &generationCount
);
152 if (set
&& (set
->getCount() > 0)) {
168 IOBSDNameMatching( const char * name
)
171 const OSSymbol
* str
= NULL
;
174 dict
= IOService::serviceMatching( gIOServiceKey
);
178 str
= OSSymbol::withCString( name
);
182 dict
->setObject( kIOBSDNameKey
, (OSObject
*) str
);
199 IOUUIDMatching( void )
201 return IOService::resourceMatching( "boot-uuid-media" );
205 IONetworkNamePrefixMatching( const char * prefix
)
207 OSDictionary
* matching
;
208 OSDictionary
* propDict
= NULL
;
209 const OSSymbol
* str
= NULL
;
210 char networkType
[128];
213 matching
= IOService::serviceMatching( "IONetworkInterface" );
214 if (matching
== NULL
) {
218 propDict
= OSDictionary::withCapacity(1);
219 if (propDict
== NULL
) {
223 str
= OSSymbol::withCString( prefix
);
228 propDict
->setObject( "IOInterfaceNamePrefix", (OSObject
*) str
);
232 // see if we're contrained to netroot off of specific network type
233 if (PE_parse_boot_argn( "network-type", networkType
, 128 )) {
234 str
= OSSymbol::withCString( networkType
);
236 propDict
->setObject( "IONetworkRootType", str
);
242 if (matching
->setObject( gIOPropertyMatchKey
,
243 (OSObject
*) propDict
) != true) {
267 IORegisterNetworkInterface( IOService
* netif
)
269 // A network interface is typically named and registered
270 // with BSD after receiving a request from a user space
271 // "namer". However, for cases when the system needs to
272 // root from the network, this registration task must be
273 // done inside the kernel and completed before the root
274 // device is handed to BSD.
277 OSNumber
* zero
= NULL
;
278 OSString
* path
= NULL
;
279 OSDictionary
* dict
= NULL
;
280 char * pathBuf
= NULL
;
282 enum { kMaxPathLen
= 512 };
285 stack
= IOService::waitForService(
286 IOService::serviceMatching("IONetworkStack"));
291 dict
= OSDictionary::withCapacity(3);
296 zero
= OSNumber::withNumber((UInt64
) 0, 32);
301 pathBuf
= (char *) IOMalloc( kMaxPathLen
);
302 if (pathBuf
== NULL
) {
307 if (netif
->getPath( pathBuf
, &len
, gIOServicePlane
)
312 path
= OSString::withCStringNoCopy( pathBuf
);
317 dict
->setObject( "IOInterfaceUnit", zero
);
318 dict
->setObject( kIOPathMatchKey
, path
);
320 stack
->setProperties( dict
);
333 IOFree(pathBuf
, kMaxPathLen
);
336 return netif
->getProperty( kIOBSDNameKey
) != NULL
;
340 IOOFPathMatching( const char * path
, char * buf
, int maxLen
)
342 OSDictionary
* matching
= NULL
;
348 len
= ((int) strlen( kIODeviceTreePlane
":" ));
354 strlcpy( buf
, kIODeviceTreePlane
":", len
+ 1 );
357 len
= ((int) strnlen( path
, INT_MAX
));
362 strlcpy( comp
, path
, len
+ 1 );
364 matching
= OSDictionary::withCapacity( 1 );
369 str
= OSString::withCString( buf
);
373 matching
->setObject( kIOPathMatchKey
, str
);
386 static int didRam
= 0;
387 enum { kMaxPathBuf
= 512, kMaxBootVar
= 128 };
392 IORegistryEntry
*entry
;
394 if ((entry
= IORegistryEntry::fromPath("/chosen", gIODTPlane
))) {
395 OSData
*uuid_data
= (OSData
*)entry
->getProperty("boot-uuid");
397 return (const char*)uuid_data
->getBytesNoCopy();
405 IOGetApfsPrebootUUID(void)
407 IORegistryEntry
*entry
;
409 if ((entry
= IORegistryEntry::fromPath("/chosen", gIODTPlane
))) {
410 OSData
*uuid_data
= (OSData
*)entry
->getProperty("apfs-preboot-uuid");
412 return (const char*)uuid_data
->getBytesNoCopy();
420 IOGetAssociatedApfsVolgroupUUID(void)
422 IORegistryEntry
*entry
;
424 if ((entry
= IORegistryEntry::fromPath("/chosen", gIODTPlane
))) {
425 OSData
*uuid_data
= (OSData
*)entry
->getProperty("associated-volume-group");
427 return (const char*)uuid_data
->getBytesNoCopy();
435 IOGetBootObjectsPath(void)
437 IORegistryEntry
*entry
;
439 if ((entry
= IORegistryEntry::fromPath("/chosen", gIODTPlane
))) {
440 OSData
*path_prefix_data
= (OSData
*)entry
->getProperty("boot-objects-path");
441 if (path_prefix_data
) {
442 return (const char *)path_prefix_data
->getBytesNoCopy();
450 * Set NVRAM to boot into the right flavor of Recovery,
451 * optionally passing a UUID of a volume that failed to boot.
452 * If `reboot` is true, reboot immediately.
454 * Returns true if `mode` was understood, false otherwise.
455 * (Does not return if `reboot` is true.)
458 IOSetRecoveryBoot(bsd_bootfail_mode_t mode
, uuid_t volume_uuid
, boolean_t reboot
)
460 IODTNVRAM
*nvram
= NULL
;
461 const OSSymbol
*boot_command_sym
= NULL
;
462 OSString
*boot_command_recover
= NULL
;
464 if (mode
== BSD_BOOTFAIL_SEAL_BROKEN
) {
465 const char *boot_mode
= "ssv-seal-broken";
466 uuid_string_t volume_uuid_str
;
468 // Set `recovery-broken-seal-uuid = <volume_uuid>`.
470 uuid_unparse_upper(volume_uuid
, volume_uuid_str
);
472 if (!PEWriteNVRAMProperty(SYSTEM_NVRAM_PREFIX
"recovery-broken-seal-uuid",
473 volume_uuid_str
, sizeof(uuid_string_t
))) {
474 IOLog("Failed to write recovery-broken-seal-uuid to NVRAM.\n");
478 // Set `recovery-boot-mode = ssv-seal-broken`.
479 if (!PEWriteNVRAMProperty(SYSTEM_NVRAM_PREFIX
"recovery-boot-mode", boot_mode
,
480 (const unsigned int) strlen(boot_mode
))) {
481 IOLog("Failed to write recovery-boot-mode to NVRAM.\n");
483 } else if (mode
== BSD_BOOTFAIL_MEDIA_MISSING
) {
484 const char *boot_picker_reason
= "missing-boot-media";
486 // Set `boot-picker-bringup-reason = missing-boot-media`.
487 if (!PEWriteNVRAMProperty(SYSTEM_NVRAM_PREFIX
"boot-picker-bringup-reason",
488 boot_picker_reason
, (const unsigned int) strlen(boot_picker_reason
))) {
489 IOLog("Failed to write boot-picker-bringup-reason to NVRAM.\n");
492 // Set `boot-command = recover`.
494 // Construct an OSSymbol and an OSString to be the (key, value) pair
495 // we write to NVRAM. Unfortunately, since our value must be an OSString
496 // instead of an OSData, we cannot use PEWriteNVRAMProperty() here.
497 boot_command_sym
= OSSymbol::withCStringNoCopy(SYSTEM_NVRAM_PREFIX
"boot-command");
498 boot_command_recover
= OSString::withCStringNoCopy("recover");
499 if (boot_command_sym
== NULL
|| boot_command_recover
== NULL
) {
500 IOLog("Failed to create boot-command strings.\n");
504 // Wait for NVRAM to be readable...
505 nvram
= OSDynamicCast(IODTNVRAM
, IOService::waitForService(
506 IOService::serviceMatching("IODTNVRAM")));
508 IOLog("Failed to acquire IODTNVRAM object.\n");
512 // Wait for NVRAM to be writable...
513 if (!IOServiceWaitForMatchingResource("IONVRAM", UINT64_MAX
)) {
514 IOLog("Failed to wait for IONVRAM service.\n");
515 // attempt the work anyway...
518 // Write the new boot-command to NVRAM, and sync if successful.
519 if (!nvram
->setProperty(boot_command_sym
, boot_command_recover
)) {
520 IOLog("Failed to save new boot-command to NVRAM.\n");
525 IOLog("Unknown mode: %d\n", mode
);
529 // Clean up and reboot!
535 if (boot_command_recover
!= NULL
) {
536 boot_command_recover
->release();
539 if (boot_command_sym
!= NULL
) {
540 boot_command_sym
->release();
544 IOLog("\nAbout to reboot into Recovery!\n");
545 (void)PEHaltRestart(kPERestartCPU
);
552 IOFindBSDRoot( char * rootName
, unsigned int rootNameSize
,
553 dev_t
* root
, u_int32_t
* oflags
)
557 IORegistryEntry
* regEntry
;
558 OSDictionary
* matching
= NULL
;
561 OSData
* data
= NULL
;
565 const char * mediaProperty
= NULL
;
568 const char * look
= NULL
;
570 bool debugInfoPrintedOnce
= false;
571 bool needNetworkKexts
= false;
572 const char * uuidStr
= NULL
;
574 static int mountAttempts
= 0;
578 // stall here for anyone matching on the IOBSD resource to finish (filesystems)
579 matching
= IOService::serviceMatching(gIOResourcesKey
);
581 matching
->setObject(gIOResourceMatchedKey
, gIOBSDKey
);
583 if ((service
= IOService::waitForMatchingService(matching
, 30ULL * kSecondScale
))) {
591 if (mountAttempts
++) {
592 IOLog("mount(%d) failed\n", mountAttempts
);
596 str
= (char *) IOMalloc( kMaxPathBuf
+ kMaxBootVar
);
598 return kIOReturnNoMemory
;
600 rdBootVar
= str
+ kMaxPathBuf
;
602 if (!PE_parse_boot_argn("rd", rdBootVar
, kMaxBootVar
)
603 && !PE_parse_boot_argn("rootdev", rdBootVar
, kMaxBootVar
)) {
608 if ((regEntry
= IORegistryEntry::fromPath( "/chosen", gIODTPlane
))) {
609 di_root_ramfile(regEntry
);
610 data
= OSDynamicCast(OSData
, regEntry
->getProperty( "root-matching" ));
612 matching
= OSDynamicCast(OSDictionary
, OSUnserializeXML((char *)data
->getBytesNoCopy()));
618 data
= (OSData
*) regEntry
->getProperty( "boot-uuid" );
620 uuidStr
= (const char*)data
->getBytesNoCopy();
621 OSString
*uuidString
= OSString::withCString( uuidStr
);
623 // match the boot-args boot-uuid processing below
625 IOLog("rooting via boot-uuid from /chosen: %s\n", uuidStr
);
626 IOService::publishResource( "boot-uuid", uuidString
);
627 uuidString
->release();
628 matching
= IOUUIDMatching();
629 mediaProperty
= "boot-uuid-media";
641 // See if we have a RAMDisk property in /chosen/memory-map. If so, make it into a device.
642 // It will become /dev/mdx, where x is 0-f.
645 if (!didRam
) { /* Have we already build this ram disk? */
646 didRam
= 1; /* Remember we did this */
647 if ((regEntry
= IORegistryEntry::fromPath( "/chosen/memory-map", gIODTPlane
))) { /* Find the map node */
648 data
= (OSData
*)regEntry
->getProperty("RAMDisk"); /* Find the ram disk, if there */
649 if (data
) { /* We found one */
650 uintptr_t *ramdParms
;
651 ramdParms
= (uintptr_t *)data
->getBytesNoCopy(); /* Point to the ram disk base and size */
653 #define MAX_PHYS_RAM (((uint64_t)UINT_MAX) << 12)
654 if (ramdParms
[1] > MAX_PHYS_RAM
) {
655 panic("ramdisk params");
657 #endif /* __LP64__ */
658 (void)mdevadd(-1, ml_static_ptovirt(ramdParms
[0]) >> 12, (unsigned int) (ramdParms
[1] >> 12), 0); /* Initialize it and pass back the device number */
660 regEntry
->release(); /* Toss the entry */
665 // Now check if we are trying to root on a memory device
668 if ((rdBootVar
[0] == 'm') && (rdBootVar
[1] == 'd') && (rdBootVar
[3] == 0)) {
669 dchar
= xchar
= rdBootVar
[2]; /* Get the actual device */
670 if ((xchar
>= '0') && (xchar
<= '9')) {
671 xchar
= xchar
- '0'; /* If digit, convert */
673 xchar
= xchar
& ~' '; /* Fold to upper case */
674 if ((xchar
>= 'A') && (xchar
<= 'F')) { /* Is this a valid digit? */
675 xchar
= (xchar
& 0xF) + 9; /* Convert the hex digit */
676 dchar
= dchar
| ' '; /* Fold to lower case */
678 xchar
= -1; /* Show bogus */
681 if (xchar
>= 0) { /* Do we have a valid memory device name? */
682 *root
= mdevlookup(xchar
); /* Find the device number */
683 if (*root
>= 0) { /* Did we find one? */
684 rootName
[0] = 'm'; /* Build root name */
685 rootName
[1] = 'd'; /* Build root name */
686 rootName
[2] = (char) dchar
; /* Build root name */
687 rootName
[3] = 0; /* Build root name */
688 IOLog("BSD root: %s, major %d, minor %d\n", rootName
, major(*root
), minor(*root
));
689 *oflags
= 0; /* Show that this is not network */
691 #if CONFIG_KDP_INTERACTIVE_DEBUGGING
692 /* retrieve final ramdisk range and initialize KDP variables */
693 if (mdevgetrange(xchar
, &kdp_core_ramdisk_addr
, &kdp_core_ramdisk_size
) != 0) {
694 IOLog("Unable to retrieve range for root memory device %d\n", xchar
);
695 kdp_core_ramdisk_addr
= 0;
696 kdp_core_ramdisk_size
= 0;
700 goto iofrootx
; /* Join common exit... */
702 panic("IOFindBSDRoot: specified root memory device, %s, has not been configured\n", rdBootVar
); /* Not there */
706 if ((!matching
) && rdBootVar
[0]) {
709 if (look
[0] == '*') {
713 if (strncmp( look
, "en", strlen( "en" )) == 0) {
714 matching
= IONetworkNamePrefixMatching( "en" );
715 needNetworkKexts
= true;
716 } else if (strncmp( look
, "uuid", strlen( "uuid" )) == 0) {
718 OSString
*uuidString
;
720 uuid
= (char *)IOMalloc( kMaxBootVar
);
723 if (!PE_parse_boot_argn( "boot-uuid", uuid
, kMaxBootVar
)) {
724 panic( "rd=uuid but no boot-uuid=<value> specified" );
726 uuidString
= OSString::withCString( uuid
);
728 IOService::publishResource( "boot-uuid", uuidString
);
729 uuidString
->release();
730 IOLog( "\nWaiting for boot volume with UUID %s\n", uuid
);
731 matching
= IOUUIDMatching();
732 mediaProperty
= "boot-uuid-media";
734 IOFree( uuid
, kMaxBootVar
);
737 matching
= IOBSDNameMatching( look
);
743 // Match any HFS media
745 matching
= IOService::serviceMatching( "IOMedia" );
746 astring
= OSString::withCStringNoCopy("Apple_HFS");
748 matching
->setObject("Content", astring
);
753 if (gIOKitDebug
& kIOWaitQuietBeforeRoot
) {
754 IOLog( "Waiting for matching to complete\n" );
755 IOService::getPlatform()->waitQuiet();
758 if (true && matching
) {
759 OSSerialize
* s
= OSSerialize::withCapacity( 5 );
761 if (matching
->serialize( s
)) {
762 IOLog( "Waiting on %s\n", s
->text());
769 || PE_parse_boot_argn("-s", namep
, sizeof(namep
))) {
770 IOService::startDeferredMatches();
774 t
.tv_sec
= ROOTDEVICETIMEOUT
;
777 service
= IOService::waitForService( matching
, &t
);
778 if ((!service
) || (mountAttempts
== 10)) {
779 #if !XNU_TARGET_OS_OSX || !defined(__arm64__)
780 PE_display_icon( 0, "noroot");
781 IOLog( "Still waiting for root device\n" );
784 if (!debugInfoPrintedOnce
) {
785 debugInfoPrintedOnce
= true;
786 if (gIOKitDebug
& kIOLogDTree
) {
787 IOLog("\nDT plane:\n");
788 IOPrintPlane( gIODTPlane
);
790 if (gIOKitDebug
& kIOLogServiceTree
) {
791 IOLog("\nService plane:\n");
792 IOPrintPlane( gIOServicePlane
);
794 if (gIOKitDebug
& kIOLogMemory
) {
799 #if XNU_TARGET_OS_OSX && defined(__arm64__)
800 // The disk isn't found - have the user pick from recoveryOS+.
801 (void)IOSetRecoveryBoot(BSD_BOOTFAIL_MEDIA_MISSING
, NULL
, true);
807 if (service
&& mediaProperty
) {
808 service
= (IOService
*)service
->getProperty(mediaProperty
);
814 // If the IOService we matched to is a subclass of IONetworkInterface,
815 // then make sure it has been registered with BSD and has a BSD name
819 && service
->metaCast( "IONetworkInterface" )
820 && !IORegisterNetworkInterface( service
)) {
826 service
->getPath( str
, &len
, gIOServicePlane
);
827 IOLog( "Got boot device = %s\n", str
);
829 iostr
= (OSString
*) service
->getProperty( kIOBSDNameKey
);
831 strlcpy( rootName
, iostr
->getCStringNoCopy(), rootNameSize
);
833 off
= (OSNumber
*) service
->getProperty( kIOBSDMajorKey
);
835 mjr
= off
->unsigned32BitValue();
837 off
= (OSNumber
*) service
->getProperty( kIOBSDMinorKey
);
839 mnr
= off
->unsigned32BitValue();
842 if (service
->metaCast( "IONetworkInterface" )) {
846 IOLog( "Wait for root failed\n" );
847 strlcpy( rootName
, "en0", rootNameSize
);
851 IOLog( "BSD root: %s", rootName
);
853 IOLog(", major %d, minor %d\n", mjr
, mnr
);
858 *root
= makedev( mjr
, mnr
);
861 IOFree( str
, kMaxPathBuf
+ kMaxBootVar
);
864 if ((gIOKitDebug
& (kIOLogDTree
| kIOLogServiceTree
| kIOLogMemory
)) && !debugInfoPrintedOnce
) {
865 IOService::getPlatform()->waitQuiet();
866 if (gIOKitDebug
& kIOLogDTree
) {
867 IOLog("\nDT plane:\n");
868 IOPrintPlane( gIODTPlane
);
870 if (gIOKitDebug
& kIOLogServiceTree
) {
871 IOLog("\nService plane:\n");
872 IOPrintPlane( gIOServicePlane
);
874 if (gIOKitDebug
& kIOLogMemory
) {
879 return kIOReturnSuccess
;
883 IORamDiskBSDRoot(void)
885 char rdBootVar
[kMaxBootVar
];
886 if (PE_parse_boot_argn("rd", rdBootVar
, kMaxBootVar
)
887 || PE_parse_boot_argn("rootdev", rdBootVar
, kMaxBootVar
)) {
888 if ((rdBootVar
[0] == 'm') && (rdBootVar
[1] == 'd') && (rdBootVar
[3] == 0)) {
896 IOSecureBSDRoot(const char * rootName
)
898 #if CONFIG_SECURE_BSD_ROOT
900 IOPlatformExpert
*pe
;
901 OSDictionary
*matching
;
902 const OSSymbol
*functionName
= OSSymbol::withCStringNoCopy("SecureRootName");
904 matching
= IOService::serviceMatching("IOPlatformExpert");
906 pe
= (IOPlatformExpert
*) IOService::waitForMatchingService(matching
, 30ULL * kSecondScale
);
909 // Returns kIOReturnNotPrivileged is the root device is not secure.
910 // Returns kIOReturnUnsupported if "SecureRootName" is not implemented.
911 result
= pe
->callPlatformFunction(functionName
, false, (void *)rootName
, (void *)NULL
, (void *)NULL
, (void *)NULL
);
912 functionName
->release();
913 OSSafeReleaseNULL(pe
);
915 if (result
== kIOReturnNotPrivileged
) {
919 #endif // CONFIG_SECURE_BSD_ROOT
923 IOBSDRegistryEntryForDeviceTree(char * path
)
925 return IORegistryEntry::fromPath(path
, gIODTPlane
);
929 IOBSDRegistryEntryRelease(void * entry
)
931 IORegistryEntry
* regEntry
= (IORegistryEntry
*)entry
;
940 IOBSDRegistryEntryGetData(void * entry
, char * property_name
,
944 IORegistryEntry
* regEntry
= (IORegistryEntry
*)entry
;
946 data
= (OSData
*) regEntry
->getProperty(property_name
);
948 *packet_length
= data
->getLength();
949 return data
->getBytesNoCopy();
955 IOBSDGetPlatformUUID( uuid_t uuid
, mach_timespec_t timeout
)
957 IOService
* resources
;
960 resources
= IOService::waitForService( IOService::resourceMatching( kIOPlatformUUIDKey
), (timeout
.tv_sec
|| timeout
.tv_nsec
) ? &timeout
: NULL
);
961 if (resources
== NULL
) {
962 return KERN_OPERATION_TIMED_OUT
;
965 string
= (OSString
*) IOService::getPlatform()->getProvider()->getProperty( kIOPlatformUUIDKey
);
966 if (string
== NULL
) {
967 return KERN_NOT_SUPPORTED
;
970 uuid_parse( string
->getCStringNoCopy(), uuid
);
976 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
978 #include <sys/conf.h>
979 #include <sys/vnode.h>
980 #include <sys/vnode_internal.h>
981 #include <sys/fcntl.h>
982 #include <IOKit/IOPolledInterface.h>
983 #include <IOKit/IOBufferMemoryDescriptor.h>
985 IOPolledFileIOVars
* gIOPolledCoreFileVars
;
986 kern_return_t gIOPolledCoreFileOpenRet
= kIOReturnNotReady
;
987 IOPolledCoreFileMode_t gIOPolledCoreFileMode
= kIOPolledCoreFileModeNotInitialized
;
989 #if IOPOLLED_COREFILE
991 #if defined(XNU_TARGET_OS_BRIDGE)
992 // On bridgeOS allocate a 150MB corefile and leave 150MB free
993 #define kIOCoreDumpSize 150ULL*1024ULL*1024ULL
994 #define kIOCoreDumpFreeSize 150ULL*1024ULL*1024ULL
996 #elif !defined(XNU_TARGET_OS_OSX) /* defined(XNU_TARGET_OS_BRIDGE) */
997 // On embedded devices with >3GB DRAM we allocate a 500MB corefile
998 // otherwise allocate a 350MB corefile. Leave 350 MB free
1000 #define kIOCoreDumpMinSize 350ULL*1024ULL*1024ULL
1001 #define kIOCoreDumpLargeSize 500ULL*1024ULL*1024ULL
1003 #define kIOCoreDumpFreeSize 350ULL*1024ULL*1024ULL
1005 #else /* defined(XNU_TARGET_OS_BRIDGE) */
1006 // on macOS devices allocate a corefile sized at 1GB / 32GB of DRAM,
1007 // fallback to a 1GB corefile and leave at least 1GB free
1008 #define kIOCoreDumpMinSize 1024ULL*1024ULL*1024ULL
1009 #define kIOCoreDumpIncrementalSize 1024ULL*1024ULL*1024ULL
1011 #define kIOCoreDumpFreeSize 1024ULL*1024ULL*1024ULL
1013 // on older macOS devices we allocate a 1MB file at boot
1014 // to store a panic time stackshot
1015 #define kIOStackshotFileSize 1024ULL*1024ULL
1017 #endif /* defined(XNU_TARGET_OS_BRIDGE) */
1019 static IOPolledCoreFileMode_t
1022 if (on_device_corefile_enabled()) {
1023 return kIOPolledCoreFileModeCoredump
;
1024 } else if (panic_stackshot_to_disk_enabled()) {
1025 return kIOPolledCoreFileModeStackshot
;
1027 return kIOPolledCoreFileModeDisabled
;
1032 IOCoreFileGetSize(uint64_t *ideal_size
, uint64_t *fallback_size
, uint64_t *free_space_to_leave
, IOPolledCoreFileMode_t mode
)
1034 unsigned int requested_corefile_size
= 0;
1036 *ideal_size
= *fallback_size
= *free_space_to_leave
= 0;
1038 #if defined(XNU_TARGET_OS_BRIDGE)
1039 #pragma unused(mode)
1040 *ideal_size
= *fallback_size
= kIOCoreDumpSize
;
1041 *free_space_to_leave
= kIOCoreDumpFreeSize
;
1042 #elif !defined(XNU_TARGET_OS_OSX) /* defined(XNU_TARGET_OS_BRIDGE) */
1043 #pragma unused(mode)
1044 *ideal_size
= *fallback_size
= kIOCoreDumpMinSize
;
1046 if (max_mem
> (3 * 1024ULL * 1024ULL * 1024ULL)) {
1047 *ideal_size
= kIOCoreDumpLargeSize
;
1050 *free_space_to_leave
= kIOCoreDumpFreeSize
;
1051 #else /* defined(XNU_TARGET_OS_BRIDGE) */
1052 if (mode
== kIOPolledCoreFileModeCoredump
) {
1053 *ideal_size
= *fallback_size
= kIOCoreDumpMinSize
;
1054 if (kIOCoreDumpIncrementalSize
!= 0 && max_mem
> (32 * 1024ULL * 1024ULL * 1024ULL)) {
1055 *ideal_size
= ((ROUNDUP(max_mem
, (32 * 1024ULL * 1024ULL * 1024ULL)) / (32 * 1024ULL * 1024ULL * 1024ULL)) * kIOCoreDumpIncrementalSize
);
1057 *free_space_to_leave
= kIOCoreDumpFreeSize
;
1058 } else if (mode
== kIOPolledCoreFileModeStackshot
) {
1059 *ideal_size
= *fallback_size
= *free_space_to_leave
= kIOStackshotFileSize
;
1061 #endif /* defined(XNU_TARGET_OS_BRIDGE) */
1062 // If a custom size was requested, override the ideal and requested sizes
1063 if (PE_parse_boot_argn("corefile_size_mb", &requested_corefile_size
, sizeof(requested_corefile_size
))) {
1064 IOLog("Boot-args specify %d MB kernel corefile\n", requested_corefile_size
);
1066 *ideal_size
= *fallback_size
= (requested_corefile_size
* 1024ULL * 1024ULL);
1073 IOOpenPolledCoreFile(thread_call_param_t __unused
, thread_call_param_t corefilename
)
1075 assert(corefilename
!= NULL
);
1078 char *filename
= (char *) corefilename
;
1079 uint64_t corefile_size_bytes
= 0, corefile_fallback_size_bytes
= 0, free_space_to_leave_bytes
= 0;
1080 IOPolledCoreFileMode_t mode_to_init
= GetCoreFileMode();
1082 if (gIOPolledCoreFileVars
) {
1085 if (!IOPolledInterface::gMetaClass
.getInstanceCount()) {
1089 if (mode_to_init
== kIOPolledCoreFileModeDisabled
) {
1090 gIOPolledCoreFileMode
= kIOPolledCoreFileModeDisabled
;
1094 // We'll overwrite this once we open the file, we update this to mark that we have made
1095 // it past initialization
1096 gIOPolledCoreFileMode
= kIOPolledCoreFileModeClosed
;
1098 IOCoreFileGetSize(&corefile_size_bytes
, &corefile_fallback_size_bytes
, &free_space_to_leave_bytes
, mode_to_init
);
1101 err
= IOPolledFileOpen(filename
, kIOPolledFileCreate
, corefile_size_bytes
, free_space_to_leave_bytes
,
1102 NULL
, 0, &gIOPolledCoreFileVars
, NULL
, NULL
, NULL
);
1103 if (kIOReturnSuccess
== err
) {
1105 } else if (kIOReturnNoSpace
== err
) {
1106 IOLog("Failed to open corefile of size %llu MB (low disk space)",
1107 (corefile_size_bytes
/ (1024ULL * 1024ULL)));
1108 if (corefile_size_bytes
== corefile_fallback_size_bytes
) {
1109 gIOPolledCoreFileOpenRet
= err
;
1113 IOLog("Failed to open corefile of size %llu MB (returned error 0x%x)\n",
1114 (corefile_size_bytes
/ (1024ULL * 1024ULL)), err
);
1115 gIOPolledCoreFileOpenRet
= err
;
1119 err
= IOPolledFileOpen(filename
, kIOPolledFileCreate
, corefile_fallback_size_bytes
, free_space_to_leave_bytes
,
1120 NULL
, 0, &gIOPolledCoreFileVars
, NULL
, NULL
, NULL
);
1121 if (kIOReturnSuccess
!= err
) {
1122 IOLog("Failed to open corefile of size %llu MB (returned error 0x%x)\n",
1123 (corefile_fallback_size_bytes
/ (1024ULL * 1024ULL)), err
);
1124 gIOPolledCoreFileOpenRet
= err
;
1129 gIOPolledCoreFileOpenRet
= IOPolledFilePollersSetup(gIOPolledCoreFileVars
, kIOPolledPreflightCoreDumpState
);
1130 if (kIOReturnSuccess
!= gIOPolledCoreFileOpenRet
) {
1131 IOPolledFileClose(&gIOPolledCoreFileVars
, 0, NULL
, 0, 0, 0);
1132 IOLog("IOPolledFilePollersSetup for corefile failed with error: 0x%x\n", err
);
1134 IOLog("Opened corefile of size %llu MB\n", (corefile_size_bytes
/ (1024ULL * 1024ULL)));
1135 gIOPolledCoreFileMode
= mode_to_init
;
1142 IOClosePolledCoreFile(void)
1144 gIOPolledCoreFileOpenRet
= kIOReturnNotOpen
;
1145 gIOPolledCoreFileMode
= kIOPolledCoreFileModeClosed
;
1146 IOPolledFilePollersClose(gIOPolledCoreFileVars
, kIOPolledPostflightCoreDumpState
);
1147 IOPolledFileClose(&gIOPolledCoreFileVars
, 0, NULL
, 0, 0, 0);
1150 #endif /* IOPOLLED_COREFILE */
1153 IOBSDMountChange(struct mount
* mp
, uint32_t op
)
1155 #if IOPOLLED_COREFILE
1163 case kIOMountChangeMount
:
1164 case kIOMountChangeDidResize
:
1166 if (gIOPolledCoreFileVars
) {
1169 flags
= vfs_flags(mp
);
1170 if (MNT_RDONLY
& flags
) {
1173 if (!(MNT_LOCAL
& flags
)) {
1177 vn
= vfs_vnodecovered(mp
);
1181 pathLen
= sizeof(path
);
1182 result
= vn_getpath(vn
, &path
[0], &pathLen
);
1190 #if defined(XNU_TARGET_OS_BRIDGE)
1191 // on bridgeOS systems we put the core in /private/var/internal. We don't
1192 // want to match with /private/var because /private/var/internal is often mounted
1193 // over /private/var
1194 if ((pathLen
- 1) < (int) strlen("/private/var/internal")) {
1198 if (0 != strncmp(path
, kIOCoreDumpPath
, pathLen
- 1)) {
1202 thread_call_enter1(corefile_open_call
, (void *) kIOCoreDumpPath
);
1205 case kIOMountChangeUnmount
:
1206 case kIOMountChangeWillResize
:
1207 if (gIOPolledCoreFileVars
&& (mp
== kern_file_mount(gIOPolledCoreFileVars
->fileRef
))) {
1208 thread_call_cancel_wait(corefile_open_call
);
1209 IOClosePolledCoreFile();
1213 #endif /* IOPOLLED_COREFILE */
1216 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1218 extern "C" boolean_t
1219 IOTaskHasEntitlement(task_t task
, const char * entitlement
)
1222 obj
= IOUserClient::copyClientEntitlement(task
, entitlement
);
1227 return obj
!= kOSBooleanFalse
;
1230 extern "C" boolean_t
1231 IOVnodeHasEntitlement(vnode_t vnode
, int64_t off
, const char *entitlement
)
1234 off_t offset
= (off_t
)off
;
1236 obj
= IOUserClient::copyClientEntitlementVnode(vnode
, offset
, entitlement
);
1241 return obj
!= kOSBooleanFalse
;
1245 IOVnodeGetEntitlement(vnode_t vnode
, int64_t off
, const char *entitlement
)
1247 OSObject
*obj
= NULL
;
1248 OSString
*str
= NULL
;
1251 off_t offset
= (off_t
)off
;
1253 obj
= IOUserClient::copyClientEntitlementVnode(vnode
, offset
, entitlement
);
1255 str
= OSDynamicCast(OSString
, obj
);
1257 len
= str
->getLength() + 1;
1258 value
= (char *)kheap_alloc(KHEAP_DATA_BUFFERS
, len
, Z_WAITOK
);
1259 strlcpy(value
, str
->getCStringNoCopy(), len
);