2 * Copyright (c) 2004-2016 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@
33 * - PMRootDomain calls IOHibernateSystemSleep() before system sleep
34 * (devices awake, normal execution context)
35 * - IOHibernateSystemSleep opens the hibernation file (or partition) at the bsd level,
36 * grabs its extents and searches for a polling driver willing to work with that IOMedia.
37 * The BSD code makes an ioctl to the storage driver to get the partition base offset to
38 * the disk, and other ioctls to get the transfer constraints
39 * If successful, the file is written to make sure its initially not bootable (in case of
40 * later failure) and nvram set to point to the first block of the file. (Has to be done
41 * here so blocking is possible in nvram support).
42 * hibernate_setup() in osfmk is called to allocate page bitmaps for all dram, and
43 * page out any pages it wants to (currently zero, but probably some percentage of memory).
44 * Its assumed just allocating pages will cause the VM system to naturally select the best
45 * pages for eviction. It also copies processor flags needed for the restore path and sets
46 * a flag in the boot processor proc info.
47 * gIOHibernateState = kIOHibernateStateHibernating.
48 * - Regular sleep progresses - some drivers may inspect the root domain property
49 * kIOHibernateStateKey to modify behavior. The platform driver saves state to memory
50 * as usual but leaves motherboard I/O on.
51 * - Eventually the platform calls ml_ppc_sleep() in the shutdown context on the last cpu,
52 * at which point memory is ready to be saved. mapping_hibernate_flush() is called to get
53 * all ppc RC bits out of the hash table and caches into the mapping structures.
54 * - hibernate_write_image() is called (still in shutdown context, no blocking or preemption).
55 * hibernate_page_list_setall() is called to get a bitmap of dram pages that need to be saved.
56 * All pages are assumed to be saved (as part of the wired image) unless explicitly subtracted
57 * by hibernate_page_list_setall(), avoiding having to find arch dependent low level bits.
58 * The image header and block list are written. The header includes the second file extent so
59 * only the header block is needed to read the file, regardless of filesystem.
60 * The kernel segment "__HIB" is written uncompressed to the image. This segment of code and data
61 * (only) is used to decompress the image during wake/boot.
62 * Some additional pages are removed from the bitmaps - the buffers used for hibernation.
63 * The bitmaps are written to the image.
64 * More areas are removed from the bitmaps (after they have been written to the image) - the
65 * segment "__HIB" pages and interrupt stack.
66 * Each wired page is compressed and written and then each non-wired page. Compression and
67 * disk writes are in parallel.
68 * The image header is written to the start of the file and the polling driver closed.
69 * The machine powers down (or sleeps).
73 * - BootX sees the boot-image nvram variable containing the device and block number of the image,
74 * reads the header and if the signature is correct proceeds. The boot-image variable is cleared.
75 * - BootX reads the portion of the image used for wired pages, to memory. Its assumed this will fit
76 * in the OF memory environment, and the image is decrypted. There is no decompression in BootX,
77 * that is in the kernel's __HIB section.
78 * - BootX copies the "__HIB" section to its correct position in memory, quiesces and calls its entry
79 * hibernate_kernel_entrypoint(), passing the location of the image in memory. Translation is off,
80 * only code & data in that section is safe to call since all the other wired pages are still
81 * compressed in the image.
82 * - hibernate_kernel_entrypoint() removes pages occupied by the raw image from the page bitmaps.
83 * It uses the bitmaps to work out which pages can be uncompressed from the image to their final
84 * location directly, and copies those that can't to interim free pages. When the image has been
85 * completed, the copies are uncompressed, overwriting the wired image pages.
86 * hibernate_restore_phys_page() (in osfmk since its arch dependent, but part of the "__HIB" section)
87 * is used to get pages into place for 64bit.
88 * - the reset vector is called (at least on ppc), the kernel proceeds on a normal wake, with some
89 * changes conditional on the per proc flag - before VM is turned on the boot cpu, all mappings
90 * are removed from the software strutures, and the hash table is reinitialized.
91 * - After the platform CPU init code is called, hibernate_machine_init() is called to restore the rest
92 * of memory, using the polled mode driver, before other threads can run or any devices are turned on.
93 * This reduces the memory usage for BootX and allows decompression in parallel with disk reads,
94 * for the remaining non wired pages.
95 * - The polling driver is closed down and regular wake proceeds. When the kernel calls iokit to wake
96 * (normal execution context) hibernate_teardown() in osmfk is called to release any memory, the file
101 * IOHibernateSystemSleep() finds a polled mode interface to the ATA controller via a property in the
102 * registry, specifying an object of calls IOPolledInterface.
104 * Before the system goes to sleep it searches from the IOMedia object (could be a filesystem or
105 * partition) that the image is going to live, looking for polled interface properties. If it finds
106 * one the IOMedia object is passed to a "probe" call for the interface to accept or reject. All the
107 * interfaces found are kept in an ordered list.
109 * There is an Open/Close pair of calls made to each of the interfaces at various stages since there are
110 * few different contexts things happen in:
112 * - there is an Open/Close (Preflight) made before any part of the system has slept (I/O is all
113 * up and running) and after wake - this is safe to allocate memory and do anything. The device
114 * ignores sleep requests from that point since its a waste of time if it goes to sleep and
115 * immediately wakes back up for the image write.
117 * - there is an Open/Close (BeforeSleep) pair made around the image write operations that happen
118 * immediately before sleep. These can't block or allocate memory - the I/O system is asleep apart
119 * from the low level bits (motherboard I/O etc). There is only one thread running. The close can be
120 * used to flush and set the disk to sleep.
122 * - there is an Open/Close (AfterSleep) pair made around the image read operations that happen
123 * immediately after sleep. These can't block or allocate memory. This is happening after the platform
124 * expert has woken the low level bits of the system, but most of the I/O system has not. There is only
125 * one thread running.
127 * For the actual I/O, all the ops are with respect to a single IOMemoryDescriptor that was passed
128 * (prepared) to the Preflight Open() call. There is a read/write op, buffer offset to the IOMD for
129 * the data, an offset to the disk and length (block aligned 64 bit numbers), and completion callback.
130 * Each I/O is async but only one is ever outstanding. The polled interface has a checkForWork call
131 * that is called for the hardware to check for events, and complete the I/O via the callback.
132 * The hibernate path uses the same transfer constraints the regular cluster I/O path in BSD uses
133 * to restrict I/O ops.
136 #include <sys/systm.h>
138 #include <IOKit/IOWorkLoop.h>
139 #include <IOKit/IOCommandGate.h>
140 #include <IOKit/IOTimerEventSource.h>
141 #include <IOKit/IOPlatformExpert.h>
142 #include <IOKit/IOKitDebug.h>
143 #include <IOKit/IOTimeStamp.h>
144 #include <IOKit/pwr_mgt/RootDomain.h>
145 #include <IOKit/pwr_mgt/IOPMPrivate.h>
146 #include <IOKit/IOMessage.h>
147 #include <IOKit/IODeviceTreeSupport.h>
148 #include <IOKit/IOBSD.h>
149 #include <IOKit/IOKitKeysPrivate.h>
150 #include "RootDomainUserClient.h"
151 #include <IOKit/pwr_mgt/IOPowerConnection.h>
152 #include "IOPMPowerStateQueue.h"
153 #include <IOKit/IOBufferMemoryDescriptor.h>
154 #include <IOKit/AppleKeyStoreInterface.h>
155 #include <libkern/crypto/aes.h>
158 #include <sys/conf.h>
159 #include <sys/stat.h>
160 #include <sys/fcntl.h> // (FWRITE, ...)
161 #include <sys/sysctl.h>
162 #include <sys/kdebug.h>
165 #include <IOKit/IOHibernatePrivate.h>
166 #include <IOKit/IOPolledInterface.h>
167 #include <IOKit/IONVRAM.h>
168 #include "IOHibernateInternal.h"
169 #include <vm/WKdm_new.h>
170 #include <vm/vm_protos.h>
171 #include "IOKitKernelInternal.h"
172 #include <pexpert/device_tree.h>
174 #include <machine/pal_routines.h>
175 #include <machine/pal_hibernate.h>
176 #include <i386/tsc.h>
177 #include <i386/cpuid.h>
178 #include <san/kasan.h>
180 extern "C" addr64_t
kvtophys(vm_offset_t va
);
181 extern "C" ppnum_t
pmap_find_phys(pmap_t pmap
, addr64_t va
);
183 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
185 #define DISABLE_TRIM 0
186 #define TRIM_DELAY 25000
188 extern unsigned int save_kdebug_enable
;
189 extern uint32_t gIOHibernateState
;
190 uint32_t gIOHibernateMode
;
191 static char gIOHibernateBootSignature
[256 + 1];
192 static char gIOHibernateFilename
[MAXPATHLEN
+ 1];
194 static uuid_string_t gIOHibernateBridgeBootSessionUUIDString
;
196 static uint32_t gIOHibernateFreeRatio
= 0; // free page target (percent)
197 uint32_t gIOHibernateFreeTime
= 0 * 1000; // max time to spend freeing pages (ms)
198 static uint64_t gIOHibernateCompression
= 0x80; // default compression 50%
199 boolean_t gIOHibernateStandbyDisabled
;
201 static IODTNVRAM
* gIOOptionsEntry
;
202 static IORegistryEntry
* gIOChosenEntry
;
204 static const OSSymbol
* gIOHibernateBootImageKey
;
205 static const OSSymbol
* gIOHibernateBootSignatureKey
;
206 static const OSSymbol
* gIOBridgeBootSessionUUIDKey
;
208 #if defined(__i386__) || defined(__x86_64__)
210 static const OSSymbol
* gIOHibernateRTCVariablesKey
;
211 static const OSSymbol
* gIOHibernateBoot0082Key
;
212 static const OSSymbol
* gIOHibernateBootNextKey
;
213 static OSData
* gIOHibernateBoot0082Data
;
214 static OSData
* gIOHibernateBootNextData
;
215 static OSObject
* gIOHibernateBootNextSave
;
217 #endif /* defined(__i386__) || defined(__x86_64__) */
219 static IOLock
* gFSLock
;
221 static thread_call_t gIOHibernateTrimCalloutEntry
;
222 static IOPolledFileIOVars gFileVars
;
223 static IOHibernateVars gIOHibernateVars
;
224 static IOPolledFileCryptVars gIOHibernateCryptWakeContext
;
225 static hibernate_graphics_t _hibernateGraphics
;
226 static hibernate_graphics_t
* gIOHibernateGraphicsInfo
= &_hibernateGraphics
;
227 static hibernate_statistics_t _hibernateStats
;
228 static hibernate_statistics_t
* gIOHibernateStats
= &_hibernateStats
;
238 static IOReturn
IOHibernateDone(IOHibernateVars
* vars
);
239 static IOReturn
IOWriteExtentsToFile(IOPolledFileIOVars
* vars
, uint32_t signature
);
240 static void IOSetBootImageNVRAM(OSData
* data
);
241 static void IOHibernateSystemPostWakeTrim(void * p1
, void * p2
);
243 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
245 enum { kDefaultIOSize
= 128 * 1024 };
246 enum { kVideoMapSize
= 80 * 1024 * 1024 };
248 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
250 // copy from phys addr to MD
253 IOMemoryDescriptorWriteFromPhysical(IOMemoryDescriptor
* md
,
254 IOByteCount offset
, addr64_t bytes
, IOByteCount length
)
256 addr64_t srcAddr
= bytes
;
257 IOByteCount remaining
;
259 remaining
= length
= min(length
, md
->getLength() - offset
);
260 while (remaining
) { // (process another target segment?)
264 dstAddr64
= md
->getPhysicalSegment(offset
, &dstLen
, kIOMemoryMapperNone
);
269 // Clip segment length to remaining
270 if (dstLen
> remaining
) {
275 bcopy_phys(srcAddr
, dstAddr64
, dstLen
);
277 copypv(srcAddr
, dstAddr64
, dstLen
,
278 cppvPsnk
| cppvFsnk
| cppvNoRefSrc
| cppvNoModSnk
| cppvKmap
);
287 return remaining
? kIOReturnUnderrun
: kIOReturnSuccess
;
290 // copy from MD to phys addr
293 IOMemoryDescriptorReadToPhysical(IOMemoryDescriptor
* md
,
294 IOByteCount offset
, addr64_t bytes
, IOByteCount length
)
296 addr64_t dstAddr
= bytes
;
297 IOByteCount remaining
;
299 remaining
= length
= min(length
, md
->getLength() - offset
);
300 while (remaining
) { // (process another target segment?)
304 srcAddr64
= md
->getPhysicalSegment(offset
, &dstLen
, kIOMemoryMapperNone
);
309 // Clip segment length to remaining
310 if (dstLen
> remaining
) {
315 bcopy_phys(srcAddr64
, dstAddr
, dstLen
);
317 copypv(srcAddr
, dstAddr64
, dstLen
,
318 cppvPsnk
| cppvFsnk
| cppvNoRefSrc
| cppvNoModSnk
| cppvKmap
);
327 return remaining
? kIOReturnUnderrun
: kIOReturnSuccess
;
330 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
333 hibernate_set_page_state(hibernate_page_list_t
* page_list
, hibernate_page_list_t
* page_list_wired
,
334 vm_offset_t ppnum
, vm_offset_t count
, uint32_t kind
)
338 case kIOHibernatePageStateUnwiredSave
:
340 for (; ppnum
< count
; ppnum
++) {
341 hibernate_page_bitset(page_list
, FALSE
, ppnum
);
342 hibernate_page_bitset(page_list_wired
, TRUE
, ppnum
);
345 case kIOHibernatePageStateWiredSave
:
347 for (; ppnum
< count
; ppnum
++) {
348 hibernate_page_bitset(page_list
, FALSE
, ppnum
);
349 hibernate_page_bitset(page_list_wired
, FALSE
, ppnum
);
352 case kIOHibernatePageStateFree
:
354 for (; ppnum
< count
; ppnum
++) {
355 hibernate_page_bitset(page_list
, TRUE
, ppnum
);
356 hibernate_page_bitset(page_list_wired
, TRUE
, ppnum
);
360 panic("hibernate_set_page_state");
365 hibernate_page_list_iterate(hibernate_page_list_t
* list
, vm_offset_t
* pPage
)
367 uint32_t page
= *pPage
;
369 hibernate_bitmap_t
* bitmap
;
371 while ((bitmap
= hibernate_page_bitmap_pin(list
, &page
))) {
372 count
= hibernate_page_bitmap_count(bitmap
, TRUE
, page
);
377 if (page
<= bitmap
->last_page
) {
384 count
= hibernate_page_bitmap_count(bitmap
, FALSE
, page
);
392 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
395 IOHibernateSystemSleep(void)
402 bool dsSSD
, vmflush
, swapPinned
;
403 IOHibernateVars
* vars
;
404 uint64_t setFileSize
= 0;
406 gIOHibernateState
= kIOHibernateStateInactive
;
408 gIOHibernateDebugFlags
= 0;
409 if (kIOLogHibernate
& gIOKitDebug
) {
410 gIOHibernateDebugFlags
|= kIOHibernateDebugRestoreLogs
;
413 if (IOService::getPMRootDomain()->getHibernateSettings(
414 &gIOHibernateMode
, &gIOHibernateFreeRatio
, &gIOHibernateFreeTime
)) {
415 if (kIOHibernateModeSleep
& gIOHibernateMode
) {
416 // default to discard clean for safe sleep
417 gIOHibernateMode
^= (kIOHibernateModeDiscardCleanInactive
418 | kIOHibernateModeDiscardCleanActive
);
422 if ((obj
= IOService::getPMRootDomain()->copyProperty(kIOHibernateFileKey
))) {
423 if ((str
= OSDynamicCast(OSString
, obj
))) {
424 strlcpy(gIOHibernateFilename
, str
->getCStringNoCopy(),
425 sizeof(gIOHibernateFilename
));
430 if (!gIOHibernateMode
|| !gIOHibernateFilename
[0]) {
431 return kIOReturnUnsupported
;
434 HIBLOG("hibernate image path: %s\n", gIOHibernateFilename
);
436 vars
= IONew(IOHibernateVars
, 1);
438 return kIOReturnNoMemory
;
440 bzero(vars
, sizeof(*vars
));
443 if (!gIOHibernateTrimCalloutEntry
) {
444 gIOHibernateTrimCalloutEntry
= thread_call_allocate(&IOHibernateSystemPostWakeTrim
, &gFSLock
);
446 IOHibernateSystemPostWakeTrim(NULL
, NULL
);
447 thread_call_cancel(gIOHibernateTrimCalloutEntry
);
448 if (kFSIdle
!= gFSState
) {
449 HIBLOG("hibernate file busy\n");
450 IOLockUnlock(gFSLock
);
451 IODelete(vars
, IOHibernateVars
, 1);
452 return kIOReturnBusy
;
454 gFSState
= kFSOpening
;
455 IOLockUnlock(gFSLock
);
459 vars
->srcBuffer
= IOBufferMemoryDescriptor::withOptions(kIODirectionOutIn
,
460 2 * page_size
+ WKdm_SCRATCH_BUF_SIZE_INTERNAL
, page_size
);
462 vars
->handoffBuffer
= IOBufferMemoryDescriptor::withOptions(kIODirectionOutIn
,
463 ptoa_64(gIOHibernateHandoffPageCount
), page_size
);
465 if (!vars
->srcBuffer
|| !vars
->handoffBuffer
) {
466 err
= kIOReturnNoMemory
;
470 if ((obj
= IOService::getPMRootDomain()->copyProperty(kIOHibernateFileMinSizeKey
))) {
471 if ((num
= OSDynamicCast(OSNumber
, obj
))) {
472 vars
->fileMinSize
= num
->unsigned64BitValue();
476 if ((obj
= IOService::getPMRootDomain()->copyProperty(kIOHibernateFileMaxSizeKey
))) {
477 if ((num
= OSDynamicCast(OSNumber
, obj
))) {
478 vars
->fileMaxSize
= num
->unsigned64BitValue();
483 boolean_t encryptedswap
= true;
485 AbsoluteTime startTime
, endTime
;
488 bzero(gIOHibernateCurrentHeader
, sizeof(IOHibernateImageHeader
));
489 gIOHibernateCurrentHeader
->debugFlags
= gIOHibernateDebugFlags
;
490 gIOHibernateCurrentHeader
->signature
= kIOHibernateHeaderInvalidSignature
;
492 vmflush
= ((kOSBooleanTrue
== IOService::getPMRootDomain()->getProperty(kIOPMDeepSleepEnabledKey
)));
493 err
= hibernate_alloc_page_lists(&vars
->page_list
,
494 &vars
->page_list_wired
,
495 &vars
->page_list_pal
);
496 if (KERN_SUCCESS
!= err
) {
497 HIBLOG("%s err, hibernate_alloc_page_lists return 0x%x\n", __FUNCTION__
, err
);
501 err
= hibernate_pin_swap(TRUE
);
502 if (KERN_SUCCESS
!= err
) {
503 HIBLOG("%s error, hibernate_pin_swap return 0x%x\n", __FUNCTION__
, err
);
508 if (vars
->fileMinSize
|| (kIOHibernateModeFileResize
& gIOHibernateMode
)) {
509 hibernate_page_list_setall(vars
->page_list
,
510 vars
->page_list_wired
,
512 true /* preflight */,
513 vmflush
/* discard */,
515 PE_Video consoleInfo
;
516 bzero(&consoleInfo
, sizeof(consoleInfo
));
517 IOService::getPlatform()->getConsoleInfo(&consoleInfo
);
519 // estimate: 6% increase in pages compressed
520 // screen preview 2 images compressed 0%
521 setFileSize
= ((ptoa_64((106 * pageCount
) / 100) * gIOHibernateCompression
) >> 8)
522 + vars
->page_list
->list_size
523 + (consoleInfo
.v_width
* consoleInfo
.v_height
* 8);
524 enum { setFileRound
= 1024 * 1024ULL };
525 setFileSize
= ((setFileSize
+ setFileRound
) & ~(setFileRound
- 1));
527 HIBLOG("hibernate_page_list_setall preflight pageCount %d est comp %qd setfile %qd min %qd\n",
528 pageCount
, (100ULL * gIOHibernateCompression
) >> 8,
529 setFileSize
, vars
->fileMinSize
);
531 if (!(kIOHibernateModeFileResize
& gIOHibernateMode
)
532 && (setFileSize
< vars
->fileMinSize
)) {
533 setFileSize
= vars
->fileMinSize
;
537 vars
->volumeCryptKeySize
= sizeof(vars
->volumeCryptKey
);
538 err
= IOPolledFileOpen(gIOHibernateFilename
,
539 (kIOPolledFileCreate
| kIOPolledFileHibernate
),
541 gIOHibernateCurrentHeader
, sizeof(gIOHibernateCurrentHeader
),
542 &vars
->fileVars
, &nvramData
,
543 &vars
->volumeCryptKey
[0], &vars
->volumeCryptKeySize
);
545 if (KERN_SUCCESS
!= err
) {
547 if (kFSOpening
!= gFSState
) {
548 err
= kIOReturnTimeout
;
550 IOLockUnlock(gFSLock
);
553 if (KERN_SUCCESS
!= err
) {
554 HIBLOG("IOPolledFileOpen(%x)\n", err
);
558 // write extents for debug data usage in EFI
559 IOWriteExtentsToFile(vars
->fileVars
, kIOHibernateHeaderOpenSignature
);
561 err
= IOPolledFilePollersSetup(vars
->fileVars
, kIOPolledPreflightState
);
562 if (KERN_SUCCESS
!= err
) {
566 clock_get_uptime(&startTime
);
567 err
= hibernate_setup(gIOHibernateCurrentHeader
,
569 vars
->page_list
, vars
->page_list_wired
, vars
->page_list_pal
);
570 clock_get_uptime(&endTime
);
571 SUB_ABSOLUTETIME(&endTime
, &startTime
);
572 absolutetime_to_nanoseconds(endTime
, &nsec
);
574 boolean_t haveSwapPin
, hibFileSSD
;
575 haveSwapPin
= vm_swap_files_pinned();
577 hibFileSSD
= (kIOPolledFileSSD
& vars
->fileVars
->flags
);
579 HIBLOG("hibernate_setup(%d) took %qd ms, swapPin(%d) ssd(%d)\n",
580 err
, nsec
/ 1000000ULL,
581 haveSwapPin
, hibFileSSD
);
582 if (KERN_SUCCESS
!= err
) {
586 gIOHibernateStandbyDisabled
= ((!haveSwapPin
|| !hibFileSSD
));
588 dsSSD
= ((0 != (kIOPolledFileSSD
& vars
->fileVars
->flags
))
589 && (kOSBooleanTrue
== IOService::getPMRootDomain()->getProperty(kIOPMDeepSleepEnabledKey
)));
592 gIOHibernateCurrentHeader
->options
|= kIOHibernateOptionSSD
| kIOHibernateOptionColor
;
594 gIOHibernateCurrentHeader
->options
|= kIOHibernateOptionProgress
;
598 #if defined(__i386__) || defined(__x86_64__)
599 if (vars
->volumeCryptKeySize
&&
600 (kOSBooleanTrue
!= IOService::getPMRootDomain()->getProperty(kIOPMDestroyFVKeyOnStandbyKey
))) {
601 uintptr_t smcVars
[2];
602 smcVars
[0] = vars
->volumeCryptKeySize
;
603 smcVars
[1] = (uintptr_t)(void *) &gIOHibernateVars
.volumeCryptKey
[0];
605 IOService::getPMRootDomain()->setProperty(kIOHibernateSMCVariablesKey
, smcVars
, sizeof(smcVars
));
606 bzero(smcVars
, sizeof(smcVars
));
611 if (encryptedswap
|| vars
->volumeCryptKeySize
) {
612 gIOHibernateMode
^= kIOHibernateModeEncrypt
;
615 if (kIOHibernateOptionProgress
& gIOHibernateCurrentHeader
->options
) {
616 vars
->videoAllocSize
= kVideoMapSize
;
617 if (KERN_SUCCESS
!= kmem_alloc_pageable(kernel_map
, &vars
->videoMapping
, vars
->videoAllocSize
, VM_KERN_MEMORY_IOKIT
)) {
618 vars
->videoMapping
= 0;
622 // generate crypt keys
623 for (uint32_t i
= 0; i
< sizeof(vars
->wiredCryptKey
); i
++) {
624 vars
->wiredCryptKey
[i
] = random();
626 for (uint32_t i
= 0; i
< sizeof(vars
->cryptKey
); i
++) {
627 vars
->cryptKey
[i
] = random();
632 IOSetBootImageNVRAM(nvramData
);
633 nvramData
->release();
635 #if defined(__i386__) || defined(__x86_64__)
637 struct AppleRTCHibernateVars
{
638 uint8_t signature
[4];
640 uint8_t booterSignature
[20];
641 uint8_t wiredCryptKey
[16];
643 AppleRTCHibernateVars rtcVars
;
646 rtcVars
.signature
[0] = 'A';
647 rtcVars
.signature
[1] = 'A';
648 rtcVars
.signature
[2] = 'P';
649 rtcVars
.signature
[3] = 'L';
650 rtcVars
.revision
= 1;
651 bcopy(&vars
->wiredCryptKey
[0], &rtcVars
.wiredCryptKey
[0], sizeof(rtcVars
.wiredCryptKey
));
654 && (data
= OSDynamicCast(OSData
, gIOChosenEntry
->getProperty(gIOHibernateBootSignatureKey
)))
655 && (sizeof(rtcVars
.booterSignature
) <= data
->getLength())) {
656 bcopy(data
->getBytesNoCopy(), &rtcVars
.booterSignature
[0], sizeof(rtcVars
.booterSignature
));
657 } else if (gIOHibernateBootSignature
[0]) {
660 uint32_t in
, out
, digits
;
661 for (in
= out
= digits
= 0;
662 (c
= gIOHibernateBootSignature
[in
]) && (in
< sizeof(gIOHibernateBootSignature
));
664 if ((c
>= 'a') && (c
<= 'f')) {
666 } else if ((c
>= 'A') && (c
<= 'F')) {
668 } else if ((c
>= '0') && (c
<= '9')) {
672 out
= digits
= value
= 0;
676 value
= (value
<< 4) | c
;
678 rtcVars
.booterSignature
[out
++] = value
;
679 if (out
>= sizeof(rtcVars
.booterSignature
)) {
686 #if DEBUG || DEVELOPMENT
687 if (kIOLogHibernate
& gIOKitDebug
) {
688 IOKitKernelLogBuffer("H> rtc:",
689 &rtcVars
, sizeof(rtcVars
), &kprintf
);
691 #endif /* DEBUG || DEVELOPMENT */
693 data
= OSData::withBytes(&rtcVars
, sizeof(rtcVars
));
695 if (gIOHibernateRTCVariablesKey
) {
696 IOService::getPMRootDomain()->setProperty(gIOHibernateRTCVariablesKey
, data
);
700 if (gIOChosenEntry
&& gIOOptionsEntry
) {
701 data
= OSDynamicCast(OSData
, gIOChosenEntry
->getProperty(kIOHibernateMachineSignatureKey
));
703 gIOHibernateCurrentHeader
->machineSignature
= *((UInt32
*)data
->getBytesNoCopy());
706 if (!gIOHibernateBoot0082Data
) {
707 OSData
* fileData
= NULL
;
708 data
= OSDynamicCast(OSData
, gIOChosenEntry
->getProperty("boot-device-path"));
709 if (data
&& data
->getLength() >= 4) {
710 fileData
= OSDynamicCast(OSData
, gIOChosenEntry
->getProperty("boot-file-path"));
713 // AppleNVRAM_EFI_LOAD_OPTION
716 uint16_t FilePathLength
;
719 loadOptionHeader
.Attributes
= 1;
720 loadOptionHeader
.FilePathLength
= data
->getLength();
721 loadOptionHeader
.Desc
= 0;
723 loadOptionHeader
.FilePathLength
-= 4;
724 loadOptionHeader
.FilePathLength
+= fileData
->getLength();
726 gIOHibernateBoot0082Data
= OSData::withCapacity(sizeof(loadOptionHeader
) + loadOptionHeader
.FilePathLength
);
727 if (gIOHibernateBoot0082Data
) {
728 gIOHibernateBoot0082Data
->appendBytes(&loadOptionHeader
, sizeof(loadOptionHeader
));
730 gIOHibernateBoot0082Data
->appendBytes(data
->getBytesNoCopy(), data
->getLength() - 4);
731 gIOHibernateBoot0082Data
->appendBytes(fileData
);
733 gIOHibernateBoot0082Data
->appendBytes(data
);
738 if (!gIOHibernateBootNextData
) {
739 uint16_t bits
= 0x0082;
740 gIOHibernateBootNextData
= OSData::withBytes(&bits
, sizeof(bits
));
743 #if DEBUG || DEVELOPMENT
744 if (kIOLogHibernate
& gIOKitDebug
) {
745 IOKitKernelLogBuffer("H> bootnext:",
746 gIOHibernateBoot0082Data
->getBytesNoCopy(), gIOHibernateBoot0082Data
->getLength(), &kprintf
);
748 #endif /* DEBUG || DEVELOPMENT */
749 if (gIOHibernateBoot0082Key
&& gIOHibernateBoot0082Data
&& gIOHibernateBootNextKey
&& gIOHibernateBootNextData
) {
750 gIOHibernateBootNextSave
= gIOOptionsEntry
->copyProperty(gIOHibernateBootNextKey
);
751 gIOOptionsEntry
->setProperty(gIOHibernateBoot0082Key
, gIOHibernateBoot0082Data
);
752 gIOOptionsEntry
->setProperty(gIOHibernateBootNextKey
, gIOHibernateBootNextData
);
757 #endif /* !i386 && !x86_64 */
761 hibernate_pin_swap(FALSE
);
765 if ((kIOReturnSuccess
== err
) && (kFSOpening
!= gFSState
)) {
766 HIBLOG("hibernate file close due timeout\n");
767 err
= kIOReturnTimeout
;
769 if (kIOReturnSuccess
== err
) {
770 gFSState
= kFSOpened
;
771 gIOHibernateVars
= *vars
;
772 gFileVars
= *vars
->fileVars
;
773 gFileVars
.allocated
= false;
774 gIOHibernateVars
.fileVars
= &gFileVars
;
775 gIOHibernateCurrentHeader
->signature
= kIOHibernateHeaderSignature
;
776 gIOHibernateState
= kIOHibernateStateHibernating
;
778 #if DEBUG || DEVELOPMENT
779 if (kIOLogHibernate
& gIOKitDebug
) {
780 OSData
* data
= OSDynamicCast(OSData
, IOService::getPMRootDomain()->getProperty(kIOHibernateSMCVariablesKey
));
782 uintptr_t * smcVars
= (typeof(smcVars
))data
->getBytesNoCopy();
783 IOKitKernelLogBuffer("H> smc:",
784 (const void *)smcVars
[1], smcVars
[0], &kprintf
);
787 #endif /* DEBUG || DEVELOPMENT */
789 IOPolledFileIOVars
* fileVars
= vars
->fileVars
;
790 IOHibernateDone(vars
);
791 IOPolledFileClose(&fileVars
,
795 0, NULL
, 0, sizeof(IOHibernateImageHeader
), setFileSize
);
799 IOLockUnlock(gFSLock
);
801 if (vars
->fileVars
) {
802 IODelete(vars
->fileVars
, IOPolledFileIOVars
, 1);
804 IODelete(vars
, IOHibernateVars
, 1);
809 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
812 IOSetBootImageNVRAM(OSData
* data
)
814 IORegistryEntry
* regEntry
;
816 if (!gIOOptionsEntry
) {
817 regEntry
= IORegistryEntry::fromPath("/options", gIODTPlane
);
818 gIOOptionsEntry
= OSDynamicCast(IODTNVRAM
, regEntry
);
819 if (regEntry
&& !gIOOptionsEntry
) {
823 if (gIOOptionsEntry
&& gIOHibernateBootImageKey
) {
825 gIOOptionsEntry
->setProperty(gIOHibernateBootImageKey
, data
);
826 #if DEBUG || DEVELOPMENT
827 if (kIOLogHibernate
& gIOKitDebug
) {
828 IOKitKernelLogBuffer("H> boot-image:",
829 data
->getBytesNoCopy(), data
->getLength(), &kprintf
);
831 #endif /* DEBUG || DEVELOPMENT */
833 gIOOptionsEntry
->removeProperty(gIOHibernateBootImageKey
);
834 gIOOptionsEntry
->sync();
839 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
841 * Writes header to disk with signature, block size and file extents data.
842 * If there are more than 2 extents, then they are written on second block.
845 IOWriteExtentsToFile(IOPolledFileIOVars
* vars
, uint32_t signature
)
847 IOHibernateImageHeader hdr
;
849 IOReturn err
= kIOReturnSuccess
;
851 IOPolledFileExtent
* fileExtents
;
853 fileExtents
= (typeof(fileExtents
))vars
->fileExtents
->getBytesNoCopy();
855 memset(&hdr
, 0, sizeof(IOHibernateImageHeader
));
856 count
= vars
->fileExtents
->getLength();
857 if (count
> sizeof(hdr
.fileExtentMap
)) {
858 hdr
.fileExtentMapSize
= count
;
859 count
= sizeof(hdr
.fileExtentMap
);
861 hdr
.fileExtentMapSize
= sizeof(hdr
.fileExtentMap
);
864 bcopy(fileExtents
, &hdr
.fileExtentMap
[0], count
);
866 // copy file block extent list if larger than header
867 if (hdr
.fileExtentMapSize
> sizeof(hdr
.fileExtentMap
)) {
868 count
= hdr
.fileExtentMapSize
- sizeof(hdr
.fileExtentMap
);
869 rc
= kern_write_file(vars
->fileRef
, vars
->blockSize
,
870 (caddr_t
)(((uint8_t *)fileExtents
) + sizeof(hdr
.fileExtentMap
)),
871 count
, IO_SKIP_ENCRYPTION
);
873 HIBLOG("kern_write_file returned %d\n", rc
);
874 err
= kIOReturnIOError
;
878 hdr
.signature
= signature
;
879 hdr
.deviceBlockSize
= vars
->blockSize
;
881 rc
= kern_write_file(vars
->fileRef
, 0, (char *)&hdr
, sizeof(hdr
), IO_SKIP_ENCRYPTION
);
883 HIBLOG("kern_write_file returned %d\n", rc
);
884 err
= kIOReturnIOError
;
892 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
894 DECLARE_IOHIBERNATEPROGRESSALPHA
897 ProgressInit(hibernate_graphics_t
* display
, uint8_t * screen
, uint8_t * saveunder
, uint32_t savelen
)
899 uint32_t rowBytes
, pixelShift
;
902 uint32_t alpha
, in
, color
, result
;
904 uint32_t saveindex
[kIOHibernateProgressCount
] = { 0 };
906 rowBytes
= display
->rowBytes
;
907 pixelShift
= display
->depth
>> 4;
908 if (pixelShift
< 1) {
912 screen
+= ((display
->width
913 - kIOHibernateProgressCount
* (kIOHibernateProgressWidth
+ kIOHibernateProgressSpacing
)) << (pixelShift
- 1))
914 + (display
->height
- kIOHibernateProgressOriginY
- kIOHibernateProgressHeight
) * rowBytes
;
916 for (y
= 0; y
< kIOHibernateProgressHeight
; y
++) {
917 out
= screen
+ y
* rowBytes
;
918 for (blob
= 0; blob
< kIOHibernateProgressCount
; blob
++) {
919 color
= blob
? kIOHibernateProgressDarkGray
: kIOHibernateProgressMidGray
;
920 for (x
= 0; x
< kIOHibernateProgressWidth
; x
++) {
921 alpha
= gIOHibernateProgressAlpha
[y
][x
];
925 if (1 == pixelShift
) {
926 in
= *((uint16_t *)out
) & 0x1f; // 16
927 in
= (in
<< 3) | (in
>> 2);
929 in
= *((uint32_t *)out
) & 0xff; // 32
931 saveunder
[blob
* kIOHibernateProgressSaveUnderSize
+ saveindex
[blob
]++] = in
;
932 result
= ((255 - alpha
) * in
+ alpha
* result
+ 0xff) >> 8;
934 if (1 == pixelShift
) {
936 *((uint16_t *)out
) = (result
<< 10) | (result
<< 5) | result
; // 16
938 *((uint32_t *)out
) = (result
<< 16) | (result
<< 8) | result
; // 32
941 out
+= (1 << pixelShift
);
943 out
+= (kIOHibernateProgressSpacing
<< pixelShift
);
950 ProgressUpdate(hibernate_graphics_t
* display
, uint8_t * screen
, int32_t firstBlob
, int32_t select
)
952 uint32_t rowBytes
, pixelShift
;
954 int32_t blob
, lastBlob
;
955 uint32_t alpha
, in
, color
, result
;
957 uint32_t saveindex
[kIOHibernateProgressCount
] = { 0 };
959 pixelShift
= display
->depth
>> 4;
960 if (pixelShift
< 1) {
964 rowBytes
= display
->rowBytes
;
966 screen
+= ((display
->width
967 - kIOHibernateProgressCount
* (kIOHibernateProgressWidth
+ kIOHibernateProgressSpacing
)) << (pixelShift
- 1))
968 + (display
->height
- kIOHibernateProgressOriginY
- kIOHibernateProgressHeight
) * rowBytes
;
970 lastBlob
= (select
< kIOHibernateProgressCount
) ? select
: (kIOHibernateProgressCount
- 1);
972 screen
+= (firstBlob
* (kIOHibernateProgressWidth
+ kIOHibernateProgressSpacing
)) << pixelShift
;
974 for (y
= 0; y
< kIOHibernateProgressHeight
; y
++) {
975 out
= screen
+ y
* rowBytes
;
976 for (blob
= firstBlob
; blob
<= lastBlob
; blob
++) {
977 color
= (blob
< select
) ? kIOHibernateProgressLightGray
: kIOHibernateProgressMidGray
;
978 for (x
= 0; x
< kIOHibernateProgressWidth
; x
++) {
979 alpha
= gIOHibernateProgressAlpha
[y
][x
];
983 in
= display
->progressSaveUnder
[blob
][saveindex
[blob
]++];
984 result
= ((255 - alpha
) * in
+ alpha
* result
+ 0xff) / 255;
986 if (1 == pixelShift
) {
988 *((uint16_t *)out
) = (result
<< 10) | (result
<< 5) | result
; // 16
990 *((uint32_t *)out
) = (result
<< 16) | (result
<< 8) | result
; // 32
993 out
+= (1 << pixelShift
);
995 out
+= (kIOHibernateProgressSpacing
<< pixelShift
);
1000 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1003 IOHibernateIOKitSleep(void)
1005 IOReturn ret
= kIOReturnSuccess
;
1006 IOLockLock(gFSLock
);
1007 if (kFSOpening
== gFSState
) {
1008 gFSState
= kFSTimedOut
;
1009 HIBLOG("hibernate file open timed out\n");
1010 ret
= kIOReturnTimeout
;
1012 IOLockUnlock(gFSLock
);
1016 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1019 IOHibernateSystemHasSlept(void)
1021 IOReturn ret
= kIOReturnSuccess
;
1022 IOHibernateVars
* vars
= &gIOHibernateVars
;
1023 OSObject
* obj
= NULL
;
1026 IOLockLock(gFSLock
);
1027 if ((kFSOpened
!= gFSState
) && gIOHibernateMode
) {
1028 ret
= kIOReturnTimeout
;
1030 IOLockUnlock(gFSLock
);
1031 if (kIOReturnSuccess
!= ret
) {
1035 if (gIOHibernateMode
) {
1036 obj
= IOService::getPMRootDomain()->copyProperty(kIOHibernatePreviewBufferKey
);
1038 vars
->previewBuffer
= OSDynamicCast(IOMemoryDescriptor
, obj
);
1039 if (obj
&& !vars
->previewBuffer
) {
1043 vars
->consoleMapping
= NULL
;
1044 if (vars
->previewBuffer
&& (kIOReturnSuccess
!= vars
->previewBuffer
->prepare())) {
1045 vars
->previewBuffer
->release();
1046 vars
->previewBuffer
= NULL
;
1049 if ((kIOHibernateOptionProgress
& gIOHibernateCurrentHeader
->options
)
1050 && vars
->previewBuffer
1051 && (data
= OSDynamicCast(OSData
,
1052 IOService::getPMRootDomain()->getProperty(kIOHibernatePreviewActiveKey
)))) {
1053 UInt32 flags
= *((UInt32
*)data
->getBytesNoCopy());
1054 HIBPRINT("kIOHibernatePreviewActiveKey %08lx\n", (long)flags
);
1056 IOService::getPMRootDomain()->removeProperty(kIOHibernatePreviewActiveKey
);
1058 if (kIOHibernatePreviewUpdates
& flags
) {
1059 PE_Video consoleInfo
;
1060 hibernate_graphics_t
* graphicsInfo
= gIOHibernateGraphicsInfo
;
1062 IOService::getPlatform()->getConsoleInfo(&consoleInfo
);
1064 graphicsInfo
->width
= consoleInfo
.v_width
;
1065 graphicsInfo
->height
= consoleInfo
.v_height
;
1066 graphicsInfo
->rowBytes
= consoleInfo
.v_rowBytes
;
1067 graphicsInfo
->depth
= consoleInfo
.v_depth
;
1068 vars
->consoleMapping
= (uint8_t *) consoleInfo
.v_baseAddr
;
1070 HIBPRINT("video %p %d %d %d\n",
1071 vars
->consoleMapping
, graphicsInfo
->depth
,
1072 graphicsInfo
->width
, graphicsInfo
->height
);
1073 if (vars
->consoleMapping
) {
1074 ProgressInit(graphicsInfo
, vars
->consoleMapping
,
1075 &graphicsInfo
->progressSaveUnder
[0][0], sizeof(graphicsInfo
->progressSaveUnder
));
1080 if (gIOOptionsEntry
) {
1081 gIOOptionsEntry
->sync();
1087 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1089 static DeviceTreeNode
*
1090 MergeDeviceTree(DeviceTreeNode
* entry
, IORegistryEntry
* regEntry
)
1092 DeviceTreeNodeProperty
* prop
;
1093 DeviceTreeNode
* child
;
1094 IORegistryEntry
* childRegEntry
;
1095 const char * nameProp
;
1096 unsigned int propLen
, idx
;
1098 prop
= (DeviceTreeNodeProperty
*) (entry
+ 1);
1099 for (idx
= 0; idx
< entry
->nProperties
; idx
++) {
1100 if (regEntry
&& (0 != strcmp("name", prop
->name
))) {
1101 regEntry
->setProperty((const char *) prop
->name
, (void *) (prop
+ 1), prop
->length
);
1102 // HIBPRINT("%s: %s, %d\n", regEntry->getName(), prop->name, prop->length);
1104 prop
= (DeviceTreeNodeProperty
*) (((uintptr_t)(prop
+ 1)) + ((prop
->length
+ 3) & ~3));
1107 child
= (DeviceTreeNode
*) prop
;
1108 for (idx
= 0; idx
< entry
->nChildren
; idx
++) {
1109 if (kSuccess
!= DTGetProperty(child
, "name", (void **) &nameProp
, &propLen
)) {
1112 childRegEntry
= regEntry
? regEntry
->childFromPath(nameProp
, gIODTPlane
) : NULL
;
1113 // HIBPRINT("%s == %p\n", nameProp, childRegEntry);
1114 child
= MergeDeviceTree(child
, childRegEntry
);
1120 IOHibernateSystemWake(void)
1122 if (kFSOpened
== gFSState
) {
1123 IOPolledFilePollersClose(gIOHibernateVars
.fileVars
, kIOPolledPostflightState
);
1124 IOHibernateDone(&gIOHibernateVars
);
1126 IOService::getPMRootDomain()->removeProperty(kIOHibernateOptionsKey
);
1127 IOService::getPMRootDomain()->removeProperty(kIOHibernateGfxStatusKey
);
1129 return kIOReturnSuccess
;
1133 IOHibernateDone(IOHibernateVars
* vars
)
1138 hibernate_teardown(vars
->page_list
, vars
->page_list_wired
, vars
->page_list_pal
);
1140 if (vars
->videoMapping
) {
1141 if (vars
->videoMapSize
) {
1143 IOUnmapPages(kernel_map
, vars
->videoMapping
, vars
->videoMapSize
);
1145 if (vars
->videoAllocSize
) {
1147 kmem_free(kernel_map
, trunc_page(vars
->videoMapping
), vars
->videoAllocSize
);
1151 if (vars
->previewBuffer
) {
1152 vars
->previewBuffer
->release();
1153 vars
->previewBuffer
= NULL
;
1156 if (kIOHibernateStateWakingFromHibernate
== gIOHibernateState
) {
1157 IOService::getPMRootDomain()->setProperty(kIOHibernateOptionsKey
,
1158 gIOHibernateCurrentHeader
->options
, 32);
1160 IOService::getPMRootDomain()->removeProperty(kIOHibernateOptionsKey
);
1163 if ((kIOHibernateStateWakingFromHibernate
== gIOHibernateState
)
1164 && (kIOHibernateGfxStatusUnknown
!= gIOHibernateGraphicsInfo
->gfxStatus
)) {
1165 IOService::getPMRootDomain()->setProperty(kIOHibernateGfxStatusKey
,
1166 &gIOHibernateGraphicsInfo
->gfxStatus
,
1167 sizeof(gIOHibernateGraphicsInfo
->gfxStatus
));
1169 IOService::getPMRootDomain()->removeProperty(kIOHibernateGfxStatusKey
);
1172 // invalidate nvram properties - (gIOOptionsEntry != 0) => nvram was touched
1174 #if defined(__i386__) || defined(__x86_64__)
1175 IOService::getPMRootDomain()->removeProperty(gIOHibernateRTCVariablesKey
);
1176 IOService::getPMRootDomain()->removeProperty(kIOHibernateSMCVariablesKey
);
1179 * Hibernate variable is written to NVRAM on platforms in which RtcRam
1180 * is not backed by coin cell. Remove Hibernate data from NVRAM.
1182 if (gIOOptionsEntry
) {
1183 if (gIOHibernateRTCVariablesKey
) {
1184 if (gIOOptionsEntry
->getProperty(gIOHibernateRTCVariablesKey
)) {
1185 gIOOptionsEntry
->removeProperty(gIOHibernateRTCVariablesKey
);
1189 if (gIOHibernateBootNextKey
) {
1190 if (gIOHibernateBootNextSave
) {
1191 gIOOptionsEntry
->setProperty(gIOHibernateBootNextKey
, gIOHibernateBootNextSave
);
1192 gIOHibernateBootNextSave
->release();
1193 gIOHibernateBootNextSave
= NULL
;
1195 gIOOptionsEntry
->removeProperty(gIOHibernateBootNextKey
);
1198 if (kIOHibernateStateWakingFromHibernate
!= gIOHibernateState
) {
1199 gIOOptionsEntry
->sync();
1204 if (vars
->srcBuffer
) {
1205 vars
->srcBuffer
->release();
1207 bzero(&gIOHibernateHandoffPages
[0], gIOHibernateHandoffPageCount
* sizeof(gIOHibernateHandoffPages
[0]));
1208 if (vars
->handoffBuffer
) {
1209 if (kIOHibernateStateWakingFromHibernate
== gIOHibernateState
) {
1210 IOHibernateHandoff
* handoff
;
1212 for (handoff
= (IOHibernateHandoff
*) vars
->handoffBuffer
->getBytesNoCopy();
1214 handoff
= (IOHibernateHandoff
*) &handoff
->data
[handoff
->bytecount
]) {
1215 HIBPRINT("handoff %p, %x, %x\n", handoff
, handoff
->type
, handoff
->bytecount
);
1216 uint8_t * data
= &handoff
->data
[0];
1217 switch (handoff
->type
) {
1218 case kIOHibernateHandoffTypeEnd
:
1222 case kIOHibernateHandoffTypeDeviceTree
:
1223 MergeDeviceTree((DeviceTreeNode
*) data
, IOService::getServiceRoot());
1226 case kIOHibernateHandoffTypeKeyStore
:
1227 #if defined(__i386__) || defined(__x86_64__)
1229 IOBufferMemoryDescriptor
*
1230 md
= IOBufferMemoryDescriptor::withBytes(data
, handoff
->bytecount
, kIODirectionOutIn
);
1232 IOSetKeyStoreData(md
);
1239 done
= (kIOHibernateHandoffType
!= (handoff
->type
& 0xFFFF0000));
1243 #if defined(__i386__) || defined(__x86_64__)
1244 if (vars
->volumeCryptKeySize
) {
1245 IOBufferMemoryDescriptor
*
1246 bmd
= IOBufferMemoryDescriptor::withBytes(&vars
->volumeCryptKey
[0],
1247 vars
->volumeCryptKeySize
, kIODirectionOutIn
);
1249 panic("IOBufferMemoryDescriptor");
1251 IOSetAPFSKeyStoreData(bmd
);
1252 bzero(&vars
->volumeCryptKey
[0], sizeof(vars
->volumeCryptKey
));
1256 vars
->handoffBuffer
->release();
1260 && (data
= OSDynamicCast(OSData
, gIOChosenEntry
->getProperty(gIOBridgeBootSessionUUIDKey
)))
1261 && (sizeof(gIOHibernateBridgeBootSessionUUIDString
) <= data
->getLength())) {
1262 bcopy(data
->getBytesNoCopy(), &gIOHibernateBridgeBootSessionUUIDString
[0],
1263 sizeof(gIOHibernateBridgeBootSessionUUIDString
));
1266 if (vars
->hwEncrypt
) {
1267 err
= IOPolledFilePollersSetEncryptionKey(vars
->fileVars
, NULL
, 0);
1268 HIBLOG("IOPolledFilePollersSetEncryptionKey(0,%x)\n", err
);
1271 bzero(vars
, sizeof(*vars
));
1273 // gIOHibernateState = kIOHibernateStateInactive; // leave it for post wake code to see
1275 return kIOReturnSuccess
;
1279 IOHibernateSystemPostWakeTrim(void * p1
, void * p2
)
1281 // invalidate & close the image file
1283 IOLockLock(gFSLock
);
1285 if (kFSTrimDelay
== gFSState
) {
1286 IOPolledFileIOVars
* vars
= &gFileVars
;
1287 IOPolledFileClose(&vars
,
1291 0, (caddr_t
)gIOHibernateCurrentHeader
, sizeof(IOHibernateImageHeader
),
1292 sizeof(IOHibernateImageHeader
), gIOHibernateCurrentHeader
->imageSize
);
1297 IOLockUnlock(gFSLock
);
1302 IOHibernateSystemPostWake(bool now
)
1304 gIOHibernateCurrentHeader
->signature
= kIOHibernateHeaderInvalidSignature
;
1305 IOSetBootImageNVRAM(NULL
);
1307 IOLockLock(gFSLock
);
1308 if (kFSTrimDelay
== gFSState
) {
1309 thread_call_cancel(gIOHibernateTrimCalloutEntry
);
1310 IOHibernateSystemPostWakeTrim(NULL
, NULL
);
1311 } else if (kFSOpened
!= gFSState
) {
1314 gFSState
= kFSTrimDelay
;
1316 thread_call_cancel(gIOHibernateTrimCalloutEntry
);
1317 IOHibernateSystemPostWakeTrim(NULL
, NULL
);
1319 AbsoluteTime deadline
;
1320 clock_interval_to_deadline(TRIM_DELAY
, kMillisecondScale
, &deadline
);
1321 thread_call_enter1_delayed(gIOHibernateTrimCalloutEntry
, NULL
, deadline
);
1324 IOLockUnlock(gFSLock
);
1326 return kIOReturnSuccess
;
1330 IOHibernateWasScreenLocked(void)
1333 if ((kIOHibernateStateWakingFromHibernate
== gIOHibernateState
) && gIOChosenEntry
) {
1335 data
= OSDynamicCast(OSData
, gIOChosenEntry
->getProperty(kIOScreenLockStateKey
));
1337 ret
= ((uint32_t *)data
->getBytesNoCopy())[0];
1338 gIOChosenEntry
->setProperty(kIOBooterScreenLockStateKey
, data
);
1341 gIOChosenEntry
->removeProperty(kIOBooterScreenLockStateKey
);
1347 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1349 SYSCTL_STRING(_kern
, OID_AUTO
, hibernatefile
,
1350 CTLFLAG_RW
| CTLFLAG_NOAUTO
| CTLFLAG_KERN
| CTLFLAG_LOCKED
,
1351 gIOHibernateFilename
, sizeof(gIOHibernateFilename
), "");
1352 SYSCTL_STRING(_kern
, OID_AUTO
, bootsignature
,
1353 CTLFLAG_RW
| CTLFLAG_NOAUTO
| CTLFLAG_KERN
| CTLFLAG_LOCKED
,
1354 gIOHibernateBootSignature
, sizeof(gIOHibernateBootSignature
), "");
1355 SYSCTL_UINT(_kern
, OID_AUTO
, hibernatemode
,
1356 CTLFLAG_RW
| CTLFLAG_NOAUTO
| CTLFLAG_KERN
| CTLFLAG_LOCKED
,
1357 &gIOHibernateMode
, 0, "");
1358 SYSCTL_STRUCT(_kern
, OID_AUTO
, hibernatestatistics
,
1359 CTLTYPE_STRUCT
| CTLFLAG_RD
| CTLFLAG_NOAUTO
| CTLFLAG_KERN
| CTLFLAG_LOCKED
,
1360 &_hibernateStats
, hibernate_statistics_t
, "");
1361 SYSCTL_STRING(_kern_bridge
, OID_AUTO
, bootsessionuuid
,
1362 CTLFLAG_RD
| CTLFLAG_NOAUTO
| CTLFLAG_KERN
| CTLFLAG_LOCKED
,
1363 gIOHibernateBridgeBootSessionUUIDString
, sizeof(gIOHibernateBridgeBootSessionUUIDString
), "");
1365 SYSCTL_UINT(_kern
, OID_AUTO
, hibernategraphicsready
,
1366 CTLFLAG_RW
| CTLFLAG_NOAUTO
| CTLFLAG_KERN
| CTLFLAG_ANYBODY
,
1367 &_hibernateStats
.graphicsReadyTime
, 0, "");
1368 SYSCTL_UINT(_kern
, OID_AUTO
, hibernatewakenotification
,
1369 CTLFLAG_RW
| CTLFLAG_NOAUTO
| CTLFLAG_KERN
| CTLFLAG_ANYBODY
,
1370 &_hibernateStats
.wakeNotificationTime
, 0, "");
1371 SYSCTL_UINT(_kern
, OID_AUTO
, hibernatelockscreenready
,
1372 CTLFLAG_RW
| CTLFLAG_NOAUTO
| CTLFLAG_KERN
| CTLFLAG_ANYBODY
,
1373 &_hibernateStats
.lockScreenReadyTime
, 0, "");
1374 SYSCTL_UINT(_kern
, OID_AUTO
, hibernatehidready
,
1375 CTLFLAG_RW
| CTLFLAG_NOAUTO
| CTLFLAG_KERN
| CTLFLAG_ANYBODY
,
1376 &_hibernateStats
.hidReadyTime
, 0, "");
1379 IOHibernateSystemInit(IOPMrootDomain
* rootDomain
)
1381 gIOHibernateBootImageKey
= OSSymbol::withCStringNoCopy(kIOHibernateBootImageKey
);
1382 gIOHibernateBootSignatureKey
= OSSymbol::withCStringNoCopy(kIOHibernateBootSignatureKey
);
1383 gIOBridgeBootSessionUUIDKey
= OSSymbol::withCStringNoCopy(kIOBridgeBootSessionUUIDKey
);
1385 #if defined(__i386__) || defined(__x86_64__)
1386 gIOHibernateRTCVariablesKey
= OSSymbol::withCStringNoCopy(kIOHibernateRTCVariablesKey
);
1387 gIOHibernateBoot0082Key
= OSSymbol::withCString("8BE4DF61-93CA-11D2-AA0D-00E098032B8C:Boot0082");
1388 gIOHibernateBootNextKey
= OSSymbol::withCString("8BE4DF61-93CA-11D2-AA0D-00E098032B8C:BootNext");
1389 gIOHibernateRTCVariablesKey
= OSSymbol::withCStringNoCopy(kIOHibernateRTCVariablesKey
);
1390 #endif /* defined(__i386__) || defined(__x86_64__) */
1392 OSData
* data
= OSData::withBytesNoCopy(&gIOHibernateState
, sizeof(gIOHibernateState
));
1394 rootDomain
->setProperty(kIOHibernateStateKey
, data
);
1398 if (PE_parse_boot_argn("hfile", gIOHibernateFilename
, sizeof(gIOHibernateFilename
))) {
1399 gIOHibernateMode
= kIOHibernateModeOn
;
1401 gIOHibernateFilename
[0] = 0;
1404 sysctl_register_oid(&sysctl__kern_hibernatefile
);
1405 sysctl_register_oid(&sysctl__kern_bootsignature
);
1406 sysctl_register_oid(&sysctl__kern_hibernatemode
);
1407 sysctl_register_oid(&sysctl__kern_hibernatestatistics
);
1408 sysctl_register_oid(&sysctl__kern_hibernategraphicsready
);
1409 sysctl_register_oid(&sysctl__kern_hibernatewakenotification
);
1410 sysctl_register_oid(&sysctl__kern_hibernatelockscreenready
);
1411 sysctl_register_oid(&sysctl__kern_hibernatehidready
);
1413 gIOChosenEntry
= IORegistryEntry::fromPath("/chosen", gIODTPlane
);
1416 && (data
= OSDynamicCast(OSData
, gIOChosenEntry
->getProperty(gIOBridgeBootSessionUUIDKey
)))
1417 && (sizeof(gIOHibernateBridgeBootSessionUUIDString
) <= data
->getLength())) {
1418 sysctl_register_oid(&sysctl__kern_bridge_bootsessionuuid
);
1419 bcopy(data
->getBytesNoCopy(), &gIOHibernateBridgeBootSessionUUIDString
[0], sizeof(gIOHibernateBridgeBootSessionUUIDString
));
1422 gFSLock
= IOLockAlloc();
1425 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1428 IOHibernatePolledFileWrite(IOPolledFileIOVars
* vars
,
1429 const uint8_t * bytes
, IOByteCount size
,
1430 IOPolledFileCryptVars
* cryptvars
)
1434 err
= IOPolledFileWrite(vars
, bytes
, size
, cryptvars
);
1435 if ((kIOReturnSuccess
== err
) && hibernate_should_abort()) {
1436 err
= kIOReturnAborted
;
1442 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
1445 hibernate_write_image(void)
1447 IOHibernateImageHeader
* header
= gIOHibernateCurrentHeader
;
1448 IOHibernateVars
* vars
= &gIOHibernateVars
;
1449 IOPolledFileExtent
* fileExtents
;
1451 _static_assert_1_arg(sizeof(IOHibernateImageHeader
) == 512);
1453 uint32_t pageCount
, pagesDone
;
1455 vm_offset_t ppnum
, page
;
1459 uint8_t * compressed
;
1461 IOByteCount pageCompressedSize
;
1462 uint64_t compressedSize
, uncompressedSize
;
1463 uint64_t image1Size
= 0;
1464 uint32_t bitmap_size
;
1465 bool iterDone
, pollerOpen
, needEncrypt
;
1466 uint32_t restore1Sum
, sum
, sum1
, sum2
;
1470 uint32_t pageAndCount
[2];
1473 uintptr_t hibernateBase
;
1474 uintptr_t hibernateEnd
;
1476 AbsoluteTime startTime
, endTime
;
1477 AbsoluteTime allTime
, compTime
;
1480 uint32_t lastProgressStamp
= 0;
1481 uint32_t progressStamp
;
1482 uint32_t blob
, lastBlob
= (uint32_t) -1L;
1484 uint32_t wiredPagesEncrypted
;
1485 uint32_t dirtyPagesEncrypted
;
1486 uint32_t wiredPagesClear
;
1487 uint32_t svPageCount
;
1488 uint32_t zvPageCount
;
1490 IOPolledFileCryptVars _cryptvars
;
1491 IOPolledFileCryptVars
* cryptvars
= NULL
;
1493 wiredPagesEncrypted
= 0;
1494 dirtyPagesEncrypted
= 0;
1495 wiredPagesClear
= 0;
1500 || !vars
->fileVars
->pollers
1501 || !(kIOHibernateModeOn
& gIOHibernateMode
)) {
1502 return kIOHibernatePostWriteSleep
;
1505 if (kIOHibernateModeSleep
& gIOHibernateMode
) {
1506 kdebug_enable
= save_kdebug_enable
;
1509 KDBG(IOKDBG_CODE(DBG_HIBERNATE
, 1) | DBG_FUNC_START
);
1510 IOService::getPMRootDomain()->tracePoint(kIOPMTracePointHibernate
);
1512 restore1Sum
= sum1
= sum2
= 0;
1515 // encryption data. "iv" is the "initial vector".
1516 if (kIOHibernateModeEncrypt
& gIOHibernateMode
) {
1517 static const unsigned char first_iv
[AES_BLOCK_SIZE
]
1518 = { 0xa3, 0x63, 0x65, 0xa9, 0x0b, 0x71, 0x7b, 0x1c,
1519 0xdf, 0x9e, 0x5f, 0x32, 0xd7, 0x61, 0x63, 0xda };
1521 cryptvars
= &gIOHibernateCryptWakeContext
;
1522 bzero(cryptvars
, sizeof(IOPolledFileCryptVars
));
1523 aes_encrypt_key(vars
->cryptKey
,
1524 kIOHibernateAESKeySize
,
1525 &cryptvars
->ctx
.encrypt
);
1526 aes_decrypt_key(vars
->cryptKey
,
1527 kIOHibernateAESKeySize
,
1528 &cryptvars
->ctx
.decrypt
);
1530 cryptvars
= &_cryptvars
;
1531 bzero(cryptvars
, sizeof(IOPolledFileCryptVars
));
1532 for (pageCount
= 0; pageCount
< sizeof(vars
->wiredCryptKey
); pageCount
++) {
1533 vars
->wiredCryptKey
[pageCount
] ^= vars
->volumeCryptKey
[pageCount
];
1535 aes_encrypt_key(vars
->wiredCryptKey
,
1536 kIOHibernateAESKeySize
,
1537 &cryptvars
->ctx
.encrypt
);
1539 bcopy(&first_iv
[0], &cryptvars
->aes_iv
[0], AES_BLOCK_SIZE
);
1540 bzero(&vars
->wiredCryptKey
[0], sizeof(vars
->wiredCryptKey
));
1541 bzero(&vars
->cryptKey
[0], sizeof(vars
->cryptKey
));
1545 hibernate_page_list_setall(vars
->page_list
,
1546 vars
->page_list_wired
,
1547 vars
->page_list_pal
,
1548 false /* !preflight */,
1550 ((0 == (kIOHibernateModeSleep
& gIOHibernateMode
))
1551 && (0 != ((kIOHibernateModeDiscardCleanActive
| kIOHibernateModeDiscardCleanInactive
) & gIOHibernateMode
))),
1554 HIBLOG("hibernate_page_list_setall found pageCount %d\n", pageCount
);
1556 fileExtents
= (IOPolledFileExtent
*) vars
->fileVars
->fileExtents
->getBytesNoCopy();
1559 count
= vars
->fileExtents
->getLength() / sizeof(IOPolledFileExtent
);
1560 for (page
= 0; page
< count
; page
++) {
1561 HIBLOG("fileExtents[%d] %qx, %qx (%qx)\n", page
,
1562 fileExtents
[page
].start
, fileExtents
[page
].length
,
1563 fileExtents
[page
].start
+ fileExtents
[page
].length
);
1567 needEncrypt
= (0 != (kIOHibernateModeEncrypt
& gIOHibernateMode
));
1568 AbsoluteTime_to_scalar(&compTime
) = 0;
1571 clock_get_uptime(&allTime
);
1572 IOService::getPMRootDomain()->pmStatsRecordEvent(
1573 kIOPMStatsHibernateImageWrite
| kIOPMStatsEventStartFlag
, allTime
);
1576 uncompressedSize
= 0;
1580 IOPolledFileSeek(vars
->fileVars
, vars
->fileVars
->blockSize
);
1582 HIBLOG("IOHibernatePollerOpen, ml_get_interrupts_enabled %d\n",
1583 ml_get_interrupts_enabled());
1584 err
= IOPolledFilePollersOpen(vars
->fileVars
, kIOPolledBeforeSleepState
,
1585 // abortable if not low battery
1586 !IOService::getPMRootDomain()->mustHibernate());
1587 HIBLOG("IOHibernatePollerOpen(%x)\n", err
);
1588 pollerOpen
= (kIOReturnSuccess
== err
);
1593 if (vars
->volumeCryptKeySize
) {
1594 err
= IOPolledFilePollersSetEncryptionKey(vars
->fileVars
, &vars
->volumeCryptKey
[0], vars
->volumeCryptKeySize
);
1595 HIBLOG("IOPolledFilePollersSetEncryptionKey(%x)\n", err
);
1596 vars
->hwEncrypt
= (kIOReturnSuccess
== err
);
1597 bzero(&vars
->volumeCryptKey
[0], sizeof(vars
->volumeCryptKey
));
1598 if (vars
->hwEncrypt
) {
1599 header
->options
|= kIOHibernateOptionHWEncrypt
;
1603 // copy file block extent list if larger than header
1605 count
= vars
->fileVars
->fileExtents
->getLength();
1606 if (count
> sizeof(header
->fileExtentMap
)) {
1607 count
-= sizeof(header
->fileExtentMap
);
1608 err
= IOHibernatePolledFileWrite(vars
->fileVars
,
1609 ((uint8_t *) &fileExtents
[0]) + sizeof(header
->fileExtentMap
), count
, cryptvars
);
1610 if (kIOReturnSuccess
!= err
) {
1615 hibernateBase
= HIB_BASE
; /* Defined in PAL headers */
1616 hibernateEnd
= (segHIBB
+ segSizeHIB
);
1618 // copy out restore1 code
1621 (phys64
= vars
->handoffBuffer
->getPhysicalSegment(count
, &segLen
, kIOMemoryMapperNone
));
1623 for (pagesDone
= 0; pagesDone
< atop_32(segLen
); pagesDone
++) {
1624 gIOHibernateHandoffPages
[atop_32(count
) + pagesDone
] = atop_64(phys64
) + pagesDone
;
1628 page
= atop_32(kvtophys(hibernateBase
));
1629 count
= atop_32(round_page(hibernateEnd
) - hibernateBase
);
1630 header
->restore1CodePhysPage
= page
;
1631 header
->restore1CodeVirt
= hibernateBase
;
1632 header
->restore1PageCount
= count
;
1633 header
->restore1CodeOffset
= ((uintptr_t) &hibernate_machine_entrypoint
) - hibernateBase
;
1634 header
->restore1StackOffset
= ((uintptr_t) &gIOHibernateRestoreStackEnd
[0]) - 64 - hibernateBase
;
1636 if (uuid_parse(&gIOHibernateBridgeBootSessionUUIDString
[0], &header
->bridgeBootSessionUUID
[0])) {
1637 bzero(&header
->bridgeBootSessionUUID
[0], sizeof(header
->bridgeBootSessionUUID
));
1640 // sum __HIB seg, with zeros for the stack
1641 src
= (uint8_t *) trunc_page(hibernateBase
);
1642 for (page
= 0; page
< count
; page
++) {
1643 if ((src
< &gIOHibernateRestoreStack
[0]) || (src
>= &gIOHibernateRestoreStackEnd
[0])) {
1644 restore1Sum
+= hibernate_sum_page(src
, header
->restore1CodeVirt
+ page
);
1646 restore1Sum
+= 0x00000000;
1652 // write the __HIB seg, with zeros for the stack
1654 src
= (uint8_t *) trunc_page(hibernateBase
);
1655 count
= ((uintptr_t) &gIOHibernateRestoreStack
[0]) - trunc_page(hibernateBase
);
1657 err
= IOHibernatePolledFileWrite(vars
->fileVars
, src
, count
, cryptvars
);
1658 if (kIOReturnSuccess
!= err
) {
1662 err
= IOHibernatePolledFileWrite(vars
->fileVars
,
1664 &gIOHibernateRestoreStackEnd
[0] - &gIOHibernateRestoreStack
[0],
1666 if (kIOReturnSuccess
!= err
) {
1669 src
= &gIOHibernateRestoreStackEnd
[0];
1670 count
= round_page(hibernateEnd
) - ((uintptr_t) src
);
1672 err
= IOHibernatePolledFileWrite(vars
->fileVars
, src
, count
, cryptvars
);
1673 if (kIOReturnSuccess
!= err
) {
1678 if (!vars
->hwEncrypt
&& (kIOHibernateModeEncrypt
& gIOHibernateMode
)) {
1679 vars
->fileVars
->encryptStart
= (vars
->fileVars
->position
& ~(AES_BLOCK_SIZE
- 1));
1680 vars
->fileVars
->encryptEnd
= UINT64_MAX
;
1681 HIBLOG("encryptStart %qx\n", vars
->fileVars
->encryptStart
);
1684 // write the preview buffer
1686 if (vars
->previewBuffer
) {
1690 phys64
= vars
->previewBuffer
->getPhysicalSegment(count
, &segLen
, kIOMemoryMapperNone
);
1691 pageAndCount
[0] = atop_64(phys64
);
1692 pageAndCount
[1] = atop_32(segLen
);
1693 err
= IOHibernatePolledFileWrite(vars
->fileVars
,
1694 (const uint8_t *) &pageAndCount
, sizeof(pageAndCount
),
1696 if (kIOReturnSuccess
!= err
) {
1700 ppnum
+= sizeof(pageAndCount
);
1702 if (kIOReturnSuccess
!= err
) {
1706 src
= (uint8_t *) vars
->previewBuffer
->getPhysicalSegment(0, NULL
, _kIOMemorySourceSegment
);
1708 ((hibernate_preview_t
*)src
)->lockTime
= gIOConsoleLockTime
;
1710 count
= vars
->previewBuffer
->getLength();
1712 header
->previewPageListSize
= ppnum
;
1713 header
->previewSize
= count
+ ppnum
;
1715 for (page
= 0; page
< count
; page
+= page_size
) {
1716 phys64
= vars
->previewBuffer
->getPhysicalSegment(page
, NULL
, kIOMemoryMapperNone
);
1717 sum1
+= hibernate_sum_page(src
+ page
, atop_64(phys64
));
1719 err
= IOHibernatePolledFileWrite(vars
->fileVars
, src
, count
, cryptvars
);
1720 if (kIOReturnSuccess
!= err
) {
1725 // mark areas for no save
1726 IOMemoryDescriptor
* ioBuffer
;
1727 ioBuffer
= IOPolledFileGetIOBuffer(vars
->fileVars
);
1729 (phys64
= ioBuffer
->getPhysicalSegment(count
, &segLen
, kIOMemoryMapperNone
));
1731 hibernate_set_page_state(vars
->page_list
, vars
->page_list_wired
,
1732 atop_64(phys64
), atop_32(segLen
),
1733 kIOHibernatePageStateFree
);
1734 pageCount
-= atop_32(segLen
);
1738 (phys64
= vars
->srcBuffer
->getPhysicalSegment(count
, &segLen
, kIOMemoryMapperNone
));
1740 hibernate_set_page_state(vars
->page_list
, vars
->page_list_wired
,
1741 atop_64(phys64
), atop_32(segLen
),
1742 kIOHibernatePageStateFree
);
1743 pageCount
-= atop_32(segLen
);
1746 // copy out bitmap of pages available for trashing during restore
1748 bitmap_size
= vars
->page_list_wired
->list_size
;
1749 src
= (uint8_t *) vars
->page_list_wired
;
1750 err
= IOHibernatePolledFileWrite(vars
->fileVars
, src
, bitmap_size
, cryptvars
);
1751 if (kIOReturnSuccess
!= err
) {
1755 // mark more areas for no save, but these are not available
1756 // for trashing during restore
1758 hibernate_page_list_set_volatile(vars
->page_list
, vars
->page_list_wired
, &pageCount
);
1761 page
= atop_32(KERNEL_IMAGE_TO_PHYS(hibernateBase
));
1762 count
= atop_32(round_page(KERNEL_IMAGE_TO_PHYS(hibernateEnd
))) - page
;
1763 hibernate_set_page_state(vars
->page_list
, vars
->page_list_wired
,
1765 kIOHibernatePageStateFree
);
1768 if (vars
->previewBuffer
) {
1770 (phys64
= vars
->previewBuffer
->getPhysicalSegment(count
, &segLen
, kIOMemoryMapperNone
));
1772 hibernate_set_page_state(vars
->page_list
, vars
->page_list_wired
,
1773 atop_64(phys64
), atop_32(segLen
),
1774 kIOHibernatePageStateFree
);
1775 pageCount
-= atop_32(segLen
);
1780 (phys64
= vars
->handoffBuffer
->getPhysicalSegment(count
, &segLen
, kIOMemoryMapperNone
));
1782 hibernate_set_page_state(vars
->page_list
, vars
->page_list_wired
,
1783 atop_64(phys64
), atop_32(segLen
),
1784 kIOHibernatePageStateFree
);
1785 pageCount
-= atop_32(segLen
);
1789 vm_size_t shadow_pages_free
= atop_64(shadow_ptop
) - atop_64(shadow_pnext
);
1791 /* no need to save unused shadow pages */
1792 hibernate_set_page_state(vars
->page_list
, vars
->page_list_wired
,
1793 atop_64(shadow_pnext
),
1795 kIOHibernatePageStateFree
);
1798 src
= (uint8_t *) vars
->srcBuffer
->getBytesNoCopy();
1799 compressed
= src
+ page_size
;
1800 scratch
= compressed
+ page_size
;
1805 HIBLOG("bitmap_size 0x%x, previewSize 0x%x, writing %d pages @ 0x%llx\n",
1806 bitmap_size
, header
->previewSize
,
1807 pageCount
, vars
->fileVars
->position
);
1814 kWiredEncrypt
= kWired
| kEncrypt
,
1815 kWiredClear
= kWired
,
1816 kUnwiredEncrypt
= kEncrypt
1819 bool cpuAES
= (0 != (CPUID_FEATURE_AES
& cpuid_features()));
1821 for (pageType
= kWiredEncrypt
; pageType
>= kUnwiredEncrypt
; pageType
--) {
1822 if (kUnwiredEncrypt
== pageType
) {
1823 // start unwired image
1824 if (!vars
->hwEncrypt
&& (kIOHibernateModeEncrypt
& gIOHibernateMode
)) {
1825 vars
->fileVars
->encryptStart
= (vars
->fileVars
->position
& ~(((uint64_t)AES_BLOCK_SIZE
) - 1));
1826 vars
->fileVars
->encryptEnd
= UINT64_MAX
;
1827 HIBLOG("encryptStart %qx\n", vars
->fileVars
->encryptStart
);
1829 bcopy(&cryptvars
->aes_iv
[0],
1830 &gIOHibernateCryptWakeContext
.aes_iv
[0],
1831 sizeof(cryptvars
->aes_iv
));
1832 cryptvars
= &gIOHibernateCryptWakeContext
;
1834 for (iterDone
= false, ppnum
= 0; !iterDone
;) {
1835 if (cpuAES
&& (pageType
== kWiredClear
)) {
1838 count
= hibernate_page_list_iterate((kWired
& pageType
) ? vars
->page_list_wired
: vars
->page_list
,
1841 // kprintf("[%d](%x : %x)\n", pageType, ppnum, count);
1845 if (count
&& (kWired
& pageType
) && needEncrypt
) {
1846 uint32_t checkIndex
;
1847 for (checkIndex
= 0;
1848 (checkIndex
< count
)
1849 && (((kEncrypt
& pageType
) == 0) == pmap_is_noencrypt(ppnum
+ checkIndex
));
1861 case kWiredEncrypt
: wiredPagesEncrypted
+= count
; break;
1862 case kWiredClear
: wiredPagesClear
+= count
; break;
1863 case kUnwiredEncrypt
: dirtyPagesEncrypted
+= count
; break;
1866 if (iterDone
&& (kWiredEncrypt
== pageType
)) {/* not yet end of wired list */
1868 pageAndCount
[0] = ppnum
;
1869 pageAndCount
[1] = count
;
1870 err
= IOHibernatePolledFileWrite(vars
->fileVars
,
1871 (const uint8_t *) &pageAndCount
, sizeof(pageAndCount
),
1873 if (kIOReturnSuccess
!= err
) {
1878 for (page
= ppnum
; page
< (ppnum
+ count
); page
++) {
1879 err
= IOMemoryDescriptorWriteFromPhysical(vars
->srcBuffer
, 0, ptoa_64(page
), page_size
);
1881 HIBLOG("IOMemoryDescriptorWriteFromPhysical %d [%ld] %x\n", __LINE__
, (long)page
, err
);
1885 sum
= hibernate_sum_page(src
, page
);
1886 if (kWired
& pageType
) {
1892 clock_get_uptime(&startTime
);
1893 wkresult
= WKdm_compress_new((const WK_word
*) src
,
1894 (WK_word
*) compressed
,
1898 clock_get_uptime(&endTime
);
1899 ADD_ABSOLUTETIME(&compTime
, &endTime
);
1900 SUB_ABSOLUTETIME(&compTime
, &startTime
);
1902 compBytes
+= page_size
;
1903 pageCompressedSize
= (-1 == wkresult
) ? page_size
: wkresult
;
1905 if (pageCompressedSize
== 0) {
1906 pageCompressedSize
= 4;
1909 if (*(uint32_t *)src
) {
1915 if (pageCompressedSize
!= page_size
) {
1922 tag
= pageCompressedSize
| kIOHibernateTagSignature
;
1923 err
= IOHibernatePolledFileWrite(vars
->fileVars
, (const uint8_t *) &tag
, sizeof(tag
), cryptvars
);
1924 if (kIOReturnSuccess
!= err
) {
1928 err
= IOHibernatePolledFileWrite(vars
->fileVars
, data
, (pageCompressedSize
+ 3) & ~3, cryptvars
);
1929 if (kIOReturnSuccess
!= err
) {
1933 compressedSize
+= pageCompressedSize
;
1934 uncompressedSize
+= page_size
;
1937 if (vars
->consoleMapping
&& (0 == (1023 & pagesDone
))) {
1938 blob
= ((pagesDone
* kIOHibernateProgressCount
) / pageCount
);
1939 if (blob
!= lastBlob
) {
1940 ProgressUpdate(gIOHibernateGraphicsInfo
, vars
->consoleMapping
, lastBlob
, blob
);
1944 if (0 == (8191 & pagesDone
)) {
1945 clock_get_uptime(&endTime
);
1946 SUB_ABSOLUTETIME(&endTime
, &allTime
);
1947 absolutetime_to_nanoseconds(endTime
, &nsec
);
1948 progressStamp
= nsec
/ 750000000ULL;
1949 if (progressStamp
!= lastProgressStamp
) {
1950 lastProgressStamp
= progressStamp
;
1951 HIBPRINT("pages %d (%d%%)\n", pagesDone
, (100 * pagesDone
) / pageCount
);
1955 if (kIOReturnSuccess
!= err
) {
1961 if (kIOReturnSuccess
!= err
) {
1965 if ((kEncrypt
& pageType
) && vars
->fileVars
->encryptStart
) {
1966 vars
->fileVars
->encryptEnd
= ((vars
->fileVars
->position
+ 511) & ~511ULL);
1967 HIBLOG("encryptEnd %qx\n", vars
->fileVars
->encryptEnd
);
1970 if (kWiredEncrypt
!= pageType
) {
1971 // end of image1/2 - fill to next block
1972 err
= IOHibernatePolledFileWrite(vars
->fileVars
, NULL
, 0, cryptvars
);
1973 if (kIOReturnSuccess
!= err
) {
1977 if (kWiredClear
== pageType
) {
1978 // enlarge wired image for test
1979 // err = IOHibernatePolledFileWrite(vars->fileVars, 0, 0x60000000, cryptvars);
1982 header
->encryptStart
= vars
->fileVars
->encryptStart
;
1983 header
->encryptEnd
= vars
->fileVars
->encryptEnd
;
1984 image1Size
= vars
->fileVars
->position
;
1985 HIBLOG("image1Size 0x%qx, encryptStart1 0x%qx, End1 0x%qx\n",
1986 image1Size
, header
->encryptStart
, header
->encryptEnd
);
1989 if (kIOReturnSuccess
!= err
) {
1990 if (kIOReturnOverrun
== err
) {
1991 // update actual compression ratio on not enough space (for retry)
1992 gIOHibernateCompression
= (compressedSize
<< 8) / uncompressedSize
;
1995 // update partial amount written (for IOPolledFileClose cleanup/unmap)
1996 header
->imageSize
= vars
->fileVars
->position
;
2002 header
->imageSize
= vars
->fileVars
->position
;
2003 header
->image1Size
= image1Size
;
2004 header
->bitmapSize
= bitmap_size
;
2005 header
->pageCount
= pageCount
;
2007 header
->restore1Sum
= restore1Sum
;
2008 header
->image1Sum
= sum1
;
2009 header
->image2Sum
= sum2
;
2010 header
->sleepTime
= gIOLastSleepTime
.tv_sec
;
2012 header
->compression
= (compressedSize
<< 8) / uncompressedSize
;
2013 gIOHibernateCompression
= header
->compression
;
2015 count
= vars
->fileVars
->fileExtents
->getLength();
2016 if (count
> sizeof(header
->fileExtentMap
)) {
2017 header
->fileExtentMapSize
= count
;
2018 count
= sizeof(header
->fileExtentMap
);
2020 header
->fileExtentMapSize
= sizeof(header
->fileExtentMap
);
2022 bcopy(&fileExtents
[0], &header
->fileExtentMap
[0], count
);
2024 header
->deviceBase
= vars
->fileVars
->block0
;
2025 header
->deviceBlockSize
= vars
->fileVars
->blockSize
;
2027 IOPolledFileSeek(vars
->fileVars
, 0);
2028 err
= IOHibernatePolledFileWrite(vars
->fileVars
,
2029 (uint8_t *) header
, sizeof(IOHibernateImageHeader
),
2031 if (kIOReturnSuccess
!= err
) {
2034 err
= IOHibernatePolledFileWrite(vars
->fileVars
, NULL
, 0, cryptvars
);
2037 clock_get_uptime(&endTime
);
2039 IOService::getPMRootDomain()->pmStatsRecordEvent(
2040 kIOPMStatsHibernateImageWrite
| kIOPMStatsEventStopFlag
, endTime
);
2042 SUB_ABSOLUTETIME(&endTime
, &allTime
);
2043 absolutetime_to_nanoseconds(endTime
, &nsec
);
2044 HIBLOG("all time: %qd ms, ", nsec
/ 1000000ULL);
2046 absolutetime_to_nanoseconds(compTime
, &nsec
);
2047 HIBLOG("comp bytes: %qd time: %qd ms %qd Mb/s, ",
2050 nsec
? (((compBytes
* 1000000000ULL) / 1024 / 1024) / nsec
) : 0);
2052 absolutetime_to_nanoseconds(vars
->fileVars
->cryptTime
, &nsec
);
2053 HIBLOG("crypt bytes: %qd time: %qd ms %qd Mb/s, ",
2054 vars
->fileVars
->cryptBytes
,
2056 nsec
? (((vars
->fileVars
->cryptBytes
* 1000000000ULL) / 1024 / 1024) / nsec
) : 0);
2058 HIBLOG("\nimage %qd (%lld%%), uncompressed %qd (%d), compressed %qd (%d%%), sum1 %x, sum2 %x\n",
2059 header
->imageSize
, (header
->imageSize
* 100) / vars
->fileVars
->fileSize
,
2060 uncompressedSize
, atop_32(uncompressedSize
), compressedSize
,
2061 uncompressedSize
? ((int) ((compressedSize
* 100ULL) / uncompressedSize
)) : 0,
2064 HIBLOG("svPageCount %d, zvPageCount %d, wiredPagesEncrypted %d, wiredPagesClear %d, dirtyPagesEncrypted %d\n",
2065 svPageCount
, zvPageCount
, wiredPagesEncrypted
, wiredPagesClear
, dirtyPagesEncrypted
);
2068 IOPolledFilePollersClose(vars
->fileVars
, (kIOReturnSuccess
== err
) ? kIOPolledBeforeSleepState
: kIOPolledBeforeSleepStateAborted
);
2071 if (vars
->consoleMapping
) {
2072 ProgressUpdate(gIOHibernateGraphicsInfo
,
2073 vars
->consoleMapping
, 0, kIOHibernateProgressCount
);
2076 HIBLOG("hibernate_write_image done(%x)\n", err
);
2078 // should we come back via regular wake, set the state in memory.
2079 gIOHibernateState
= kIOHibernateStateInactive
;
2081 KDBG(IOKDBG_CODE(DBG_HIBERNATE
, 1) | DBG_FUNC_END
, wiredPagesEncrypted
,
2082 wiredPagesClear
, dirtyPagesEncrypted
);
2084 if (kIOReturnSuccess
== err
) {
2085 if (kIOHibernateModeSleep
& gIOHibernateMode
) {
2086 return kIOHibernatePostWriteSleep
;
2087 } else if (kIOHibernateModeRestart
& gIOHibernateMode
) {
2088 return kIOHibernatePostWriteRestart
;
2090 /* by default, power down */
2091 return kIOHibernatePostWriteHalt
;
2093 } else if (kIOReturnAborted
== err
) {
2094 return kIOHibernatePostWriteWake
;
2096 /* on error, sleep */
2097 return kIOHibernatePostWriteSleep
;
2101 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2104 hibernate_machine_init(void)
2109 uint32_t pagesRead
= 0;
2110 AbsoluteTime startTime
, compTime
;
2111 AbsoluteTime allTime
, endTime
;
2112 AbsoluteTime startIOTime
, endIOTime
;
2113 uint64_t nsec
, nsecIO
;
2115 uint32_t lastProgressStamp
= 0;
2116 uint32_t progressStamp
;
2117 IOPolledFileCryptVars
* cryptvars
= NULL
;
2119 IOHibernateVars
* vars
= &gIOHibernateVars
;
2120 bzero(gIOHibernateStats
, sizeof(hibernate_statistics_t
));
2122 if (!vars
->fileVars
|| !vars
->fileVars
->pollers
) {
2126 sum
= gIOHibernateCurrentHeader
->actualImage1Sum
;
2127 pagesDone
= gIOHibernateCurrentHeader
->actualUncompressedPages
;
2129 if (kIOHibernateStateWakingFromHibernate
!= gIOHibernateState
) {
2130 HIBLOG("regular wake\n");
2134 HIBPRINT("diag %x %x %x %x\n",
2135 gIOHibernateCurrentHeader
->diag
[0], gIOHibernateCurrentHeader
->diag
[1],
2136 gIOHibernateCurrentHeader
->diag
[2], gIOHibernateCurrentHeader
->diag
[3]);
2138 #define t40ms(x) (tmrCvt((((uint64_t)(x)) << 8), tscFCvtt2n) / 1000000)
2139 #define tStat(x, y) gIOHibernateStats->x = t40ms(gIOHibernateCurrentHeader->y);
2140 tStat(booterStart
, booterStart
);
2141 gIOHibernateStats
->smcStart
= gIOHibernateCurrentHeader
->smcStart
;
2142 tStat(booterDuration0
, booterTime0
);
2143 tStat(booterDuration1
, booterTime1
);
2144 tStat(booterDuration2
, booterTime2
);
2145 tStat(booterDuration
, booterTime
);
2146 tStat(booterConnectDisplayDuration
, connectDisplayTime
);
2147 tStat(booterSplashDuration
, splashTime
);
2148 tStat(trampolineDuration
, trampolineTime
);
2150 gIOHibernateStats
->image1Size
= gIOHibernateCurrentHeader
->image1Size
;
2151 gIOHibernateStats
->imageSize
= gIOHibernateCurrentHeader
->imageSize
;
2152 gIOHibernateStats
->image1Pages
= pagesDone
;
2154 /* HIBERNATE_stats */
2155 KDBG(IOKDBG_CODE(DBG_HIBERNATE
, 14), gIOHibernateStats
->smcStart
,
2156 gIOHibernateStats
->booterStart
, gIOHibernateStats
->booterDuration
,
2157 gIOHibernateStats
->trampolineDuration
);
2159 HIBLOG("booter start at %d ms smc %d ms, [%d, %d, %d] total %d ms, dsply %d, %d ms, tramp %d ms\n",
2160 gIOHibernateStats
->booterStart
,
2161 gIOHibernateStats
->smcStart
,
2162 gIOHibernateStats
->booterDuration0
,
2163 gIOHibernateStats
->booterDuration1
,
2164 gIOHibernateStats
->booterDuration2
,
2165 gIOHibernateStats
->booterDuration
,
2166 gIOHibernateStats
->booterConnectDisplayDuration
,
2167 gIOHibernateStats
->booterSplashDuration
,
2168 gIOHibernateStats
->trampolineDuration
);
2170 HIBLOG("hibernate_machine_init: state %d, image pages %d, sum was %x, imageSize 0x%qx, image1Size 0x%qx, conflictCount %d, nextFree %x\n",
2171 gIOHibernateState
, pagesDone
, sum
, gIOHibernateStats
->imageSize
, gIOHibernateStats
->image1Size
,
2172 gIOHibernateCurrentHeader
->conflictCount
, gIOHibernateCurrentHeader
->nextFree
);
2174 if ((0 != (kIOHibernateModeSleep
& gIOHibernateMode
))
2175 && (0 != ((kIOHibernateModeDiscardCleanActive
| kIOHibernateModeDiscardCleanInactive
) & gIOHibernateMode
))) {
2176 hibernate_page_list_discard(vars
->page_list
);
2179 cryptvars
= (kIOHibernateModeEncrypt
& gIOHibernateMode
) ? &gIOHibernateCryptWakeContext
: NULL
;
2181 if (gIOHibernateCurrentHeader
->handoffPageCount
> gIOHibernateHandoffPageCount
) {
2182 panic("handoff overflow");
2185 IOHibernateHandoff
* handoff
;
2187 bool foundCryptData
= false;
2188 bool foundVolumeEncryptData
= false;
2190 for (handoff
= (IOHibernateHandoff
*) vars
->handoffBuffer
->getBytesNoCopy();
2192 handoff
= (IOHibernateHandoff
*) &handoff
->data
[handoff
->bytecount
]) {
2193 // HIBPRINT("handoff %p, %x, %x\n", handoff, handoff->type, handoff->bytecount);
2194 uint8_t * data
= &handoff
->data
[0];
2195 switch (handoff
->type
) {
2196 case kIOHibernateHandoffTypeEnd
:
2200 case kIOHibernateHandoffTypeGraphicsInfo
:
2201 if (handoff
->bytecount
== sizeof(*gIOHibernateGraphicsInfo
)) {
2202 bcopy(data
, gIOHibernateGraphicsInfo
, sizeof(*gIOHibernateGraphicsInfo
));
2206 case kIOHibernateHandoffTypeCryptVars
:
2208 hibernate_cryptwakevars_t
*
2209 wakevars
= (hibernate_cryptwakevars_t
*) &handoff
->data
[0];
2210 bcopy(&wakevars
->aes_iv
[0], &cryptvars
->aes_iv
[0], sizeof(cryptvars
->aes_iv
));
2212 foundCryptData
= true;
2213 bzero(data
, handoff
->bytecount
);
2216 case kIOHibernateHandoffTypeVolumeCryptKey
:
2217 if (handoff
->bytecount
== vars
->volumeCryptKeySize
) {
2218 bcopy(data
, &vars
->volumeCryptKey
[0], vars
->volumeCryptKeySize
);
2219 foundVolumeEncryptData
= true;
2221 panic("kIOHibernateHandoffTypeVolumeCryptKey(%d)", handoff
->bytecount
);
2225 case kIOHibernateHandoffTypeMemoryMap
:
2227 clock_get_uptime(&allTime
);
2229 hibernate_newruntime_map(data
, handoff
->bytecount
,
2230 gIOHibernateCurrentHeader
->systemTableOffset
);
2232 clock_get_uptime(&endTime
);
2234 SUB_ABSOLUTETIME(&endTime
, &allTime
);
2235 absolutetime_to_nanoseconds(endTime
, &nsec
);
2237 HIBLOG("hibernate_newruntime_map time: %qd ms, ", nsec
/ 1000000ULL);
2241 case kIOHibernateHandoffTypeDeviceTree
:
2243 // DTEntry chosen = NULL;
2244 // HIBPRINT("DTLookupEntry %d\n", DTLookupEntry((const DTEntry) data, "/chosen", &chosen));
2249 done
= (kIOHibernateHandoffType
!= (handoff
->type
& 0xFFFF0000));
2254 if (vars
->hwEncrypt
&& !foundVolumeEncryptData
) {
2255 panic("no volumeCryptKey");
2256 } else if (cryptvars
&& !foundCryptData
) {
2257 panic("hibernate handoff");
2260 HIBPRINT("video 0x%llx %d %d %d status %x\n",
2261 gIOHibernateGraphicsInfo
->physicalAddress
, gIOHibernateGraphicsInfo
->depth
,
2262 gIOHibernateGraphicsInfo
->width
, gIOHibernateGraphicsInfo
->height
, gIOHibernateGraphicsInfo
->gfxStatus
);
2264 if (vars
->videoMapping
&& gIOHibernateGraphicsInfo
->physicalAddress
) {
2265 vars
->videoMapSize
= round_page(gIOHibernateGraphicsInfo
->height
2266 * gIOHibernateGraphicsInfo
->rowBytes
);
2267 if (vars
->videoMapSize
> vars
->videoAllocSize
) {
2268 vars
->videoMapSize
= 0;
2270 IOMapPages(kernel_map
,
2271 vars
->videoMapping
, gIOHibernateGraphicsInfo
->physicalAddress
,
2272 vars
->videoMapSize
, kIOMapInhibitCache
);
2276 if (vars
->videoMapSize
) {
2277 ProgressUpdate(gIOHibernateGraphicsInfo
,
2278 (uint8_t *) vars
->videoMapping
, 0, kIOHibernateProgressCount
);
2281 uint8_t * src
= (uint8_t *) vars
->srcBuffer
->getBytesNoCopy();
2282 uint8_t * compressed
= src
+ page_size
;
2283 uint8_t * scratch
= compressed
+ page_size
;
2284 uint32_t decoOffset
;
2286 clock_get_uptime(&allTime
);
2287 AbsoluteTime_to_scalar(&compTime
) = 0;
2290 HIBLOG("IOPolledFilePollersOpen(), ml_get_interrupts_enabled %d\n", ml_get_interrupts_enabled());
2291 err
= IOPolledFilePollersOpen(vars
->fileVars
, kIOPolledAfterSleepState
, false);
2292 clock_get_uptime(&startIOTime
);
2293 endTime
= startIOTime
;
2294 SUB_ABSOLUTETIME(&endTime
, &allTime
);
2295 absolutetime_to_nanoseconds(endTime
, &nsec
);
2296 HIBLOG("IOPolledFilePollersOpen(%x) %qd ms\n", err
, nsec
/ 1000000ULL);
2298 if (vars
->hwEncrypt
) {
2299 err
= IOPolledFilePollersSetEncryptionKey(vars
->fileVars
,
2300 &vars
->volumeCryptKey
[0], vars
->volumeCryptKeySize
);
2301 HIBLOG("IOPolledFilePollersSetEncryptionKey(%x) %ld\n", err
, vars
->volumeCryptKeySize
);
2302 if (kIOReturnSuccess
!= err
) {
2303 panic("IOPolledFilePollersSetEncryptionKey(0x%x)", err
);
2308 IOPolledFileSeek(vars
->fileVars
, gIOHibernateCurrentHeader
->image1Size
);
2310 // kick off the read ahead
2311 vars
->fileVars
->bufferHalf
= 0;
2312 vars
->fileVars
->bufferLimit
= 0;
2313 vars
->fileVars
->lastRead
= 0;
2314 vars
->fileVars
->readEnd
= gIOHibernateCurrentHeader
->imageSize
;
2315 vars
->fileVars
->bufferOffset
= vars
->fileVars
->bufferLimit
;
2316 vars
->fileVars
->cryptBytes
= 0;
2317 AbsoluteTime_to_scalar(&vars
->fileVars
->cryptTime
) = 0;
2319 err
= IOPolledFileRead(vars
->fileVars
, NULL
, 0, cryptvars
);
2320 vars
->fileVars
->bufferOffset
= vars
->fileVars
->bufferLimit
;
2323 HIBLOG("hibernate_machine_init reading\n");
2325 uint32_t * header
= (uint32_t *) src
;
2328 while (kIOReturnSuccess
== err
) {
2332 vm_offset_t ppnum
, compressedSize
;
2334 err
= IOPolledFileRead(vars
->fileVars
, src
, 8, cryptvars
);
2335 if (kIOReturnSuccess
!= err
) {
2342 // HIBPRINT("(%x, %x)\n", ppnum, count);
2348 for (page
= 0; page
< count
; page
++) {
2349 err
= IOPolledFileRead(vars
->fileVars
, (uint8_t *) &tag
, 4, cryptvars
);
2350 if (kIOReturnSuccess
!= err
) {
2354 compressedSize
= kIOHibernateTagLength
& tag
;
2355 if (kIOHibernateTagSignature
!= (tag
& ~kIOHibernateTagLength
)) {
2356 err
= kIOReturnIPCError
;
2360 err
= IOPolledFileRead(vars
->fileVars
, src
, (compressedSize
+ 3) & ~3, cryptvars
);
2361 if (kIOReturnSuccess
!= err
) {
2365 if (compressedSize
< page_size
) {
2366 decoOffset
= page_size
;
2367 clock_get_uptime(&startTime
);
2369 if (compressedSize
== 4) {
2373 s
= (uint32_t *)src
;
2374 d
= (uint32_t *)(uintptr_t)compressed
;
2376 for (i
= 0; i
< (int)(PAGE_SIZE
/ sizeof(int32_t)); i
++) {
2380 WKdm_decompress_new((WK_word
*) src
, (WK_word
*) compressed
, (WK_word
*) scratch
, compressedSize
);
2382 clock_get_uptime(&endTime
);
2383 ADD_ABSOLUTETIME(&compTime
, &endTime
);
2384 SUB_ABSOLUTETIME(&compTime
, &startTime
);
2385 compBytes
+= page_size
;
2390 sum
+= hibernate_sum_page((src
+ decoOffset
), ppnum
);
2391 err
= IOMemoryDescriptorReadToPhysical(vars
->srcBuffer
, decoOffset
, ptoa_64(ppnum
), page_size
);
2393 HIBLOG("IOMemoryDescriptorReadToPhysical [%ld] %x\n", (long)ppnum
, err
);
2401 if (0 == (8191 & pagesDone
)) {
2402 clock_get_uptime(&endTime
);
2403 SUB_ABSOLUTETIME(&endTime
, &allTime
);
2404 absolutetime_to_nanoseconds(endTime
, &nsec
);
2405 progressStamp
= nsec
/ 750000000ULL;
2406 if (progressStamp
!= lastProgressStamp
) {
2407 lastProgressStamp
= progressStamp
;
2408 HIBPRINT("pages %d (%d%%)\n", pagesDone
,
2409 (100 * pagesDone
) / gIOHibernateCurrentHeader
->pageCount
);
2414 if ((kIOReturnSuccess
== err
) && (pagesDone
== gIOHibernateCurrentHeader
->actualUncompressedPages
)) {
2415 err
= kIOReturnLockedRead
;
2418 if (kIOReturnSuccess
!= err
) {
2419 panic("Hibernate restore error %x", err
);
2422 gIOHibernateCurrentHeader
->actualImage2Sum
= sum
;
2423 gIOHibernateCompression
= gIOHibernateCurrentHeader
->compression
;
2425 clock_get_uptime(&endIOTime
);
2427 err
= IOPolledFilePollersClose(vars
->fileVars
, kIOPolledAfterSleepState
);
2429 clock_get_uptime(&endTime
);
2431 IOService::getPMRootDomain()->pmStatsRecordEvent(
2432 kIOPMStatsHibernateImageRead
| kIOPMStatsEventStartFlag
, allTime
);
2433 IOService::getPMRootDomain()->pmStatsRecordEvent(
2434 kIOPMStatsHibernateImageRead
| kIOPMStatsEventStopFlag
, endTime
);
2436 SUB_ABSOLUTETIME(&endTime
, &allTime
);
2437 absolutetime_to_nanoseconds(endTime
, &nsec
);
2439 SUB_ABSOLUTETIME(&endIOTime
, &startIOTime
);
2440 absolutetime_to_nanoseconds(endIOTime
, &nsecIO
);
2442 gIOHibernateStats
->kernelImageReadDuration
= nsec
/ 1000000ULL;
2443 gIOHibernateStats
->imagePages
= pagesDone
;
2445 HIBLOG("hibernate_machine_init pagesDone %d sum2 %x, time: %d ms, disk(0x%x) %qd Mb/s, ",
2446 pagesDone
, sum
, gIOHibernateStats
->kernelImageReadDuration
, kDefaultIOSize
,
2447 nsecIO
? ((((gIOHibernateCurrentHeader
->imageSize
- gIOHibernateCurrentHeader
->image1Size
) * 1000000000ULL) / 1024 / 1024) / nsecIO
) : 0);
2449 absolutetime_to_nanoseconds(compTime
, &nsec
);
2450 HIBLOG("comp bytes: %qd time: %qd ms %qd Mb/s, ",
2453 nsec
? (((compBytes
* 1000000000ULL) / 1024 / 1024) / nsec
) : 0);
2455 absolutetime_to_nanoseconds(vars
->fileVars
->cryptTime
, &nsec
);
2456 HIBLOG("crypt bytes: %qd time: %qd ms %qd Mb/s\n",
2457 vars
->fileVars
->cryptBytes
,
2459 nsec
? (((vars
->fileVars
->cryptBytes
* 1000000000ULL) / 1024 / 1024) / nsec
) : 0);
2461 KDBG(IOKDBG_CODE(DBG_HIBERNATE
, 2), pagesRead
, pagesDone
);
2464 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2467 IOHibernateSetWakeCapabilities(uint32_t capability
)
2469 if (kIOHibernateStateWakingFromHibernate
== gIOHibernateState
) {
2470 gIOHibernateStats
->wakeCapability
= capability
;
2472 if (kIOPMSystemCapabilityGraphics
& capability
) {
2473 vm_compressor_do_warmup();
2478 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
2481 IOHibernateSystemRestart(void)
2483 static uint8_t noteStore
[32] __attribute__((aligned(32)));
2484 IORegistryEntry
* regEntry
;
2485 const OSSymbol
* sym
;
2488 uintptr_t * smcVars
;
2493 data
= OSDynamicCast(OSData
, IOService::getPMRootDomain()->getProperty(kIOHibernateSMCVariablesKey
));
2498 smcVars
= (typeof(smcVars
))data
->getBytesNoCopy();
2499 smcBytes
= (typeof(smcBytes
))smcVars
[1];
2501 if (len
> sizeof(noteStore
)) {
2502 len
= sizeof(noteStore
);
2504 noteProp
= OSData::withCapacity(3 * sizeof(element
));
2509 noteProp
->appendBytes(&element
, sizeof(element
));
2510 element
= crc32(0, smcBytes
, len
);
2511 noteProp
->appendBytes(&element
, sizeof(element
));
2513 bcopy(smcBytes
, noteStore
, len
);
2514 element
= (addr64_t
) ¬eStore
[0];
2515 element
= (element
& page_mask
) | ptoa_64(pmap_find_phys(kernel_pmap
, element
));
2516 noteProp
->appendBytes(&element
, sizeof(element
));
2518 if (!gIOOptionsEntry
) {
2519 regEntry
= IORegistryEntry::fromPath("/options", gIODTPlane
);
2520 gIOOptionsEntry
= OSDynamicCast(IODTNVRAM
, regEntry
);
2521 if (regEntry
&& !gIOOptionsEntry
) {
2522 regEntry
->release();
2526 sym
= OSSymbol::withCStringNoCopy(kIOHibernateBootNoteKey
);
2527 if (gIOOptionsEntry
&& sym
) {
2528 gIOOptionsEntry
->setProperty(sym
, noteProp
);
2531 noteProp
->release();