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/IOPlatformExpert.h>
38 #include <pexpert/pexpert.h>
39 #include <kern/clock.h>
40 #include <uuid/uuid.h>
42 // how long to wait for matching root device, secs
44 #define ROOTDEVICETIMEOUT 120
46 #define ROOTDEVICETIMEOUT 60
49 extern dev_t
mdevadd(int devid
, uint64_t base
, unsigned int size
, int phys
);
50 extern dev_t
mdevlookup(int devid
);
51 extern void mdevremoveall(void);
52 extern void di_root_ramfile(IORegistryEntry
* entry
);
57 IOService::publishResource("IOBSD");
59 return( kIOReturnSuccess
);
63 IOServicePublishResource( const char * property
, boolean_t value
)
66 IOService::publishResource( property
, kOSBooleanTrue
);
68 IOService::getResourceService()->removeProperty( property
);
72 IOServiceWaitForMatchingResource( const char * property
, uint64_t timeout
)
74 OSDictionary
* dict
= 0;
75 IOService
* match
= 0;
76 boolean_t found
= false;
80 dict
= IOService::resourceMatching( property
);
83 match
= IOService::waitForMatchingService( dict
, timeout
);
98 IOCatalogueMatchingDriversPresent( const char * property
)
100 OSDictionary
* dict
= 0;
101 OSOrderedSet
* set
= 0;
102 SInt32 generationCount
= 0;
103 boolean_t found
= false;
107 dict
= OSDictionary::withCapacity(1);
110 dict
->setObject( property
, kOSBooleanTrue
);
111 set
= gIOCatalogue
->findDrivers( dict
, &generationCount
);
112 if ( set
&& (set
->getCount() > 0))
125 OSDictionary
* IOBSDNameMatching( const char * name
)
128 const OSSymbol
* str
= 0;
132 dict
= IOService::serviceMatching( gIOServiceKey
);
135 str
= OSSymbol::withCString( name
);
138 dict
->setObject( kIOBSDNameKey
, (OSObject
*) str
);
153 OSDictionary
* IOUUIDMatching( void )
155 return IOService::resourceMatching( "boot-uuid-media" );
158 OSDictionary
* IONetworkNamePrefixMatching( const char * prefix
)
160 OSDictionary
* matching
;
161 OSDictionary
* propDict
= 0;
162 const OSSymbol
* str
= 0;
163 char networkType
[128];
166 matching
= IOService::serviceMatching( "IONetworkInterface" );
170 propDict
= OSDictionary::withCapacity(1);
174 str
= OSSymbol::withCString( prefix
);
178 propDict
->setObject( "IOInterfaceNamePrefix", (OSObject
*) str
);
182 // see if we're contrained to netroot off of specific network type
183 if(PE_parse_boot_argn( "network-type", networkType
, 128 ))
185 str
= OSSymbol::withCString( networkType
);
188 propDict
->setObject( "IONetworkRootType", str
);
194 if ( matching
->setObject( gIOPropertyMatchKey
,
195 (OSObject
*) propDict
) != true )
205 if ( matching
) matching
->release();
206 if ( propDict
) propDict
->release();
207 if ( str
) str
->release();
212 static bool IORegisterNetworkInterface( IOService
* netif
)
214 // A network interface is typically named and registered
215 // with BSD after receiving a request from a user space
216 // "namer". However, for cases when the system needs to
217 // root from the network, this registration task must be
218 // done inside the kernel and completed before the root
219 // device is handed to BSD.
224 OSDictionary
* dict
= 0;
227 enum { kMaxPathLen
= 512 };
230 stack
= IOService::waitForService(
231 IOService::serviceMatching("IONetworkStack") );
232 if ( stack
== 0 ) break;
234 dict
= OSDictionary::withCapacity(3);
235 if ( dict
== 0 ) break;
237 zero
= OSNumber::withNumber((UInt64
) 0, 32);
238 if ( zero
== 0 ) break;
240 pathBuf
= (char *) IOMalloc( kMaxPathLen
);
241 if ( pathBuf
== 0 ) break;
244 if ( netif
->getPath( pathBuf
, &len
, gIOServicePlane
)
247 path
= OSString::withCStringNoCopy( pathBuf
);
248 if ( path
== 0 ) break;
250 dict
->setObject( "IOInterfaceUnit", zero
);
251 dict
->setObject( kIOPathMatchKey
, path
);
253 stack
->setProperties( dict
);
257 if ( zero
) zero
->release();
258 if ( path
) path
->release();
259 if ( dict
) dict
->release();
260 if ( pathBuf
) IOFree(pathBuf
, kMaxPathLen
);
262 return ( netif
->getProperty( kIOBSDNameKey
) != 0 );
265 OSDictionary
* IOOFPathMatching( const char * path
, char * buf
, int maxLen
)
267 OSDictionary
* matching
;
274 len
= strlen( kIODeviceTreePlane
":" );
279 strlcpy( buf
, kIODeviceTreePlane
":", len
+ 1 );
282 len
= strlen( path
);
286 strlcpy( comp
, path
, len
+ 1 );
288 matching
= OSDictionary::withCapacity( 1 );
292 str
= OSString::withCString( buf
);
295 matching
->setObject( kIOPathMatchKey
, str
);
308 static int didRam
= 0;
310 kern_return_t
IOFindBSDRoot( char * rootName
, unsigned int rootNameSize
,
311 dev_t
* root
, u_int32_t
* oflags
)
315 IORegistryEntry
* regEntry
;
316 OSDictionary
* matching
= 0;
323 const char * mediaProperty
= 0;
325 enum { kMaxPathBuf
= 512, kMaxBootVar
= 128 };
327 const char * look
= 0;
329 bool debugInfoPrintedOnce
= false;
330 const char * uuidStr
= NULL
;
332 static int mountAttempts
= 0;
340 str
= (char *) IOMalloc( kMaxPathBuf
+ kMaxBootVar
);
342 return( kIOReturnNoMemory
);
343 rdBootVar
= str
+ kMaxPathBuf
;
345 if (!PE_parse_boot_argn("rd", rdBootVar
, kMaxBootVar
)
346 && !PE_parse_boot_argn("rootdev", rdBootVar
, kMaxBootVar
))
350 if( (regEntry
= IORegistryEntry::fromPath( "/chosen", gIODTPlane
))) {
351 di_root_ramfile(regEntry
);
352 data
= OSDynamicCast(OSData
, regEntry
->getProperty( "root-matching" ));
354 matching
= OSDynamicCast(OSDictionary
, OSUnserializeXML((char *)data
->getBytesNoCopy()));
360 data
= (OSData
*) regEntry
->getProperty( "boot-uuid" );
362 uuidStr
= (const char*)data
->getBytesNoCopy();
363 OSString
*uuidString
= OSString::withCString( uuidStr
);
365 // match the boot-args boot-uuid processing below
367 IOLog("rooting via boot-uuid from /chosen: %s\n", uuidStr
);
368 IOService::publishResource( "boot-uuid", uuidString
);
369 uuidString
->release();
370 matching
= IOUUIDMatching();
371 mediaProperty
= "boot-uuid-media";
383 // See if we have a RAMDisk property in /chosen/memory-map. If so, make it into a device.
384 // It will become /dev/mdx, where x is 0-f.
387 if(!didRam
) { /* Have we already build this ram disk? */
388 didRam
= 1; /* Remember we did this */
389 if((regEntry
= IORegistryEntry::fromPath( "/chosen/memory-map", gIODTPlane
))) { /* Find the map node */
390 data
= (OSData
*)regEntry
->getProperty("RAMDisk"); /* Find the ram disk, if there */
391 if(data
) { /* We found one */
392 UInt32
*ramdParms
= 0;
393 ramdParms
= (UInt32
*)data
->getBytesNoCopy(); /* Point to the ram disk base and size */
394 (void)mdevadd(-1, ml_static_ptovirt(ramdParms
[0]) >> 12, ramdParms
[1] >> 12, 0); /* Initialize it and pass back the device number */
396 regEntry
->release(); /* Toss the entry */
401 // Now check if we are trying to root on a memory device
404 if((rdBootVar
[0] == 'm') && (rdBootVar
[1] == 'd') && (rdBootVar
[3] == 0)) {
405 dchar
= xchar
= rdBootVar
[2]; /* Get the actual device */
406 if((xchar
>= '0') && (xchar
<= '9')) xchar
= xchar
- '0'; /* If digit, convert */
408 xchar
= xchar
& ~' '; /* Fold to upper case */
409 if((xchar
>= 'A') && (xchar
<= 'F')) { /* Is this a valid digit? */
410 xchar
= (xchar
& 0xF) + 9; /* Convert the hex digit */
411 dchar
= dchar
| ' '; /* Fold to lower case */
413 else xchar
= -1; /* Show bogus */
415 if(xchar
>= 0) { /* Do we have a valid memory device name? */
416 *root
= mdevlookup(xchar
); /* Find the device number */
417 if(*root
>= 0) { /* Did we find one? */
419 rootName
[0] = 'm'; /* Build root name */
420 rootName
[1] = 'd'; /* Build root name */
421 rootName
[2] = dchar
; /* Build root name */
422 rootName
[3] = 0; /* Build root name */
423 IOLog("BSD root: %s, major %d, minor %d\n", rootName
, major(*root
), minor(*root
));
424 *oflags
= 0; /* Show that this is not network */
425 goto iofrootx
; /* Join common exit... */
427 panic("IOFindBSDRoot: specified root memory device, %s, has not been configured\n", rdBootVar
); /* Not there */
431 if( (!matching
) && rdBootVar
[0] ) {
437 if ( strncmp( look
, "en", strlen( "en" )) == 0 ) {
438 matching
= IONetworkNamePrefixMatching( "en" );
439 } else if ( strncmp( look
, "uuid", strlen( "uuid" )) == 0 ) {
441 OSString
*uuidString
;
443 uuid
= (char *)IOMalloc( kMaxBootVar
);
446 if (!PE_parse_boot_argn( "boot-uuid", uuid
, kMaxBootVar
)) {
447 panic( "rd=uuid but no boot-uuid=<value> specified" );
449 uuidString
= OSString::withCString( uuid
);
451 IOService::publishResource( "boot-uuid", uuidString
);
452 uuidString
->release();
453 IOLog( "\nWaiting for boot volume with UUID %s\n", uuid
);
454 matching
= IOUUIDMatching();
455 mediaProperty
= "boot-uuid-media";
457 IOFree( uuid
, kMaxBootVar
);
460 matching
= IOBSDNameMatching( look
);
466 // Match any HFS media
468 matching
= IOService::serviceMatching( "IOMedia" );
469 astring
= OSString::withCStringNoCopy("Apple_HFS");
471 matching
->setObject("Content", astring
);
476 if( true && matching
) {
477 OSSerialize
* s
= OSSerialize::withCapacity( 5 );
479 if( matching
->serialize( s
)) {
480 IOLog( "Waiting on %s\n", s
->text() );
486 t
.tv_sec
= ROOTDEVICETIMEOUT
;
489 service
= IOService::waitForService( matching
, &t
);
490 if( (!service
) || (mountAttempts
== 10)) {
491 PE_display_icon( 0, "noroot");
492 IOLog( "Still waiting for root device\n" );
494 if( !debugInfoPrintedOnce
) {
495 debugInfoPrintedOnce
= true;
496 if( gIOKitDebug
& kIOLogDTree
) {
497 IOLog("\nDT plane:\n");
498 IOPrintPlane( gIODTPlane
);
500 if( gIOKitDebug
& kIOLogServiceTree
) {
501 IOLog("\nService plane:\n");
502 IOPrintPlane( gIOServicePlane
);
504 if( gIOKitDebug
& kIOLogMemory
)
511 if ( service
&& mediaProperty
) {
512 service
= (IOService
*)service
->getProperty(mediaProperty
);
518 // If the IOService we matched to is a subclass of IONetworkInterface,
519 // then make sure it has been registered with BSD and has a BSD name
523 && service
->metaCast( "IONetworkInterface" )
524 && !IORegisterNetworkInterface( service
) )
532 service
->getPath( str
, &len
, gIOServicePlane
);
533 IOLog( "Got boot device = %s\n", str
);
535 iostr
= (OSString
*) service
->getProperty( kIOBSDNameKey
);
537 strlcpy( rootName
, iostr
->getCStringNoCopy(), rootNameSize
);
538 off
= (OSNumber
*) service
->getProperty( kIOBSDMajorKey
);
540 mjr
= off
->unsigned32BitValue();
541 off
= (OSNumber
*) service
->getProperty( kIOBSDMinorKey
);
543 mnr
= off
->unsigned32BitValue();
545 if( service
->metaCast( "IONetworkInterface" ))
550 IOLog( "Wait for root failed\n" );
551 strlcpy( rootName
, "en0", rootNameSize
);
555 IOLog( "BSD root: %s", rootName
);
557 IOLog(", major %d, minor %d\n", mjr
, mnr
);
561 *root
= makedev( mjr
, mnr
);
564 IOFree( str
, kMaxPathBuf
+ kMaxBootVar
);
567 if( (gIOKitDebug
& (kIOLogDTree
| kIOLogServiceTree
| kIOLogMemory
)) && !debugInfoPrintedOnce
) {
569 IOService::getPlatform()->waitQuiet();
570 if( gIOKitDebug
& kIOLogDTree
) {
571 IOLog("\nDT plane:\n");
572 IOPrintPlane( gIODTPlane
);
574 if( gIOKitDebug
& kIOLogServiceTree
) {
575 IOLog("\nService plane:\n");
576 IOPrintPlane( gIOServicePlane
);
578 if( gIOKitDebug
& kIOLogMemory
)
582 return( kIOReturnSuccess
);
585 void IOSecureBSDRoot(const char * rootName
)
589 IOPlatformExpert
*pe
;
590 const OSSymbol
*functionName
= OSSymbol::withCStringNoCopy("SecureRootName");
592 while ((pe
= IOService::getPlatform()) == 0) IOSleep(1 * 1000);
594 // Returns kIOReturnNotPrivileged is the root device is not secure.
595 // Returns kIOReturnUnsupported if "SecureRootName" is not implemented.
596 result
= pe
->callPlatformFunction(functionName
, false, (void *)rootName
, (void *)0, (void *)0, (void *)0);
598 functionName
->release();
600 if (result
== kIOReturnNotPrivileged
) mdevremoveall();
605 IOBSDRegistryEntryForDeviceTree(char * path
)
607 return (IORegistryEntry::fromPath(path
, gIODTPlane
));
611 IOBSDRegistryEntryRelease(void * entry
)
613 IORegistryEntry
* regEntry
= (IORegistryEntry
*)entry
;
621 IOBSDRegistryEntryGetData(void * entry
, char * property_name
,
625 IORegistryEntry
* regEntry
= (IORegistryEntry
*)entry
;
627 data
= (OSData
*) regEntry
->getProperty(property_name
);
629 *packet_length
= data
->getLength();
630 return (data
->getBytesNoCopy());
635 kern_return_t
IOBSDGetPlatformUUID( uuid_t uuid
, mach_timespec_t timeout
)
637 IOService
* resources
;
640 resources
= IOService::waitForService( IOService::resourceMatching( kIOPlatformUUIDKey
), ( timeout
.tv_sec
|| timeout
.tv_nsec
) ? &timeout
: 0 );
641 if ( resources
== 0 ) return KERN_OPERATION_TIMED_OUT
;
643 string
= ( OSString
* ) IOService::getPlatform( )->getProvider( )->getProperty( kIOPlatformUUIDKey
);
644 if ( string
== 0 ) return KERN_NOT_SUPPORTED
;
646 uuid_parse( string
->getCStringNoCopy( ), uuid
);
651 kern_return_t
IOBSDGetPlatformSerialNumber( char *serial_number_str
, u_int32_t len
)
653 OSDictionary
* platform_dict
;
660 serial_number_str
[0] = '\0';
662 platform_dict
= IOService::serviceMatching( "IOPlatformExpertDevice" );
663 if (platform_dict
== NULL
) {
664 return KERN_NOT_SUPPORTED
;
667 platform
= IOService::waitForService( platform_dict
);
669 string
= ( OSString
* ) platform
->getProperty( kIOPlatformSerialNumberKey
);
671 return KERN_NOT_SUPPORTED
;
673 strlcpy( serial_number_str
, string
->getCStringNoCopy( ), len
);
680 dev_t
IOBSDGetMediaWithUUID( const char *uuid_cstring
, char *bsd_name
, int bsd_name_len
, int timeout
)
683 OSDictionary
*dictionary
;
684 OSString
*uuid_string
;
686 if (bsd_name_len
< 1) {
691 dictionary
= IOService::serviceMatching( "IOMedia" );
693 uuid_string
= OSString::withCString( uuid_cstring
);
696 mach_timespec_t tv
= { timeout
, 0 }; // wait up to "timeout" seconds for the device
698 dictionary
->setObject( "UUID", uuid_string
);
699 dictionary
->retain();
700 service
= IOService::waitForService( dictionary
, &tv
);
702 OSNumber
*dev_major
= (OSNumber
*) service
->getProperty( kIOBSDMajorKey
);
703 OSNumber
*dev_minor
= (OSNumber
*) service
->getProperty( kIOBSDMinorKey
);
704 OSString
*iostr
= (OSString
*) service
->getProperty( kIOBSDNameKey
);
707 strlcpy( bsd_name
, iostr
->getCStringNoCopy(), bsd_name_len
);
709 if ( dev_major
&& dev_minor
)
710 dev
= makedev( dev_major
->unsigned32BitValue(), dev_minor
->unsigned32BitValue() );
712 uuid_string
->release();
714 dictionary
->release();
721 void IOBSDIterateMediaWithContent(const char *content_uuid_cstring
, int (*func
)(const char *bsd_dev_name
, const char *uuid_str
, void *arg
), void *arg
)
723 OSDictionary
*dictionary
;
724 OSString
*content_uuid_string
;
726 dictionary
= IOService::serviceMatching( "IOMedia" );
728 content_uuid_string
= OSString::withCString( content_uuid_cstring
);
729 if( content_uuid_string
) {
733 dictionary
->setObject( "Content", content_uuid_string
);
734 dictionary
->retain();
736 iter
= IOService::getMatchingServices(dictionary
);
737 while (iter
&& (service
= (IOService
*)iter
->getNextObject())) {
739 OSString
*iostr
= (OSString
*) service
->getProperty( kIOBSDNameKey
);
740 OSString
*uuidstr
= (OSString
*) service
->getProperty( "UUID" );
745 uuid
= uuidstr
->getCStringNoCopy();
747 uuid
= "00000000-0000-0000-0000-000000000000";
751 if (func
&& func(iostr
->getCStringNoCopy(), uuid
, arg
) == 0) {
760 content_uuid_string
->release();
762 dictionary
->release();
767 int IOBSDIsMediaEjectable( const char *cdev_name
)
770 OSDictionary
*dictionary
;
773 if (strncmp(cdev_name
, "/dev/", 5) == 0) {
777 dictionary
= IOService::serviceMatching( "IOMedia" );
779 dev_name
= OSString::withCString( cdev_name
);
782 mach_timespec_t tv
= { 5, 0 }; // wait up to "timeout" seconds for the device
784 dictionary
->setObject( kIOBSDNameKey
, dev_name
);
785 dictionary
->retain();
786 service
= IOService::waitForService( dictionary
, &tv
);
788 OSBoolean
*ejectable
= (OSBoolean
*) service
->getProperty( "Ejectable" );
791 ret
= (int)ejectable
->getValue();
797 dictionary
->release();