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!
531 if (boot_command_recover
!= NULL
) {
532 boot_command_recover
->release();
535 if (boot_command_sym
!= NULL
) {
536 boot_command_sym
->release();
540 IOLog("\nAbout to reboot into Recovery!\n");
541 (void)PEHaltRestart(kPERestartCPU
);
548 IOFindBSDRoot( char * rootName
, unsigned int rootNameSize
,
549 dev_t
* root
, u_int32_t
* oflags
)
553 IORegistryEntry
* regEntry
;
554 OSDictionary
* matching
= NULL
;
557 OSData
* data
= NULL
;
561 const char * mediaProperty
= NULL
;
564 const char * look
= NULL
;
566 bool debugInfoPrintedOnce
= false;
567 bool needNetworkKexts
= false;
568 const char * uuidStr
= NULL
;
570 static int mountAttempts
= 0;
574 // stall here for anyone matching on the IOBSD resource to finish (filesystems)
575 matching
= IOService::serviceMatching(gIOResourcesKey
);
577 matching
->setObject(gIOResourceMatchedKey
, gIOBSDKey
);
579 if ((service
= IOService::waitForMatchingService(matching
, 30ULL * kSecondScale
))) {
587 if (mountAttempts
++) {
588 IOLog("mount(%d) failed\n", mountAttempts
);
592 str
= (char *) IOMalloc( kMaxPathBuf
+ kMaxBootVar
);
594 return kIOReturnNoMemory
;
596 rdBootVar
= str
+ kMaxPathBuf
;
598 if (!PE_parse_boot_argn("rd", rdBootVar
, kMaxBootVar
)
599 && !PE_parse_boot_argn("rootdev", rdBootVar
, kMaxBootVar
)) {
604 if ((regEntry
= IORegistryEntry::fromPath( "/chosen", gIODTPlane
))) {
605 di_root_ramfile(regEntry
);
606 data
= OSDynamicCast(OSData
, regEntry
->getProperty( "root-matching" ));
608 matching
= OSDynamicCast(OSDictionary
, OSUnserializeXML((char *)data
->getBytesNoCopy()));
614 data
= (OSData
*) regEntry
->getProperty( "boot-uuid" );
616 uuidStr
= (const char*)data
->getBytesNoCopy();
617 OSString
*uuidString
= OSString::withCString( uuidStr
);
619 // match the boot-args boot-uuid processing below
621 IOLog("rooting via boot-uuid from /chosen: %s\n", uuidStr
);
622 IOService::publishResource( "boot-uuid", uuidString
);
623 uuidString
->release();
624 matching
= IOUUIDMatching();
625 mediaProperty
= "boot-uuid-media";
637 // See if we have a RAMDisk property in /chosen/memory-map. If so, make it into a device.
638 // It will become /dev/mdx, where x is 0-f.
641 if (!didRam
) { /* Have we already build this ram disk? */
642 didRam
= 1; /* Remember we did this */
643 if ((regEntry
= IORegistryEntry::fromPath( "/chosen/memory-map", gIODTPlane
))) { /* Find the map node */
644 data
= (OSData
*)regEntry
->getProperty("RAMDisk"); /* Find the ram disk, if there */
645 if (data
) { /* We found one */
646 uintptr_t *ramdParms
;
647 ramdParms
= (uintptr_t *)data
->getBytesNoCopy(); /* Point to the ram disk base and size */
649 #define MAX_PHYS_RAM (((uint64_t)UINT_MAX) << 12)
650 if (ramdParms
[1] > MAX_PHYS_RAM
) {
651 panic("ramdisk params");
653 #endif /* __LP64__ */
654 (void)mdevadd(-1, ml_static_ptovirt(ramdParms
[0]) >> 12, (unsigned int) (ramdParms
[1] >> 12), 0); /* Initialize it and pass back the device number */
656 regEntry
->release(); /* Toss the entry */
661 // Now check if we are trying to root on a memory device
664 if ((rdBootVar
[0] == 'm') && (rdBootVar
[1] == 'd') && (rdBootVar
[3] == 0)) {
665 dchar
= xchar
= rdBootVar
[2]; /* Get the actual device */
666 if ((xchar
>= '0') && (xchar
<= '9')) {
667 xchar
= xchar
- '0'; /* If digit, convert */
669 xchar
= xchar
& ~' '; /* Fold to upper case */
670 if ((xchar
>= 'A') && (xchar
<= 'F')) { /* Is this a valid digit? */
671 xchar
= (xchar
& 0xF) + 9; /* Convert the hex digit */
672 dchar
= dchar
| ' '; /* Fold to lower case */
674 xchar
= -1; /* Show bogus */
677 if (xchar
>= 0) { /* Do we have a valid memory device name? */
678 *root
= mdevlookup(xchar
); /* Find the device number */
679 if (*root
>= 0) { /* Did we find one? */
680 rootName
[0] = 'm'; /* Build root name */
681 rootName
[1] = 'd'; /* Build root name */
682 rootName
[2] = (char) dchar
; /* Build root name */
683 rootName
[3] = 0; /* Build root name */
684 IOLog("BSD root: %s, major %d, minor %d\n", rootName
, major(*root
), minor(*root
));
685 *oflags
= 0; /* Show that this is not network */
687 #if CONFIG_KDP_INTERACTIVE_DEBUGGING
688 /* retrieve final ramdisk range and initialize KDP variables */
689 if (mdevgetrange(xchar
, &kdp_core_ramdisk_addr
, &kdp_core_ramdisk_size
) != 0) {
690 IOLog("Unable to retrieve range for root memory device %d\n", xchar
);
691 kdp_core_ramdisk_addr
= 0;
692 kdp_core_ramdisk_size
= 0;
696 goto iofrootx
; /* Join common exit... */
698 panic("IOFindBSDRoot: specified root memory device, %s, has not been configured\n", rdBootVar
); /* Not there */
702 if ((!matching
) && rdBootVar
[0]) {
705 if (look
[0] == '*') {
709 if (strncmp( look
, "en", strlen( "en" )) == 0) {
710 matching
= IONetworkNamePrefixMatching( "en" );
711 needNetworkKexts
= true;
712 } else if (strncmp( look
, "uuid", strlen( "uuid" )) == 0) {
714 OSString
*uuidString
;
716 uuid
= (char *)IOMalloc( kMaxBootVar
);
719 if (!PE_parse_boot_argn( "boot-uuid", uuid
, kMaxBootVar
)) {
720 panic( "rd=uuid but no boot-uuid=<value> specified" );
722 uuidString
= OSString::withCString( uuid
);
724 IOService::publishResource( "boot-uuid", uuidString
);
725 uuidString
->release();
726 IOLog( "\nWaiting for boot volume with UUID %s\n", uuid
);
727 matching
= IOUUIDMatching();
728 mediaProperty
= "boot-uuid-media";
730 IOFree( uuid
, kMaxBootVar
);
733 matching
= IOBSDNameMatching( look
);
739 // Match any HFS media
741 matching
= IOService::serviceMatching( "IOMedia" );
742 astring
= OSString::withCStringNoCopy("Apple_HFS");
744 matching
->setObject("Content", astring
);
749 if (gIOKitDebug
& kIOWaitQuietBeforeRoot
) {
750 IOLog( "Waiting for matching to complete\n" );
751 IOService::getPlatform()->waitQuiet();
754 if (true && matching
) {
755 OSSerialize
* s
= OSSerialize::withCapacity( 5 );
757 if (matching
->serialize( s
)) {
758 IOLog( "Waiting on %s\n", s
->text());
765 || PE_parse_boot_argn("-s", namep
, sizeof(namep
))) {
766 IOService::startDeferredMatches();
770 t
.tv_sec
= ROOTDEVICETIMEOUT
;
773 service
= IOService::waitForService( matching
, &t
);
774 if ((!service
) || (mountAttempts
== 10)) {
775 #if !XNU_TARGET_OS_OSX || !defined(__arm64__)
776 PE_display_icon( 0, "noroot");
777 IOLog( "Still waiting for root device\n" );
780 if (!debugInfoPrintedOnce
) {
781 debugInfoPrintedOnce
= true;
782 if (gIOKitDebug
& kIOLogDTree
) {
783 IOLog("\nDT plane:\n");
784 IOPrintPlane( gIODTPlane
);
786 if (gIOKitDebug
& kIOLogServiceTree
) {
787 IOLog("\nService plane:\n");
788 IOPrintPlane( gIOServicePlane
);
790 if (gIOKitDebug
& kIOLogMemory
) {
795 #if XNU_TARGET_OS_OSX && defined(__arm64__)
796 // The disk isn't found - have the user pick from recoveryOS+.
797 (void)IOSetRecoveryBoot(BSD_BOOTFAIL_MEDIA_MISSING
, NULL
, true);
803 if (service
&& mediaProperty
) {
804 service
= (IOService
*)service
->getProperty(mediaProperty
);
810 // If the IOService we matched to is a subclass of IONetworkInterface,
811 // then make sure it has been registered with BSD and has a BSD name
815 && service
->metaCast( "IONetworkInterface" )
816 && !IORegisterNetworkInterface( service
)) {
822 service
->getPath( str
, &len
, gIOServicePlane
);
823 IOLog( "Got boot device = %s\n", str
);
825 iostr
= (OSString
*) service
->getProperty( kIOBSDNameKey
);
827 strlcpy( rootName
, iostr
->getCStringNoCopy(), rootNameSize
);
829 off
= (OSNumber
*) service
->getProperty( kIOBSDMajorKey
);
831 mjr
= off
->unsigned32BitValue();
833 off
= (OSNumber
*) service
->getProperty( kIOBSDMinorKey
);
835 mnr
= off
->unsigned32BitValue();
838 if (service
->metaCast( "IONetworkInterface" )) {
842 IOLog( "Wait for root failed\n" );
843 strlcpy( rootName
, "en0", rootNameSize
);
847 IOLog( "BSD root: %s", rootName
);
849 IOLog(", major %d, minor %d\n", mjr
, mnr
);
854 *root
= makedev( mjr
, mnr
);
857 IOFree( str
, kMaxPathBuf
+ kMaxBootVar
);
860 if ((gIOKitDebug
& (kIOLogDTree
| kIOLogServiceTree
| kIOLogMemory
)) && !debugInfoPrintedOnce
) {
861 IOService::getPlatform()->waitQuiet();
862 if (gIOKitDebug
& kIOLogDTree
) {
863 IOLog("\nDT plane:\n");
864 IOPrintPlane( gIODTPlane
);
866 if (gIOKitDebug
& kIOLogServiceTree
) {
867 IOLog("\nService plane:\n");
868 IOPrintPlane( gIOServicePlane
);
870 if (gIOKitDebug
& kIOLogMemory
) {
875 return kIOReturnSuccess
;
879 IORamDiskBSDRoot(void)
881 char rdBootVar
[kMaxBootVar
];
882 if (PE_parse_boot_argn("rd", rdBootVar
, kMaxBootVar
)
883 || PE_parse_boot_argn("rootdev", rdBootVar
, kMaxBootVar
)) {
884 if ((rdBootVar
[0] == 'm') && (rdBootVar
[1] == 'd') && (rdBootVar
[3] == 0)) {
892 IOSecureBSDRoot(const char * rootName
)
894 #if CONFIG_SECURE_BSD_ROOT
896 IOPlatformExpert
*pe
;
897 OSDictionary
*matching
;
898 const OSSymbol
*functionName
= OSSymbol::withCStringNoCopy("SecureRootName");
900 matching
= IOService::serviceMatching("IOPlatformExpert");
902 pe
= (IOPlatformExpert
*) IOService::waitForMatchingService(matching
, 30ULL * kSecondScale
);
905 // Returns kIOReturnNotPrivileged is the root device is not secure.
906 // Returns kIOReturnUnsupported if "SecureRootName" is not implemented.
907 result
= pe
->callPlatformFunction(functionName
, false, (void *)rootName
, (void *)NULL
, (void *)NULL
, (void *)NULL
);
908 functionName
->release();
909 OSSafeReleaseNULL(pe
);
911 if (result
== kIOReturnNotPrivileged
) {
915 #endif // CONFIG_SECURE_BSD_ROOT
919 IOBSDRegistryEntryForDeviceTree(char * path
)
921 return IORegistryEntry::fromPath(path
, gIODTPlane
);
925 IOBSDRegistryEntryRelease(void * entry
)
927 IORegistryEntry
* regEntry
= (IORegistryEntry
*)entry
;
936 IOBSDRegistryEntryGetData(void * entry
, char * property_name
,
940 IORegistryEntry
* regEntry
= (IORegistryEntry
*)entry
;
942 data
= (OSData
*) regEntry
->getProperty(property_name
);
944 *packet_length
= data
->getLength();
945 return data
->getBytesNoCopy();
951 IOBSDGetPlatformUUID( uuid_t uuid
, mach_timespec_t timeout
)
953 IOService
* resources
;
956 resources
= IOService::waitForService( IOService::resourceMatching( kIOPlatformUUIDKey
), (timeout
.tv_sec
|| timeout
.tv_nsec
) ? &timeout
: NULL
);
957 if (resources
== NULL
) {
958 return KERN_OPERATION_TIMED_OUT
;
961 string
= (OSString
*) IOService::getPlatform()->getProvider()->getProperty( kIOPlatformUUIDKey
);
962 if (string
== NULL
) {
963 return KERN_NOT_SUPPORTED
;
966 uuid_parse( string
->getCStringNoCopy(), uuid
);
972 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
974 #include <sys/conf.h>
975 #include <sys/vnode.h>
976 #include <sys/vnode_internal.h>
977 #include <sys/fcntl.h>
978 #include <IOKit/IOPolledInterface.h>
979 #include <IOKit/IOBufferMemoryDescriptor.h>
981 IOPolledFileIOVars
* gIOPolledCoreFileVars
;
982 kern_return_t gIOPolledCoreFileOpenRet
= kIOReturnNotReady
;
983 IOPolledCoreFileMode_t gIOPolledCoreFileMode
= kIOPolledCoreFileModeNotInitialized
;
985 #if IOPOLLED_COREFILE
987 #if defined(XNU_TARGET_OS_BRIDGE)
988 // On bridgeOS allocate a 150MB corefile and leave 150MB free
989 #define kIOCoreDumpSize 150ULL*1024ULL*1024ULL
990 #define kIOCoreDumpFreeSize 150ULL*1024ULL*1024ULL
992 #elif !defined(XNU_TARGET_OS_OSX) /* defined(XNU_TARGET_OS_BRIDGE) */
993 // On embedded devices with >3GB DRAM we allocate a 500MB corefile
994 // otherwise allocate a 350MB corefile. Leave 350 MB free
996 #define kIOCoreDumpMinSize 350ULL*1024ULL*1024ULL
997 #define kIOCoreDumpLargeSize 500ULL*1024ULL*1024ULL
999 #define kIOCoreDumpFreeSize 350ULL*1024ULL*1024ULL
1001 #else /* defined(XNU_TARGET_OS_BRIDGE) */
1002 // on macOS devices allocate a corefile sized at 1GB / 32GB of DRAM,
1003 // fallback to a 1GB corefile and leave at least 1GB free
1004 #define kIOCoreDumpMinSize 1024ULL*1024ULL*1024ULL
1005 #define kIOCoreDumpIncrementalSize 1024ULL*1024ULL*1024ULL
1007 #define kIOCoreDumpFreeSize 1024ULL*1024ULL*1024ULL
1009 // on older macOS devices we allocate a 1MB file at boot
1010 // to store a panic time stackshot
1011 #define kIOStackshotFileSize 1024ULL*1024ULL
1013 #endif /* defined(XNU_TARGET_OS_BRIDGE) */
1015 static IOPolledCoreFileMode_t
1018 if (on_device_corefile_enabled()) {
1019 return kIOPolledCoreFileModeCoredump
;
1020 } else if (panic_stackshot_to_disk_enabled()) {
1021 return kIOPolledCoreFileModeStackshot
;
1023 return kIOPolledCoreFileModeDisabled
;
1028 IOCoreFileGetSize(uint64_t *ideal_size
, uint64_t *fallback_size
, uint64_t *free_space_to_leave
, IOPolledCoreFileMode_t mode
)
1030 unsigned int requested_corefile_size
= 0;
1032 *ideal_size
= *fallback_size
= *free_space_to_leave
= 0;
1034 #if defined(XNU_TARGET_OS_BRIDGE)
1035 #pragma unused(mode)
1036 *ideal_size
= *fallback_size
= kIOCoreDumpSize
;
1037 *free_space_to_leave
= kIOCoreDumpFreeSize
;
1038 #elif !defined(XNU_TARGET_OS_OSX) /* defined(XNU_TARGET_OS_BRIDGE) */
1039 #pragma unused(mode)
1040 *ideal_size
= *fallback_size
= kIOCoreDumpMinSize
;
1042 if (max_mem
> (3 * 1024ULL * 1024ULL * 1024ULL)) {
1043 *ideal_size
= kIOCoreDumpLargeSize
;
1046 *free_space_to_leave
= kIOCoreDumpFreeSize
;
1047 #else /* defined(XNU_TARGET_OS_BRIDGE) */
1048 if (mode
== kIOPolledCoreFileModeCoredump
) {
1049 *ideal_size
= *fallback_size
= kIOCoreDumpMinSize
;
1050 if (kIOCoreDumpIncrementalSize
!= 0 && max_mem
> (32 * 1024ULL * 1024ULL * 1024ULL)) {
1051 *ideal_size
= ((ROUNDUP(max_mem
, (32 * 1024ULL * 1024ULL * 1024ULL)) / (32 * 1024ULL * 1024ULL * 1024ULL)) * kIOCoreDumpIncrementalSize
);
1053 *free_space_to_leave
= kIOCoreDumpFreeSize
;
1054 } else if (mode
== kIOPolledCoreFileModeStackshot
) {
1055 *ideal_size
= *fallback_size
= *free_space_to_leave
= kIOStackshotFileSize
;
1057 #endif /* defined(XNU_TARGET_OS_BRIDGE) */
1058 // If a custom size was requested, override the ideal and requested sizes
1059 if (PE_parse_boot_argn("corefile_size_mb", &requested_corefile_size
, sizeof(requested_corefile_size
))) {
1060 IOLog("Boot-args specify %d MB kernel corefile\n", requested_corefile_size
);
1062 *ideal_size
= *fallback_size
= (requested_corefile_size
* 1024ULL * 1024ULL);
1069 IOOpenPolledCoreFile(thread_call_param_t __unused
, thread_call_param_t corefilename
)
1071 assert(corefilename
!= NULL
);
1074 char *filename
= (char *) corefilename
;
1075 uint64_t corefile_size_bytes
= 0, corefile_fallback_size_bytes
= 0, free_space_to_leave_bytes
= 0;
1076 IOPolledCoreFileMode_t mode_to_init
= GetCoreFileMode();
1078 if (gIOPolledCoreFileVars
) {
1081 if (!IOPolledInterface::gMetaClass
.getInstanceCount()) {
1085 if (mode_to_init
== kIOPolledCoreFileModeDisabled
) {
1086 gIOPolledCoreFileMode
= kIOPolledCoreFileModeDisabled
;
1090 // We'll overwrite this once we open the file, we update this to mark that we have made
1091 // it past initialization
1092 gIOPolledCoreFileMode
= kIOPolledCoreFileModeClosed
;
1094 IOCoreFileGetSize(&corefile_size_bytes
, &corefile_fallback_size_bytes
, &free_space_to_leave_bytes
, mode_to_init
);
1097 err
= IOPolledFileOpen(filename
, kIOPolledFileCreate
, corefile_size_bytes
, free_space_to_leave_bytes
,
1098 NULL
, 0, &gIOPolledCoreFileVars
, NULL
, NULL
, NULL
);
1099 if (kIOReturnSuccess
== err
) {
1101 } else if (kIOReturnNoSpace
== err
) {
1102 IOLog("Failed to open corefile of size %llu MB (low disk space)",
1103 (corefile_size_bytes
/ (1024ULL * 1024ULL)));
1104 if (corefile_size_bytes
== corefile_fallback_size_bytes
) {
1105 gIOPolledCoreFileOpenRet
= err
;
1109 IOLog("Failed to open corefile of size %llu MB (returned error 0x%x)\n",
1110 (corefile_size_bytes
/ (1024ULL * 1024ULL)), err
);
1111 gIOPolledCoreFileOpenRet
= err
;
1115 err
= IOPolledFileOpen(filename
, kIOPolledFileCreate
, corefile_fallback_size_bytes
, free_space_to_leave_bytes
,
1116 NULL
, 0, &gIOPolledCoreFileVars
, NULL
, NULL
, NULL
);
1117 if (kIOReturnSuccess
!= err
) {
1118 IOLog("Failed to open corefile of size %llu MB (returned error 0x%x)\n",
1119 (corefile_fallback_size_bytes
/ (1024ULL * 1024ULL)), err
);
1120 gIOPolledCoreFileOpenRet
= err
;
1125 gIOPolledCoreFileOpenRet
= IOPolledFilePollersSetup(gIOPolledCoreFileVars
, kIOPolledPreflightCoreDumpState
);
1126 if (kIOReturnSuccess
!= gIOPolledCoreFileOpenRet
) {
1127 IOPolledFileClose(&gIOPolledCoreFileVars
, 0, NULL
, 0, 0, 0);
1128 IOLog("IOPolledFilePollersSetup for corefile failed with error: 0x%x\n", err
);
1130 IOLog("Opened corefile of size %llu MB\n", (corefile_size_bytes
/ (1024ULL * 1024ULL)));
1131 gIOPolledCoreFileMode
= mode_to_init
;
1138 IOClosePolledCoreFile(void)
1140 gIOPolledCoreFileOpenRet
= kIOReturnNotOpen
;
1141 gIOPolledCoreFileMode
= kIOPolledCoreFileModeClosed
;
1142 IOPolledFilePollersClose(gIOPolledCoreFileVars
, kIOPolledPostflightCoreDumpState
);
1143 IOPolledFileClose(&gIOPolledCoreFileVars
, 0, NULL
, 0, 0, 0);
1146 #endif /* IOPOLLED_COREFILE */
1149 IOBSDMountChange(struct mount
* mp
, uint32_t op
)
1151 #if IOPOLLED_COREFILE
1159 case kIOMountChangeMount
:
1160 case kIOMountChangeDidResize
:
1162 if (gIOPolledCoreFileVars
) {
1165 flags
= vfs_flags(mp
);
1166 if (MNT_RDONLY
& flags
) {
1169 if (!(MNT_LOCAL
& flags
)) {
1173 vn
= vfs_vnodecovered(mp
);
1177 pathLen
= sizeof(path
);
1178 result
= vn_getpath(vn
, &path
[0], &pathLen
);
1186 #if defined(XNU_TARGET_OS_BRIDGE)
1187 // on bridgeOS systems we put the core in /private/var/internal. We don't
1188 // want to match with /private/var because /private/var/internal is often mounted
1189 // over /private/var
1190 if ((pathLen
- 1) < (int) strlen("/private/var/internal")) {
1194 if (0 != strncmp(path
, kIOCoreDumpPath
, pathLen
- 1)) {
1198 thread_call_enter1(corefile_open_call
, (void *) kIOCoreDumpPath
);
1201 case kIOMountChangeUnmount
:
1202 case kIOMountChangeWillResize
:
1203 if (gIOPolledCoreFileVars
&& (mp
== kern_file_mount(gIOPolledCoreFileVars
->fileRef
))) {
1204 thread_call_cancel_wait(corefile_open_call
);
1205 IOClosePolledCoreFile();
1209 #endif /* IOPOLLED_COREFILE */
1212 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1214 extern "C" boolean_t
1215 IOTaskHasEntitlement(task_t task
, const char * entitlement
)
1218 obj
= IOUserClient::copyClientEntitlement(task
, entitlement
);
1223 return obj
!= kOSBooleanFalse
;
1226 extern "C" boolean_t
1227 IOVnodeHasEntitlement(vnode_t vnode
, int64_t off
, const char *entitlement
)
1230 off_t offset
= (off_t
)off
;
1232 obj
= IOUserClient::copyClientEntitlementVnode(vnode
, offset
, entitlement
);
1237 return obj
!= kOSBooleanFalse
;
1241 IOVnodeGetEntitlement(vnode_t vnode
, int64_t off
, const char *entitlement
)
1243 OSObject
*obj
= NULL
;
1244 OSString
*str
= NULL
;
1247 off_t offset
= (off_t
)off
;
1249 obj
= IOUserClient::copyClientEntitlementVnode(vnode
, offset
, entitlement
);
1251 str
= OSDynamicCast(OSString
, obj
);
1253 len
= str
->getLength() + 1;
1254 value
= (char *)kheap_alloc(KHEAP_DATA_BUFFERS
, len
, Z_WAITOK
);
1255 strlcpy(value
, str
->getCStringNoCopy(), len
);